rapidkit 0.40.1 → 0.41.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/README.md +48 -7
  2. package/contracts/agent-customization-pack.v1.json +52 -2
  3. package/contracts/extension-cli-compatibility.v1.json +14 -2
  4. package/contracts/runtime-command-surface.v1.json +7 -1
  5. package/contracts/workspace-intelligence/agent-action-outcome.v1.json +38 -0
  6. package/contracts/workspace-intelligence/blocker-resolution.v1.json +65 -0
  7. package/contracts/workspace-intelligence/doctor-fix-result.v1.json +34 -0
  8. package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +91 -0
  9. package/contracts/workspace-intelligence/workspace-contract-verify.v1.json +51 -0
  10. package/contracts/workspace-intelligence/workspace-dependency-graph.v1.json +61 -1
  11. package/contracts/workspace-intelligence/workspace-explain.v1.json +31 -0
  12. package/contracts/workspace-intelligence/workspace-intelligence-history.v1.json +36 -0
  13. package/contracts/workspace-intelligence/workspace-operational-skill.v1.json +37 -0
  14. package/contracts/workspace-intelligence/workspace-skills-index.v1.json +27 -0
  15. package/dist/analyze-QYHMGLSG.js +1 -0
  16. package/dist/autopilot-release-AHMQEUFH.js +1 -0
  17. package/dist/chunk-33LR2QEM.js +2 -0
  18. package/dist/chunk-3PTJID76.js +2 -0
  19. package/dist/chunk-46AGNYI7.js +50 -0
  20. package/dist/chunk-64RTZBHU.js +2 -0
  21. package/dist/chunk-AQ4XZZC6.js +1 -0
  22. package/dist/{chunk-RXWM5DSC.js → chunk-BFEBZABL.js} +3 -3
  23. package/dist/{chunk-3YLMCP3V.js → chunk-CDCYRBAY.js} +1 -1
  24. package/dist/chunk-CDPR2YKL.js +13 -0
  25. package/dist/chunk-CKXJR3YT.js +7 -0
  26. package/dist/chunk-E5ZVQL3C.js +13 -0
  27. package/dist/chunk-ELU3G6DQ.js +9 -0
  28. package/dist/chunk-EN6YCX36.js +1 -0
  29. package/dist/chunk-FMBSON6H.js +33 -0
  30. package/dist/chunk-GBJBQ43T.js +1 -0
  31. package/dist/chunk-ICGWHIMK.js +1 -0
  32. package/dist/{chunk-4FJQWL7P.js → chunk-ITJ6RKUW.js} +3 -3
  33. package/dist/{workspace-graph-ICB7OVAZ.js → chunk-JEI6BTZI.js} +1 -1
  34. package/dist/{chunk-G76C74EV.js → chunk-JU3VNLTY.js} +1 -1
  35. package/dist/chunk-JW2FSKT3.js +2 -0
  36. package/dist/chunk-KIUSCFHF.js +1 -0
  37. package/dist/chunk-LKX3L7TE.js +2 -0
  38. package/dist/chunk-MIWDCR6I.js +2 -0
  39. package/dist/{chunk-6G2KSHP6.js → chunk-OLDPVVSV.js} +1 -1
  40. package/dist/{chunk-4Q2ZZKGB.js → chunk-PCXSTKZ5.js} +1 -1
  41. package/dist/{chunk-6KD5F6LX.js → chunk-Q2KZIBV4.js} +1 -1
  42. package/dist/{chunk-ERCD6NFF.js → chunk-RSYUNEH7.js} +13 -13
  43. package/dist/chunk-TJN7G2MA.js +1 -0
  44. package/dist/chunk-UQR6G7KH.js +32 -0
  45. package/dist/chunk-VMJA36WD.js +1 -0
  46. package/dist/chunk-WRMCPKGA.js +1 -0
  47. package/dist/{create-XVDDQA42.js → create-RNP5ACQL.js} +1 -1
  48. package/dist/demo-kit-N5U3NGAE.js +149 -0
  49. package/dist/{doctor-UOLOGJ2Z.js → doctor-XM6QDTDC.js} +1 -1
  50. package/dist/{dotnet-webapi-clean-RTBRPDPL.js → dotnet-webapi-clean-K33C77EI.js} +1 -1
  51. package/dist/{gofiber-standard-UGIRKPKL.js → gofiber-standard-BQ4HCXL2.js} +1 -1
  52. package/dist/{gogin-standard-HJ7SPFNT.js → gogin-standard-PUBCYW3A.js} +1 -1
  53. package/dist/index.d.ts +45 -7
  54. package/dist/index.js +145 -127
  55. package/dist/{pipeline-XK62WL4D.js → pipeline-DH6Z47O4.js} +1 -1
  56. package/dist/platform-capabilities-TSLK667K.js +1 -0
  57. package/dist/{pythonRapidkitExec-MNWRC4F2.js → pythonRapidkitExec-SGKW76XM.js} +1 -1
  58. package/dist/{springboot-standard-IWJSVDLZ.js → springboot-standard-XFVQI37R.js} +1 -1
  59. package/dist/{workspace-L4ITCKMM.js → workspace-E554C5SM.js} +1 -1
  60. package/dist/workspace-agent-sync-2HRPM5ZD.js +1 -0
  61. package/dist/{workspace-context-NMMQMHNU.js → workspace-context-VJTXW3K4.js} +1 -1
  62. package/dist/workspace-contract-OO4GMENV.js +1 -0
  63. package/dist/workspace-explain-3WSJLIJ6.js +1 -0
  64. package/dist/workspace-explain-contract-24RQ7KIW.js +1 -0
  65. package/dist/workspace-feedback-65NR3EZH.js +1 -0
  66. package/dist/{workspace-foundation-HNIRAIBF.js → workspace-foundation-LISDH53T.js} +1 -1
  67. package/dist/workspace-graph-2A5THUCI.js +1 -0
  68. package/dist/workspace-history-VPDADQKG.js +1 -0
  69. package/dist/{workspace-intelligence-64IWAYHS.js → workspace-intelligence-E3KXEZCM.js} +1 -1
  70. package/dist/workspace-mcp-serve-RFYDCA2L.js +3 -0
  71. package/dist/workspace-model-YL7W3573.js +1 -0
  72. package/dist/workspace-registry-summary-X5WRUU3T.js +1 -0
  73. package/dist/workspace-run-GCIQD73R.js +1 -0
  74. package/dist/workspace-verify-NRYH7RNB.js +1 -0
  75. package/dist/workspace-watch-H2AETGFI.js +1 -0
  76. package/docs/DEVELOPMENT.md +1 -1
  77. package/docs/OPEN_SOURCE_USER_SCENARIOS.md +1 -1
  78. package/docs/README.md +1 -1
  79. package/docs/commands-reference.md +10 -2
  80. package/docs/contracts/ARTIFACT_CATALOG.md +3 -1
  81. package/docs/contracts/NAMING_AND_COEXISTENCE.md +58 -0
  82. package/docs/workspace-run.md +25 -1
  83. package/package.json +7 -3
  84. package/scripts/enterprise-package-smoke.mjs +427 -0
  85. package/scripts/prepack-enterprise.mjs +40 -0
  86. package/templates/generator.js +175 -0
  87. package/templates/kits/fastapi-ddd/README.md.j2 +122 -0
  88. package/templates/kits/fastapi-ddd/common/env.example.j2 +10 -0
  89. package/templates/kits/fastapi-ddd/env.example.j2 +1 -0
  90. package/templates/kits/fastapi-ddd/pyproject.toml.j2 +64 -0
  91. package/templates/kits/fastapi-ddd/src/__init__.py.j2 +3 -0
  92. package/templates/kits/fastapi-ddd/src/app/__init__.py.j2 +11 -0
  93. package/templates/kits/fastapi-ddd/src/app/application/__init__.py.j2 +5 -0
  94. package/templates/kits/fastapi-ddd/src/app/application/interfaces.py.j2 +43 -0
  95. package/templates/kits/fastapi-ddd/src/app/application/use_cases/__init__.py.j2 +6 -0
  96. package/templates/kits/fastapi-ddd/src/app/application/use_cases/health.py.j2 +14 -0
  97. package/templates/kits/fastapi-ddd/src/app/application/use_cases/notes.py.j2 +24 -0
  98. package/templates/kits/fastapi-ddd/src/app/config/__init__.py.j2 +16 -0
  99. package/templates/kits/fastapi-ddd/src/app/domain/__init__.py.j2 +3 -0
  100. package/templates/kits/fastapi-ddd/src/app/domain/models/__init__.py.j2 +6 -0
  101. package/templates/kits/fastapi-ddd/src/app/domain/models/health.py.j2 +16 -0
  102. package/templates/kits/fastapi-ddd/src/app/domain/models/note.py.j2 +27 -0
  103. package/templates/kits/fastapi-ddd/src/app/infrastructure/__init__.py.j2 +5 -0
  104. package/templates/kits/fastapi-ddd/src/app/infrastructure/repositories/__init__.py.j2 +6 -0
  105. package/templates/kits/fastapi-ddd/src/app/infrastructure/repositories/health.py.j2 +17 -0
  106. package/templates/kits/fastapi-ddd/src/app/infrastructure/repositories/notes.py.j2 +28 -0
  107. package/templates/kits/fastapi-ddd/src/app/main.py.j2 +61 -0
  108. package/templates/kits/fastapi-ddd/src/app/presentation/__init__.py.j2 +3 -0
  109. package/templates/kits/fastapi-ddd/src/app/presentation/api/__init__.py.j2 +5 -0
  110. package/templates/kits/fastapi-ddd/src/app/presentation/api/dependencies/__init__.py.j2 +19 -0
  111. package/templates/kits/fastapi-ddd/src/app/presentation/api/router.py.j2 +10 -0
  112. package/templates/kits/fastapi-ddd/src/app/presentation/api/routes/__init__.py.j2 +5 -0
  113. package/templates/kits/fastapi-ddd/src/app/presentation/api/routes/health.py.j2 +27 -0
  114. package/templates/kits/fastapi-ddd/src/app/presentation/api/routes/notes.py.j2 +50 -0
  115. package/templates/kits/fastapi-ddd/src/app/shared/__init__.py.j2 +5 -0
  116. package/templates/kits/fastapi-ddd/src/app/shared/result.py.j2 +28 -0
  117. package/templates/kits/fastapi-ddd/src/cli.py.j2 +167 -0
  118. package/templates/kits/fastapi-ddd/src/main.py.j2 +35 -0
  119. package/templates/kits/fastapi-ddd/src/modules/__init__.py.j2 +3 -0
  120. package/templates/kits/fastapi-ddd/src/routing/__init__.py.j2 +13 -0
  121. package/templates/kits/fastapi-ddd/src/routing/health.py.j2 +7 -0
  122. package/templates/kits/fastapi-ddd/src/routing/notes.py.j2 +7 -0
  123. package/templates/kits/fastapi-ddd/tests/__init__.py.j2 +1 -0
  124. package/templates/kits/fastapi-ddd/tests/test_app_factory.py.j2 +22 -0
  125. package/templates/kits/fastapi-ddd/tests/test_health.py.j2 +17 -0
  126. package/templates/kits/fastapi-ddd/tests/test_notes.py.j2 +27 -0
  127. package/templates/kits/fastapi-standard/README.md.j2 +145 -0
  128. package/templates/kits/fastapi-standard/common/env.example.j2 +10 -0
  129. package/templates/kits/fastapi-standard/env.example.j2 +1 -0
  130. package/templates/kits/fastapi-standard/pyproject.toml.j2 +64 -0
  131. package/templates/kits/fastapi-standard/src/__init__.py.j2 +3 -0
  132. package/templates/kits/fastapi-standard/src/cli.py.j2 +168 -0
  133. package/templates/kits/fastapi-standard/src/main.py.j2 +66 -0
  134. package/templates/kits/fastapi-standard/src/modules/__init__.py.j2 +3 -0
  135. package/templates/kits/fastapi-standard/src/routing/__init__.py.j2 +16 -0
  136. package/templates/kits/fastapi-standard/src/routing/examples.py.j2 +71 -0
  137. package/templates/kits/fastapi-standard/src/routing/health.py.j2 +22 -0
  138. package/templates/kits/fastapi-standard/tests/__init__.py.j2 +1 -0
  139. package/templates/kits/fastapi-standard/tests/test_examples.py.j2 +29 -0
  140. package/templates/kits/fastapi-standard/tests/test_health.py.j2 +17 -0
  141. package/templates/kits/nestjs-standard/Dockerfile.j2 +41 -0
  142. package/templates/kits/nestjs-standard/README.md.j2 +139 -0
  143. package/templates/kits/nestjs-standard/docker-compose.yml.j2 +94 -0
  144. package/templates/kits/nestjs-standard/docs/README.md.j2 +15 -0
  145. package/templates/kits/nestjs-standard/env.example.j2 +18 -0
  146. package/templates/kits/nestjs-standard/eslint.config.cjs.j2 +9 -0
  147. package/templates/kits/nestjs-standard/jest.config.ts.j2 +22 -0
  148. package/templates/kits/nestjs-standard/nest-cli.json.j2 +10 -0
  149. package/templates/kits/nestjs-standard/package.json.j2 +101 -0
  150. package/templates/kits/nestjs-standard/src/app.controller.ts.j2 +14 -0
  151. package/templates/kits/nestjs-standard/src/app.module.ts.j2 +26 -0
  152. package/templates/kits/nestjs-standard/src/app.service.ts.j2 +16 -0
  153. package/templates/kits/nestjs-standard/src/auth/auth.controller.ts.j2 +20 -0
  154. package/templates/kits/nestjs-standard/src/auth/auth.module.ts.j2 +13 -0
  155. package/templates/kits/nestjs-standard/src/auth/auth.service.ts.j2 +6 -0
  156. package/templates/kits/nestjs-standard/src/auth/entities/token.entity.ts.j2 +3 -0
  157. package/templates/kits/nestjs-standard/src/auth/entities/user.entity.ts.j2 +3 -0
  158. package/templates/kits/nestjs-standard/src/auth/entities/webauthn.entity.ts.j2 +3 -0
  159. package/templates/kits/nestjs-standard/src/config/configuration.ts.j2 +85 -0
  160. package/templates/kits/nestjs-standard/src/config/index.ts.j2 +2 -0
  161. package/templates/kits/nestjs-standard/src/config/validation.ts.j2 +21 -0
  162. package/templates/kits/nestjs-standard/src/examples/dto/create-note.dto.ts.j2 +11 -0
  163. package/templates/kits/nestjs-standard/src/examples/examples.controller.ts.j2 +24 -0
  164. package/templates/kits/nestjs-standard/src/examples/examples.module.ts.j2 +10 -0
  165. package/templates/kits/nestjs-standard/src/examples/examples.service.ts.j2 +33 -0
  166. package/templates/kits/nestjs-standard/src/main.ts.j2 +53 -0
  167. package/templates/kits/nestjs-standard/src/modules/index.ts.j2 +25 -0
  168. package/templates/kits/nestjs-standard/test/app.controller.spec.ts.j2 +24 -0
  169. package/templates/kits/nestjs-standard/test/app.e2e-spec.ts.j2 +60 -0
  170. package/templates/kits/nestjs-standard/test/examples.controller.spec.ts.j2 +28 -0
  171. package/templates/kits/nestjs-standard/test/jest-e2e.json.j2 +15 -0
  172. package/templates/kits/nestjs-standard/tsconfig.build.json.j2 +12 -0
  173. package/templates/kits/nestjs-standard/tsconfig.json.j2 +26 -0
  174. package/dist/analyze-RHQM4AB2.js +0 -1
  175. package/dist/autopilot-release-OJTLXPMX.js +0 -1
  176. package/dist/chunk-5VBRMLRU.js +0 -7
  177. package/dist/chunk-7VI4U7Q5.js +0 -2
  178. package/dist/chunk-FV5A3N3I.js +0 -2
  179. package/dist/chunk-GDGATWR5.js +0 -2
  180. package/dist/chunk-GOM3RFB3.js +0 -2
  181. package/dist/chunk-GX7UU7LL.js +0 -33
  182. package/dist/chunk-KYH364KQ.js +0 -1
  183. package/dist/chunk-OWNGSAO3.js +0 -2
  184. package/dist/chunk-QPEBI6AB.js +0 -2
  185. package/dist/chunk-TYZPPUBH.js +0 -1
  186. package/dist/chunk-VQMZC5TC.js +0 -9
  187. package/dist/chunk-WHCON2VN.js +0 -50
  188. package/dist/chunk-X7PWDIQW.js +0 -1
  189. package/dist/chunk-Z5LKRG57.js +0 -1
  190. package/dist/chunk-ZWKLRZE5.js +0 -13
  191. package/dist/demo-kit-RWGOEDW4.js +0 -141
  192. package/dist/workspace-agent-sync-G7JU77IK.js +0 -25
  193. package/dist/workspace-contract-D5O4OZD5.js +0 -1
  194. package/dist/workspace-history-LHUTLE3S.js +0 -1
  195. package/dist/workspace-model-SDHH5RBC.js +0 -1
  196. package/dist/workspace-registry-summary-MIPHVB56.js +0 -1
  197. package/dist/workspace-run-SPP32MPV.js +0 -1
  198. package/dist/workspace-verify-6Q6MGRG6.js +0 -1
  199. package/dist/workspace-watch-JDXVGW4H.js +0 -1
@@ -0,0 +1,28 @@
1
+ import { Test, TestingModule } from '@nestjs/testing';
2
+
3
+ import { ExamplesController } from '../src/examples/examples.controller';
4
+ import { ExamplesService } from '../src/examples/examples.service';
5
+
6
+ describe('ExamplesController', () => {
7
+ let controller: ExamplesController;
8
+
9
+ beforeEach(async () => {
10
+ const module: TestingModule = await Test.createTestingModule({
11
+ controllers: [ExamplesController],
12
+ providers: [ExamplesService],
13
+ }).compile();
14
+
15
+ controller = module.get<ExamplesController>(ExamplesController);
16
+ });
17
+
18
+ it('creates and retrieves notes', () => {
19
+ const created = controller.create({ title: 'spec', body: 'covered by tests' });
20
+ expect(created).toMatchObject({ id: 1, title: 'spec' });
21
+
22
+ const list = controller.findAll();
23
+ expect(list).toHaveLength(1);
24
+
25
+ const single = controller.findOne(created.id);
26
+ expect(single).toMatchObject({ id: created.id, title: 'spec' });
27
+ });
28
+ });
@@ -0,0 +1,15 @@
1
+ {
2
+ "moduleFileExtensions": ["js", "json", "ts"],
3
+ "rootDir": "../",
4
+ "testEnvironment": "node",
5
+ "testRegex": ".e2e-spec.ts$",
6
+ "transform": {
7
+ "^.+\\.ts$": "ts-jest"
8
+ },
9
+ "setupFiles": ["dotenv/config"],
10
+ "moduleNameMapper": {
11
+ "^@config/(.*)$": "<rootDir>/src/config/$1",
12
+ "^@modules/(.*)$": "<rootDir>/src/modules/$1",
13
+ "^@shared/(.*)$": "<rootDir>/src/shared/$1"
14
+ }
15
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "declaration": true,
6
+ "sourceMap": false,
7
+ "removeComments": true,
8
+ "incremental": false
9
+ },
10
+ "exclude": ["node_modules", "test", "src/**/*.spec.ts", "src/**/*.e2e-spec.ts"],
11
+ "include": ["src/.rapidkit/**/*.ts", "src/**/*.ts"]
12
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "declaration": true,
5
+ "removeComments": true,
6
+ "emitDecoratorMetadata": true,
7
+ "experimentalDecorators": true,
8
+ "allowSyntheticDefaultImports": true,
9
+ "target": "es2021",
10
+ "sourceMap": true,
11
+ "outDir": "./dist",
12
+ "baseUrl": "./",
13
+ "incremental": true,
14
+ "strict": true,
15
+ "skipLibCheck": true,
16
+ "moduleResolution": "node",
17
+ "esModuleInterop": true,
18
+ "paths": {
19
+ "@config/*": ["src/config/*"],
20
+ "@modules/*": ["src/modules/*"],
21
+ "@shared/*": ["src/shared/*"]
22
+ }
23
+ },
24
+ "exclude": ["node_modules", "dist"],
25
+ "include": ["src/.rapidkit/**/*.ts", "src/**/*.ts", "test/**/*.ts"]
26
+ }
@@ -1 +0,0 @@
1
- export{b as printAnalyzeReport,a as runAnalyze}from'./chunk-VQMZC5TC.js';
@@ -1 +0,0 @@
1
- export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-5VBRMLRU.js';
@@ -1,7 +0,0 @@
1
- import {a}from'./chunk-7VI4U7Q5.js';import {a as a$1,d}from'./chunk-FV5A3N3I.js';import {a as a$2}from'./chunk-KMUWWZRT.js';import l from'chalk';import Y from'fs';import y from'path';import {execa}from'execa';var Z="autopilot-release-last-run.json",ee="autopilot-release.json";function $(s){try{return JSON.parse(s)}catch{return null}}function ge(s){let t=y.resolve(s),o=a$2(t);if(!o)throw new Error("No RapidKit workspace found in current directory or parents");return o}async function b(s,t){let o=process.argv[1];if(!o)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for autopilot execution.",crashed:true};try{let a=await execa(process.execPath,[o,...s],{cwd:t,reject:false,env:{...process.env,RAPIDKIT_AUTOPILOT_CHILD:"1"}});return {exitCode:Number(a.exitCode??1),stdout:a.stdout,stderr:a.stderr,crashed:false}}catch(a){return {exitCode:1,stdout:"",stderr:a instanceof Error?a.message:String(a),crashed:true}}}function te(s){let t=s.toLowerCase();return t==="pass"?"pass":t==="warn"?"warn":t==="fail"?"fail":"warn"}function se(s){return s.summary.failed>0||s.gates.results.some(t=>t.status==="fail")?"fail":s.gates.results.some(t=>t.status==="warn")?"warn":"pass"}function we(s){let t=s.filter(a=>a.status!=="skipped");if(t.length===0)return 100;let o=t.reduce((a,e)=>e.status==="pass"?a+1:e.status==="warn"?a+.6:a,0);return Math.round(o/t.length*100)}function he(s){return s.executionError?["Re-run: npx rapidkit autopilot release --mode audit --json","Inspect .rapidkit/reports/autopilot-release-last-run.json for execution failure details"]:s.blockers.length>0?["Run: npx rapidkit doctor workspace --plan","Run: npx rapidkit readiness --json --strict","Run: npx rapidkit workspace run test --affected --strict"]:s.hasWarnings&&s.mode!=="enforce"?["Review warning-level findings in autopilot report","Optionally run: npx rapidkit autopilot release --mode safe-fix"]:["Workspace is release-ready based on current autopilot policy"]}async function U(s,t){await Y.promises.mkdir(y.dirname(s),{recursive:true}),await Y.promises.writeFile(s,`${JSON.stringify(t,null,2)}
2
- `,"utf-8");}async function je(s){let t=ge(s.workspacePath),o=s.mode,a$2=[],e=[],F,B,C,O,J,G=0,f=false,I=0,T=0,D=-1,N=-1,c="skipped",p="skipped",re=o==="enforce"?["doctor","workspace","--json","--strict"]:["doctor","workspace","--json","--ci"];if(s.skipPipelineStages)a$2.push({name:"doctor-workspace",status:"skipped",durationMs:0,summary:"doctor stage skipped (pipeline already executed)"},{name:"analyze",status:"skipped",durationMs:0,summary:"analyze stage skipped (pipeline already executed)"},{name:"readiness",status:"skipped",durationMs:0,summary:"readiness stage skipped (pipeline already executed)"});else {let r=Date.now(),i=await b([...re],t),m=Date.now()-r;if(c="pass",i.crashed)c="fail",f=true,e.push(`doctor workspace execution error: ${i.stderr||"unknown error"}`);else if(i.exitCode===1)c="fail",e.push("doctor workspace command failed or reported errors");else if(i.exitCode===2)c="warn",e.push("doctor workspace reported warnings");else if(i.exitCode!==0)c="fail",e.push("doctor workspace command failed");else {let d=$(i.stdout),j=d&&d.healthScore&&typeof d.healthScore=="object"?d.healthScore:{},k=Number(j.errors??0),E=Number(j.warnings??0);Number.isFinite(k)&&k>0?(c="fail",e.push(`doctor workspace reports ${k} error(s)`)):Number.isFinite(E)&&E>0&&(c="warn");}D=a$2.push({name:"doctor-workspace",status:c,durationMs:m,summary:c==="pass"?"doctor workspace passed":c==="warn"?"doctor workspace reported warnings":"doctor workspace reported errors"})-1,o==="enforce"&&c==="warn"&&e.push("doctor workspace reported warnings under enforce mode");let g=Date.now(),w=await b(["analyze","--json"],t),v=Date.now()-g;B=y.join(t,".rapidkit","reports","analyze-last-run.json");let n="pass";if(w.crashed)n="fail",f=true,e.push(`analyze execution error: ${w.stderr||"unknown error"}`);else if(w.exitCode!==0)n=w.exitCode===2?"warn":"fail",e.push(w.exitCode===2?"analyze reported needs-attention verdict":"analyze command failed or reported blocked verdict");else {let d=$(w.stdout),j=d&&d.summary&&typeof d.summary=="object"?d.summary:{},k=String(j.verdict??"ready");k==="blocked"?(n="fail",e.push("analyze reported blocked verdict")):k==="needs-attention"&&(n="warn");}a$2.push({name:"analyze",status:n,durationMs:v,summary:n==="pass"?"analyze passed":n==="warn"?"analyze reported needs-attention":"analyze reported blocked verdict"}),o==="enforce"&&n==="warn"&&e.push("analyze reported warnings under enforce mode");let P=Date.now(),h=await b(["readiness","--json"],t),R=Date.now()-P;if(p="fail",h.crashed)p="fail",f=true,e.push(`readiness execution error: ${h.stderr||"unknown error"}`);else if(h.exitCode!==0)p="fail",e.push("readiness command failed");else {let d=$(h.stdout),j=String(d?.overallStatus??"fail");if(p=te(j),typeof d?.evidencePath=="string"&&d.evidencePath.trim().length>0&&(F=d.evidencePath),p==="fail"){let k=Array.isArray(d?.blockingReasons)?d?.blockingReasons.filter(E=>typeof E=="string"):[];k.length>0?e.push(...k.map(E=>`readiness: ${E}`)):e.push("readiness overall status is fail");}}N=a$2.push({name:"readiness",status:p,durationMs:R,summary:`readiness overall status is ${p}`})-1,o==="enforce"&&p==="warn"&&e.push("readiness reported warnings under enforce mode");}let ae=Date.now(),M=await b(["doctor","workspace","--plan","--json"],t),oe=Date.now()-ae,S="warn";if(M.crashed)S="fail",f=true,e.push(`doctor remediation plan execution error: ${M.stderr||"unknown error"}`);else if(M.exitCode!==0)S="fail",e.push("doctor remediation plan command failed");else {let r=$(M.stdout),i=r&&r.remediationPlan&&typeof r.remediationPlan=="object"?r.remediationPlan:null,m=Number(i?.totalSteps??0),g=Number(i?.executableSteps??0);Number.isFinite(m)&&m>0&&(I=m),Number.isFinite(g)&&g>0&&(T=g),Number.isFinite(m)&&m===0?S="pass":S="warn";}if(a$2.push({name:"remediation-plan",status:S,durationMs:oe,summary:S==="pass"?"no remediation steps required":"remediation steps available"}),o==="enforce"&&S==="warn"&&e.push("remediation plan has pending steps under enforce mode"),o==="safe-fix"){let r=Date.now(),i=await b(["doctor","workspace","--apply"],t),m=Date.now()-r,g=i.crashed||i.exitCode!==0?"fail":"pass";if(i.crashed)f=true,e.push(`doctor remediation apply execution error: ${i.stderr||"unknown error"}`);else if(g==="fail")e.push("doctor remediation apply failed");else {G=T>0?T:I>0?I:1;let w=await b(["doctor","workspace","--json"],t);if(w.crashed)c="fail",f=true,e.push(`post-apply doctor execution error: ${w.stderr||"unknown error"}`);else if(w.exitCode!==0)c="fail",e.push("post-apply doctor workspace command failed");else {let n=$(w.stdout),P=n&&n.healthScore&&typeof n.healthScore=="object"?n.healthScore:{},h=Number(P.errors??0),R=Number(P.warnings??0);Number.isFinite(h)&&h>0?(c="fail",e.push(`post-apply doctor reports ${h} error(s)`)):Number.isFinite(R)&&R>0?c="warn":c="pass";}D>=0&&(a$2[D].status=c,a$2[D].summary=`doctor workspace post-apply status is ${c}`);let v=await b(["readiness","--json"],t);if(v.crashed)p="fail",f=true,e.push(`post-apply readiness execution error: ${v.stderr||"unknown error"}`);else if(v.exitCode!==0)p="fail",e.push("post-apply readiness command failed");else {let n=$(v.stdout),P=String(n?.overallStatus??"fail");if(p=te(P),typeof n?.evidencePath=="string"&&n.evidencePath.trim().length>0&&(F=n.evidencePath),p==="fail"){let h=Array.isArray(n?.blockingReasons)?n?.blockingReasons.filter(R=>typeof R=="string"):[];h.length>0?e.push(...h.map(R=>`post-apply readiness: ${R}`)):e.push("post-apply readiness overall status is fail");}}N>=0&&(a$2[N].status=p,a$2[N].summary=`readiness post-apply overall status is ${p}`);}a$2.push({name:"remediation-apply",status:g,durationMs:m,summary:g==="pass"?"safe remediation apply completed":"safe remediation apply failed"});}else a$2.push({name:"remediation-apply",status:"skipped",durationMs:0,summary:"remediation apply is skipped for this mode"});let ne=Date.now(),x="pass",A="workspace test/build completed for selected projects";try{let r=await a({workspacePath:t,stage:"test",affected:true,since:s.since,parallel:s.parallel,maxWorkers:s.maxWorkers,strict:true,json:true,enforceGates:false});C=y.join(t,".rapidkit","reports",a$1),await d(t,r),O=C;let i=se(r);if(i==="fail")x="fail",A="workspace test stage failed for selected projects",e.push("workspace run test failed for selected projects");else {i==="warn"&&(x="warn",A="workspace test stage completed with warnings",o==="enforce"&&e.push("workspace run test reported warnings under enforce mode"));let m=await a({workspacePath:t,stage:"build",affected:true,since:s.since,parallel:s.parallel,maxWorkers:s.maxWorkers,strict:true,json:true,enforceGates:false});await d(t,m),J=C;let g=se(m);g==="fail"?(x="fail",A="workspace build stage failed for selected projects",e.push("workspace run build failed for selected projects")):g==="warn"&&(x="warn",A="workspace test/build completed with warnings",o==="enforce"&&e.push("workspace run test/build reported warnings under enforce mode"));}}catch(r){x="fail",A="workspace test/build orchestration failed",f=true,e.push(`workspace run orchestration error: ${r instanceof Error?r.message:String(r)}`);}let ie=Date.now()-ne;a$2.push({name:"workspace-run-test-build",status:x,durationMs:ie,summary:A});let z=a$2.filter(r=>r.status==="warn").length,le=a$2.filter(r=>r.status==="fail").length,L=o==="enforce"?a$2.some(r=>r.status==="warn"||r.status==="fail"):le>0,W=[...new Set(e)],ce=f||L?Math.max(1,W.length):0,de=we(a$2),pe=f||L?"blocked":z>0?"partial":"approved",ue=f?3:L?1:z>0?2:0,fe=he({mode:o,executionError:f,blockers:W,hasWarnings:z>0}),V=y.join(t,".rapidkit","reports"),H=y.join(V,Z),q=y.join(V,ee),u={schemaVersion:"autopilot-release-v1",generatedAt:new Date().toISOString(),workspacePath:t,mode:o,summary:{releaseScore:de,verdict:pe,blockers:ce,warnings:z,safeFixesApplied:G,manualActions:W.length,exitCode:ue},stages:a$2,blockingReasons:W,nextActions:fe,artifacts:{reportPath:H,aliasEvidencePath:q,analyzeEvidencePath:B,readinessEvidencePath:F,workspaceRunEvidencePath:C,workspaceRunTestPath:O,workspaceRunBuildPath:J},enterpriseControls:{jsonReady:true,evidencePath:`.rapidkit/reports/${Z}`,aliasEvidencePath:`.rapidkit/reports/${ee}`}};if(await U(H,u),await U(q,u),s.output&&await U(y.resolve(s.output),u),!s.json){console.log(l.bold.cyan(`
3
- \u{1F680} RapidKit Autopilot Release
4
- `)),console.log(l.bold(`Workspace: ${l.cyan(y.basename(t))}`)),console.log(l.gray(`Path: ${t}`)),console.log(l.white(`Mode: ${o}`)),console.log(l.white(`Verdict: ${u.summary.verdict==="approved"?l.green("approved"):u.summary.verdict==="partial"?l.yellow("partial"):l.red("blocked")}`)),console.log(l.white(`Release score: ${u.summary.releaseScore}`));for(let r of u.stages){let i=r.status==="pass"?l.green("PASS"):r.status==="warn"?l.yellow("WARN"):r.status==="skipped"?l.gray("SKIP"):l.red("FAIL");console.log(` - ${r.name}: ${i} ${r.summary} (${r.durationMs}ms)`);}if(u.blockingReasons.length>0){console.log(l.bold.red(`
5
- Blocking reasons:`));for(let r of u.blockingReasons)console.log(l.red(` - ${r}`));}if(u.nextActions.length>0){console.log(l.bold(`
6
- Next actions:`));for(let r of u.nextActions)console.log(l.gray(` - ${r}`));}console.log(l.gray(`
7
- Report: ${u.artifacts.reportPath}`));}return u}export{Z as a,ee as b,je as c};
@@ -1,2 +0,0 @@
1
- import {a,b as b$1,d}from'./chunk-FV5A3N3I.js';import {d as d$1}from'./chunk-S5KTATOU.js';import {n,q as q$1,g}from'./chunk-YBS2HGO3.js';import {h,i,f,e}from'./chunk-UZW5QFRW.js';import {a as a$1}from'./chunk-VKLL63TL.js';import M from'fs';import b from'path';import v from'chalk';import {execa}from'execa';function pe(e){return M.existsSync(b.join(e,"bun.lock"))||M.existsSync(b.join(e,"bunfig.toml"))?"bun":M.existsSync(b.join(e,"pnpm-lock.yaml"))?"pnpm":M.existsSync(b.join(e,"yarn.lock"))?"yarn":(M.existsSync(b.join(e,"package-lock.json")),"npm")}function me(e,r,t=pe(e)){return t==="npm"?`npm run ${r}`:`${t} run ${r}`}function ge(e,r=pe(e)){return `${r} install`}var Ae={"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:[]}}},Te={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 fe(e$1,r,t){if(r){let o=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),a=e(r),m=`${e$1}-${a==="gofiber"?"fiber":a==="gogin"?"gin":a==="dotnet"?"aspnetcore":a!=="unknown"?a:o==="fiber"?"fiber":o==="aspnetcore"||o==="asp-net-core"?"aspnetcore":o}`,g=Ae[m];if(g&&g.commands[t])return g.commands[t]}let n=Te[t]?.[e$1]??[];return n.length>0?n[0]:void 0}var Ne={test:"test",build:"build",start:"start"};function J(e){if(e.stage==="init")return e.runtime==="node"?ge(e.projectPath):fe(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=Ne[e.stage];if(r){let t=g(e.projectPath,r,{framework:e.framework});if(t)return me(e.projectPath,t.scriptName)}}return fe(e.runtime,e.framework,e.stage)}function Ie(e){let r=h(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,o)=>o.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function ye(e){return Ie(e).primary}function he(e,r){if(!e)return "unknown";r||(r={setup:["ModuleNotFoundError","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[t,n]of Object.entries(r))for(let o of n)if(new RegExp(o,"i").test(e))return t;return "unknown"}async function G(e){let r=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(r))return {valid:true};try{let n=process.platform==="win32"?"where":"which";if((await execa(n,[r],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${r}' not found or not executable`}}function ke(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(o=>["init","test","build","start"].includes(o))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}var we={init:"init",test:"test",build:"build",start:"start"};function We(e){return e in we?we[e]:null}function be(e,r,t=q$1(e)){let n=We(r);if(!n)return {supported:false,reason:`Workspace stage "${r}" is not part of the RapidKit fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No RapidKit project metadata was detected for this target."};let o=t.commandMap[n];return !o||o.status!=="supported"?{supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`}:{supported:true}}var $e=new Set(["init","test","build","start"]),De=new Set([".git","node_modules",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function T(e){try{return await M.promises.access(e,M.constants.F_OK),true}catch{return false}}async function Me(e,r,t){if(r==="python"){let n=b.join(e,".rapidkit","cli.py");return await T(n)?{valid:true}:{valid:false,reason:"Project-local .rapidkit/cli.py is missing. Run `rapidkit init` in this project first."}}return G(t)}async function Q(e){let r=await M.promises.readFile(e,"utf-8");return JSON.parse(r)}function P(e){return e.replace(/\\/g,"/")}function Oe(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function Le(e){return a$1(e,{skipDirs:De,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(r,t)=>await T(b.join(r,".rapidkit","context.json"))||await T(b.join(r,".rapidkit","project.json"))?true:b.resolve(r)===b.resolve(t)?false:h(r).length>0})}async function _e(e){for(let r of [b.join(".rapidkit","project.json"),b.join(".rapidkit","context.json")]){let t=b.join(e,r);if(await T(t))try{let n=await Q(t),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function Ge(e,r,t){let n=Oe(t);if(!n)return {projects:r,normalizedScope:null};let o=P(n).toLowerCase(),a=[];for(let u of r){let m=P(b.relative(e,u)),g=b.basename(u),y=await _e(u);[m,g,y].filter(s=>typeof s=="string"&&s.length>0).map(s=>P(s).toLowerCase()).includes(o)&&a.push(u);}if(a.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:a,normalizedScope:n}}async function Be(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false});if(n.exitCode!==0)return new Set(r);let o=n.stdout.split(/\r?\n/).map(u=>u.trim()).filter(u=>u.length>0).map(u=>P(u));if(o.length===0)return new Set;let a=new Set;for(let u of r){let m=P(b.relative(e,u));if(!m||m===".")continue;let g=`${m}/`;o.some(y=>y===m||y.startsWith(g))&&a.add(u);}return a}async function Ke(e,r,t){let n=b.join(e,".rapidkit","workspace.contract.json");if(await T(n))try{let p=await Ve(e,r,t,n);if(p.graphStatus!=="missing")return p}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let o=b.join(e,".rapidkit","workspace-dependency-graph.json");if(!await T(o))return {expanded:t,graphStatus:"missing",expansionDepth:0};let a;try{a=await Q(o);}catch{return {expanded:t,graphStatus:"invalid",expansionDepth:0}}let u=new Set(r.map(p=>b.resolve(p))),m=new Map;if(!a||typeof a!="object"||Array.isArray(a))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let g=Array.isArray(a.projects)?a.projects:[];for(let p of g){if(!p||typeof p!="object"||Array.isArray(p))continue;let s=p,d=typeof s.path=="string"?s.path:"",f=b.resolve(e,d);if(!u.has(f))continue;let k=Array.isArray(s.dependsOn)?s.dependsOn.filter(R=>typeof R=="string"):[];for(let R of k){let c=b.resolve(e,R);u.has(c)&&(m.has(c)||m.set(c,new Set),m.get(c)?.add(f));}}let y=d$1(m,t);return {expanded:y.reached,graphStatus:"loaded",expansionDepth:y.added}}async function Ve(e,r,t,n){let o=await Q(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let a=o,u=Array.isArray(a.projects)?a.projects:null;if(!u)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let m=new Map,g=new Map;for(let f of r){let k=P(b.relative(e,f));g.set(k,b.resolve(f));}let y=new Map,p=new Map,s=new Map;for(let f of u){if(!f||typeof f!="object"||Array.isArray(f))continue;let k=f,R=typeof k.slug=="string"?k.slug:"",c=typeof k.relativePath=="string"?P(k.relativePath):R,h=g.get(c);!R||!h||m.set(R,h);}for(let f of u){if(!f||typeof f!="object"||Array.isArray(f))continue;let k=f,R=typeof k.slug=="string"?k.slug:"",c=m.get(R);if(!c)continue;let h=k.contracts&&typeof k.contracts=="object"&&!Array.isArray(k.contracts)?k.contracts:{},N=Array.isArray(h.dependsOn)?h.dependsOn.filter(x=>typeof x=="string"):[],W=Array.isArray(h.publishes)?h.publishes.filter(x=>typeof x=="string"):[],$=Array.isArray(h.consumes)?h.consumes.filter(x=>typeof x=="string"):[];for(let x of N){let S=m.get(x);S&&(s.has(S)||s.set(S,new Set),s.get(S)?.add(c));}for(let x of W)y.has(x)||y.set(x,new Set),y.get(x)?.add(c);for(let x of $)p.has(x)||p.set(x,new Set),p.get(x)?.add(c);}for(let[f,k]of y.entries()){let R=p.get(f);if(R)for(let c of k){s.has(c)||s.set(c,new Set);for(let h of R)h!==c&&s.get(c)?.add(h);}}let d=d$1(s,t);return {expanded:d.reached,graphStatus:"loaded",expansionDepth:d.added}}async function He(e,r){if(typeof r=="boolean")return r;let t=b.join(e,".rapidkit","policies.yml");if(!await T(t))return true;let n="";try{n=await M.promises.readFile(t,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}async function q(e,r){let t=process.argv[1];if(!t)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};let n=await execa(process.execPath,[t,...e],{cwd:r,reject:false,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});return {exitCode:Number(n.exitCode??1),stdout:n.stdout,stderr:n.stderr}}function ze(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"}function Ue(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}async function Je(e){let r=process.cwd();try{process.chdir(e);let{handleInitCommand:t}=await import('./index.js');return {exitCode:await t(["init"]),stdout:"",stderr:""}}finally{process.chdir(r);}}async function qe(e$1){let r=s=>{let d=f(s);return d==="node"||d==="bun"?"node":d==="python"?"python":d==="go"?"go":d==="java"?"java":d==="php"?"php":d==="ruby"?"ruby":d==="rust"?"rust":d==="dotnet"?"dotnet":d==="elixir"?"elixir":d==="clojure"||d==="scala"||d==="kotlin"?"jvm-generic":ye(e$1)},t=s=>{if(!s)return;let d=e(s);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(d))return d},n$1=n(e$1),o=n$1?.detection??i(e$1,n$1?.projectJson??null),a=n$1?.contextJson,u=r(o.runtime),m=t(o.key),g={},y=new Set(["init","test","build","start"]);if(a?.commands&&typeof a.commands=="object")for(let[s,d]of Object.entries(a.commands))typeof d=="string"&&y.has(s)&&(g[s]=d);let p;if(a?.commandEnvironments&&typeof a.commandEnvironments=="object"){let s=a.commandEnvironments;p={dev:typeof s.dev=="string"?s.dev:void 0,staging:typeof s.staging=="string"?s.staging:void 0,prod:typeof s.prod=="string"?s.prod:void 0,default:typeof s.default=="string"?s.default:void 0};}return {runtime:u,framework:m,commandOverrides:Object.keys(g).length>0?g:void 0,environmentCommandVariants:p,environment:typeof a?.environment=="string"?a.environment:void 0}}async function Ye(e,r,t,n,o,a,u){let m=!o?.[r]&&ze(t),g;if(o&&o[r]?g=o[r]:m?g=`rapidkit ${r}`:g=J({projectPath:e,runtime:t,framework:n,stage:r}),!g)return {exitCode:127,command:`<stage not supported for ${t}>`,message:`No stage command found for runtime '${t}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let y=ke(g,a,u);if(!y)return {exitCode:127,command:g,message:"Failed to resolve stage command",errorCategory:"runtime"};let p=J({projectPath:e,runtime:t,framework:n,stage:r});if(m){if(p){let c=m?await Me(e,t,p):await G(p);if(!c.valid)return {exitCode:127,command:y,message:c.reason||"Command not available",errorCategory:"setup"}}}else {let c=await G(y);if(!c.valid)return {exitCode:127,command:y,message:c.reason||"Command not available",errorCategory:"setup"}}let s=0,d="",f="",k;try{let c=m?r==="init"&&Ue()?await Je(e):await q([r],e):await execa(y,[],{cwd:e,reject:false,shell:true});if(s=Number(c.exitCode??0),d=c.stdout,f=c.stderr,s!==0){let h=`${d}
2
- ${f}`;k=he(h);}}catch(c){return {exitCode:1,command:y,message:c instanceof Error?c.message:"Command execution failed",errorCategory:"runtime"}}return {exitCode:s,command:y,errorCategory:k,healthStatus:void 0,message:s!==0?`Stage failed with exit code ${s}`:void 0}}function xe(e){try{return JSON.parse(e)}catch{return null}}function Qe(e){switch(e){case "dotnet":return "Install .NET 8+ SDK, then rerun `npx rapidkit setup dotnet` or `npx rapidkit init`.";case "go":return "Install Go 1.21+, then rerun `npx rapidkit setup go` or `npx rapidkit init`.";case "java":case "jvm-generic":return "Install Java 21+ and Maven/Gradle, then rerun `npx rapidkit setup java` or `npx rapidkit init`.";case "node":return "Install Node.js LTS and npm/pnpm/yarn, then rerun `npx rapidkit setup node` or `npx rapidkit init`.";case "python":return "Install Python 3.10+ and pip/Poetry, then rerun `npx rapidkit setup python` or `npx rapidkit init`.";default:return null}}async function Xe(e){let r=[],t=await q(["doctor","workspace","--json"],e);if(t.exitCode!==0)r.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let a=xe(t.stdout)?.healthScore,u=Number(a?.errors??0);Number.isFinite(u)&&u>0?r.push({gate:"doctor-workspace",status:"fail",summary:`doctor workspace reports ${u} error(s)`}):r.push({gate:"doctor-workspace",status:"pass",summary:"doctor workspace passed"});}let n=await q(["readiness","--json"],e);if(n.exitCode!==0)r.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let o=xe(n.stdout),a=String(o?.overallStatus??"").toLowerCase();a==="fail"?r.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):a==="warn"?r.push({gate:"readiness",status:"warn",summary:"readiness overall status is warn"}):r.push({gate:"readiness",status:"pass",summary:"readiness overall status is pass"});}return r}function Ze(e){return $e.has(e)}function et(e,r){let t=Math.max(1,Math.min(4,r)),n=Number(e??t);return Number.isFinite(n)?Math.max(1,Math.min(16,Math.trunc(n))):t}async function Ft(e){if(!Ze(e.stage))throw new Error(`Unsupported workspace run stage: ${e.stage}`);let r=Date.now(),t=b.resolve(e.workspacePath),n=await Le(t),{projects:o,normalizedScope:a$1}=await Ge(t,n,e.scope),u=e.affected===true,m=e.blastRadius===true,g=e.since?.trim()||"HEAD~1",y=u?await Be(t,o,g):new Set(o),p,s="not-applicable",d$1=0,f="all";if(u&&m){let l=await Ke(t,n,y);p=l.expanded,s=l.graphStatus,d$1=l.expansionDepth,f="affected+blast-radius";}else u?(p=y,f="affected"):(p=y,f="all");let k=e.stage==="init"?false:await He(t,e.enforceGates),R=k?await Xe(t):[{gate:"doctor-workspace",status:"skipped",summary:"workspace run gates disabled"},{gate:"readiness",status:"skipped",summary:"workspace run gates disabled"}],c=R.find(l=>l.status==="fail"),h=o.filter(l=>p.has(l)),N=e.continueOnError===true||e.stage==="init",W=e.parallel===true,$=et(e.maxWorkers,h.length),x=h.length,S=0;e.json||console.log(v.gray(`Workspace run (${e.stage}) started: ${x} target(s), ${W?`parallel x${$}`:"sequential"}`));let F=new Map;for(let l of n){let w=o.includes(l),i=w&&p.has(l);F.set(l,{path:l,relativePath:P(b.relative(t,l)),selected:i,affected:i,status:"skipped",exitCode:null,durationMs:0,reason:i?void 0:w?"not affected":"outside scope",framework:void 0,runtimeDetected:void 0,executionCommand:void 0});}if(c)for(let l of h){let w=F.get(l);w&&(w.status="skipped",w.reason=`blocked by ${c.gate}`);}else {let l=async w=>{let i=F.get(w);if(!i)return;let I=P(b.relative(t,w));e.json||console.log(v.gray(`\u23F3 [${S}/${x}] ${e.stage} ${I}`)),i.selected=true,i.affected=true;let E=Date.now(),{runtime:j,framework:C,commandOverrides:je,environmentCommandVariants:Se,environment:Ee}=await qe(w);i.runtimeDetected=j,i.framework=C;let re=be(w,e.stage);if(!re.supported){i.status="skipped",i.reason=re.reason??`stage "${e.stage}" unsupported for project`,i.durationMs=Date.now()-E,i.exitCode=null,S+=1;return}let A=await Ye(w,e.stage,j,C,je,Se,Ee);if(i.executionCommand=A.command,i.errorCategory=A.errorCategory,i.healthStatus=A.healthStatus,i.durationMs=Date.now()-E,i.exitCode=A.exitCode,A.exitCode===0?(i.status="passed",i.reason=void 0):(i.status="failed",i.reason=A.message||"stage command failed",i.errorMessage=A.message),S+=1,!e.json){let Ce=x>0?Math.round(S/x*100):100,Pe=i.status==="passed"?v.green("\u2705"):v.red("\u274C");if(console.log(v.gray(`${Pe} [${S}/${x}] (${Ce}%) ${I} ${i.durationMs}ms`)),i.status==="failed"){i.reason&&console.log(v.red(` Reason: ${i.reason}`)),i.executionCommand&&console.log(v.gray(` Command: ${i.executionCommand}`));let ne=Qe(i.runtimeDetected);ne&&i.errorCategory==="setup"&&console.log(v.gray(` Hint: ${ne}`));}}};if(W&&h.length>1){let w=0,i=false,I=new Array($).fill(null).map(async()=>{for(;w<h.length;){if(i&&!N)return;let E=w;w+=1;let j=h[E];await l(j),F.get(j)?.status==="failed"&&(i=true);}});if(await Promise.all(I),!N&&i){let E=false;for(let j of h){let C=F.get(j);if(C){if(C.status==="failed"){E=true;continue}E&&C.status==="skipped"&&(C.reason=C.reason||"stopped after failure");}}}}else for(let w of h){await l(w);let i=F.get(w);if(!N&&i?.status==="failed"){let I=h.slice(h.indexOf(w)+1);for(let E of I){let j=F.get(E);j&&(j.status="skipped",j.reason="stopped after failure");}break}}}let D=[];for(let l of n){let w=F.get(l);w&&D.push(w);}let X=D.filter(l=>l.status==="passed").length,K=D.filter(l=>l.status==="failed").length,Z=D.filter(l=>l.status==="skipped").length,ee=e.strict===true,Re=K>0||ee&&R.some(l=>l.status==="fail"||l.status==="warn")?1:0,te={schemaVersion:"1.0",workspacePath:t,stage:e.stage,generatedAt:new Date().toISOString(),durationMs:Date.now()-r,options:{affected:u,blastRadius:m,since:u?g:null,parallel:W,maxWorkers:$,continueOnError:N,strict:ee,enforceGates:k,scope:a$1},selection:{mode:f,since:u?g:null,scope:a$1,graphStatus:s,expansionDepth:d$1},gates:{enforced:k,results:R,blocked:!!c,blockingGate:c?.gate},summary:{projectCount:n.length,selectedCount:h.length,passed:X,failed:K,skipped:Z,exitCode:Re},projects:D,enterpriseControls:{jsonReady:true,evidencePath:b$1}},ve=b.join(t,".rapidkit","reports",a);return await d(t,te),e.json||(c&&(console.log(v.red(`\u274C Workspace run blocked by ${c.gate}`)),console.log(v.gray(` ${c.summary}`))),console.log(v.cyan(`Workspace run (${e.stage}) => passed: ${X}, failed: ${K}, skipped: ${Z}`)),console.log(v.gray(`Report: ${ve}`))),te}export{Ft as a};
@@ -1,2 +0,0 @@
1
- import o from'fs';import a from'path';var s="workspace-run-v1",R="workspace-run-last.json",g=`.rapidkit/reports/${R}`;var E=new Set(["init","test","build","start"]);function d(e){return E.has(e)}async function S(e){try{let r=await o.promises.readFile(e,"utf-8");return JSON.parse(r)}catch{return null}}async function W(e,r){await o.promises.mkdir(a.dirname(e),{recursive:true}),await o.promises.writeFile(e,`${JSON.stringify(r,null,2)}
2
- `,"utf-8");}function k(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function f(e){let r=e.stage;return typeof r=="string"&&d(r)&&Array.isArray(e.projects)}function w(e){let r=k(e);return !r||r.schemaVersion===s?false:f(r)}function A(e){let r=k(e);return r?r.schemaVersion===s&&r.stages!=null:false}function l(e){if(A(e))return e;if(w(e)){let r=e.stage;return {schemaVersion:s,generatedAt:e.generatedAt,workspacePath:e.workspacePath,latestStage:r,stages:{[r]:e},enterpriseControls:e.enterpriseControls??{jsonReady:true,evidencePath:g}}}return null}function v(e,r){let n=l(e);if(!n)return null;let t=r??n.latestStage;return n.stages[t]??null}async function O(e,r){let n=a.resolve(e),t=a.join(n,".rapidkit","reports",R),i=await S(t),c=l(i),u=c?{...c.stages}:{};u[r.stage]=r;let p={schemaVersion:s,generatedAt:r.generatedAt,workspacePath:r.workspacePath,latestStage:r.stage,stages:u,enterpriseControls:{jsonReady:true,evidencePath:g}};return await W(t,p),p}export{R as a,g as b,v as c,O as d};
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-HHJAANUC.js';import {l}from'./chunk-OCGZNSOE.js';import c from'path';import h from'fs-extra';var j=".rapidkit/workspace.contract.json",w=1;function W(e){return e.replace(/\\/g,"/")}function y(e){let r=W(e).trim();return !r||r.startsWith("/")||r.startsWith("~")||/^[a-zA-Z]:\//.test(r)||r.includes("\0")?false:!r.split("/").filter(Boolean).some(o=>o===".."||o===".")}function $(e,r){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||r}function E(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0):[]}async function R(e){let r=c.join(e,".rapidkit","workspace.json");try{let o=await h.readJson(r);return {name:typeof o.workspace_name=="string"&&o.workspace_name.trim()||typeof o.name=="string"&&o.name.trim()||c.basename(e),profile:typeof o.profile=="string"?o.profile:void 0}}catch{return {name:c.basename(e)}}}async function O(e){let r=[],o=[e],n=new Set,i=new Set([".git","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;o.length>0;){let a=o.shift();if(!a||n.has(a))continue;n.add(a);let p=c.join(a,".rapidkit","project.json"),u=c.join(a,".rapidkit","context.json");if(await h.pathExists(p)||await h.pathExists(u)){r.push(await h.pathExists(p)?p:u);continue}let t;try{t=await h.readdir(a,{withFileTypes:true});}catch{continue}for(let s of t)!s.isDirectory()||i.has(s.name)||o.push(c.join(a,s.name));}return r.sort()}function J(e){let r=(e||"").toLowerCase();if(r.includes("fastapi"))return "fastapi";if(r.includes("nestjs"))return "nestjs";if(r.includes("springboot"))return "springboot";if(r.includes("gofiber"))return "fiber";if(r.includes("gogin"))return "gin"}function _(e,r){let o=(e||"").toLowerCase(),n=(r||"").toLowerCase();return o.includes("fastapi")?8e3:o.includes("nestjs")?3e3:o.includes("springboot")?8080:o.includes("gofiber")?3e3:o.includes("gogin")?8080:n==="node"?3e3:n==="python"?8e3:n==="java"||n==="go"?8080:null}function N(e,r){let o=e;for(;r.has(o)&&o<65535;)o+=1;return o}function P(e,r,o){let n=_(r.kit,r.runtime),i=e?.ports||[],a=i.length>0?i:n?[{name:"http",port:N(n,o),protocol:"http"}]:[];for(let t of a)o.add(t.port);let p={...r,...e,slug:e?.slug||r.slug,relativePath:e?.relativePath&&y(e.relativePath)?e.relativePath:r.relativePath,source:e?.source||r.source,relationship:e?.relationship||r.relationship,externalPath:e?.externalPath||r.externalPath,runtime:e?.runtime||r.runtime,framework:e?.framework||r.framework,kit:e?.kit||r.kit,modules:e?.modules?.length?e.modules:r.modules,ports:a,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},u=JSON.stringify(e||null)!==JSON.stringify(p);return {project:p,changed:u}}async function A(e){let r=c.resolve(e.workspacePath),o=await R(r),n=await O(r),i=await a(r),a$1=[];for(let t of i){let s=c.resolve(t.path),d=c.join(s,".rapidkit","project.json"),f=c.join(s,".rapidkit","context.json"),k=await h.pathExists(d)?d:await h.pathExists(f)?f:null;!k||n.some(l=>c.resolve(l)===c.resolve(k))||a$1.push({projectJsonPath:k,registryEntry:t});}let p=[],u=[...n.map(t=>({projectJsonPath:t})),...a$1];for(let{projectJsonPath:t,registryEntry:s}of u){let d=c.dirname(c.dirname(t)),f=W(c.relative(r,d)),k=s!==void 0&&!y(f),l=$(s?.name||c.basename(d),c.basename(d)),m=k?`external/${l}`:f||l,g=await h.readJson(t),C=typeof g.kit_name=="string"&&g.kit_name||typeof g.kit=="string"&&g.kit||void 0,x=typeof g.framework=="string"&&g.framework||J(C);p.push({slug:s?.name||m||c.basename(d),relativePath:m,source:s?.source??"workspace",relationship:s?.relationship,externalPath:k?d:void 0,runtime:typeof g.runtime=="string"?g.runtime:void 0,framework:x,kit:C,modules:E(g.modules),ports:[],contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}return {schemaVersion:w,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:o,projects:p}}async function F(e){let r=c.resolve(e.outputPath||c.join(e.workspacePath,j));if(await h.pathExists(r)&&e.force!==true)throw new Error(`Workspace contract already exists: ${r}. Use --force to overwrite.`);let o=await A({workspacePath:e.workspacePath,now:e.now}),n=new Set,i={...o,projects:o.projects.map(p=>P(void 0,p,n).project)};await h.ensureDir(c.dirname(r)),await h.writeJson(r,i,{spaces:2});let{publishWorkspaceRegistrySummary:a}=await import('./workspace-registry-summary-MIPHVB56.js');return await a(e.workspacePath,{now:e.now}),{contractPath:r,contract:i}}async function K(e){let r=c.resolve(e.workspacePath),o=c.join(r,j),n=await A({workspacePath:r,now:e.now}),i=await h.pathExists(o)?await h.readJson(o):null,a=new Map((i?.projects||[]).map(l=>[l.slug,l])),p=new Set,u=[],t=[],s=[];for(let l of n.projects){let m=a.get(l.slug),g=P(m,l,p);m?g.changed&&t.push(l.slug):u.push(l.slug),s.push(g.project),a.delete(l.slug);}for(let l of a.values()){let m=P(l,l,p);s.push(m.project);}let d={schemaVersion:w,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...n.workspace,...i?.workspace||{},name:i?.workspace?.name||n.workspace.name},projects:s.sort((l,m)=>l.slug.localeCompare(m.slug))};await h.ensureDir(c.dirname(o)),await h.writeJson(o,d,{spaces:2});let f=await V({workspacePath:r}),{publishWorkspaceRegistrySummary:k}=await import('./workspace-registry-summary-MIPHVB56.js');return await k(r,{now:e.now}),{contractPath:o,contract:d,addedProjects:u,updatedProjects:t,verification:f}}async function S(e){let r=c.resolve(e.contractPath||c.join(e.workspacePath,j)),o=await h.readJson(r);return {contractPath:r,contract:o}}async function L(e){let{contractPath:r,contract:o}=await S(e),n=o.projects.map(t=>({id:t.slug,label:t.slug,relativePath:t.relativePath,source:t.source,relationship:t.relationship,externalPath:t.externalPath,runtime:t.runtime,framework:t.framework,kit:t.kit,modules:t.modules,ports:t.ports,apis:t.contracts.apis,owns:t.contracts.owns,env:t.contracts.env})),i=new Set(n.map(t=>t.id)),a=new Map,p=[];for(let t of o.projects){for(let s of t.contracts.dependsOn||[])i.has(s)&&p.push({from:s,to:t.slug,type:"dependency",label:"dependsOn"});for(let s of t.contracts.publishes||[])a.has(s)||a.set(s,new Set),a.get(s)?.add(t.slug);}for(let t of o.projects)for(let s of t.contracts.consumes||[]){let d=a.get(s);if(d)for(let f of d)f!==t.slug&&p.push({from:f,to:t.slug,type:"event",label:s});}let u={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:o.workspace,generatedAt:new Date().toISOString(),nodes:n.sort((t,s)=>t.id.localeCompare(s.id)),edges:p.sort((t,s)=>`${t.from}:${t.to}:${t.type}:${t.label}`.localeCompare(`${s.from}:${s.to}:${s.type}:${s.label}`)),summary:{projectCount:n.length,dependencyEdges:p.filter(t=>t.type==="dependency").length,eventEdges:p.filter(t=>t.type==="event").length,portCount:n.reduce((t,s)=>t+s.ports.length,0),apiCount:n.reduce((t,s)=>t+s.apis.length,0)}};return {contractPath:r,graph:u}}async function V(e){let{contractPath:r,contract:o}=await S(e),n=[],i=[];o.kind!=="rapidkit.workspace.contract"&&n.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==w&&n.push(`Contract schemaVersion must be ${w}.`),o.workspace?.name||n.push("Contract workspace.name is required."),Array.isArray(o.projects)||n.push("Contract projects must be an array.");let a=new Set,p=new Map;for(let t of o.projects||[]){if(!t.slug){n.push("Every project must declare slug.");continue}a.has(t.slug)&&n.push(`Duplicate project slug: ${t.slug}.`),a.add(t.slug),t.relativePath?y(t.relativePath)||n.push(`Project ${t.slug} declares unsafe relativePath: ${t.relativePath}.`):n.push(`Project ${t.slug} must declare relativePath.`),t.externalPath&&(t.relationship==="adopted"||t.source==="adopted-local"||t.source==="local-folder"||t.source==="git-url"||n.push(`Project ${t.slug} declares externalPath without imported/adopted provenance.`),c.isAbsolute(t.externalPath)||n.push(`Project ${t.slug} declares non-absolute externalPath.`));for(let s of t.ports||[]){(!Number.isInteger(s.port)||s.port<1||s.port>65535)&&n.push(`Project ${t.slug} declares invalid port: ${s.port}.`);let d=p.get(s.port);d&&n.push(`Port ${s.port} is claimed by both ${d} and ${t.slug}.`),p.set(s.port,t.slug);}for(let s of t.contracts?.apis||[])(!s.name?.trim()||!s.basePath?.startsWith("/"))&&n.push(`Project ${t.slug} declares invalid API contract.`);for(let s of [...t.contracts?.publishes||[],...t.contracts?.consumes||[]])s.trim()||n.push(`Project ${t.slug} declares an empty event contract.`);for(let s of t.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(s)||n.push(`Project ${t.slug} declares invalid env contract: ${s}.`);for(let s of t.contracts?.dependsOn||[])a.has(s);}for(let t of o.projects||[])for(let s of t.contracts?.dependsOn||[])a.has(s)||n.push(`Project ${t.slug} depends on unknown project: ${s}.`);i.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===w?"passed":"failed",message:"Contract schema and kind are valid."}),i.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),i.push({id:"ports",status:n.some(t=>t.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),i.push({id:"dependencies",status:n.some(t=>t.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),i.push({id:"contracts",status:n.some(t=>t.includes("unsafe relativePath")||t.includes("invalid API contract")||t.includes("event contract")||t.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let u=await l(e.workspacePath);if(u.moduleCount>0){for(let t of u.issues)n.push(`${c.basename(t.projectRoot)}: ${t.message} (slug=${t.slug})`);i.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&&i.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:n.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:i,violations:n}}
2
- export{j as a,w as b,O as c,A as d,F as e,K as f,S as g,L as h,V as i};
@@ -1,2 +0,0 @@
1
- var a="cli-log-event-v1";var m="RAPIDKIT_LOG_FORMAT";function c(e=process.argv){let r=process.env[m]?.trim().toLowerCase();if(r==="json")return "json";if(r==="text")return "text";for(let o=0;o<e.length;o+=1){let t=e[o];if(t==="--log-json")return "json";if(t==="--log-format"){let n=e[o+1]?.trim().toLowerCase();if(n==="json")return "json";if(n==="text")return "text"}if(t?.startsWith("--log-format=")){let n=t.slice(13).trim().toLowerCase();if(n==="json")return "json";if(n==="text")return "text"}}return "text"}function l(e=process.argv){return c(e)==="json"}var g="unknown-run";function I(e){g=e;}function u(){return g}function L(e){return {schemaVersion:a,runId:u(),timestamp:new Date().toISOString(),level:e.level,event:e.event,component:e.component,message:e.message,...e.command?{command:e.command}:{},...e.metadata&&Object.keys(e.metadata).length>0?{metadata:f(e.metadata)}:{}}}function y(e){l()&&p(L(e));}function p(e){process.stderr.write(`${JSON.stringify(e)}
2
- `);}function f(e){let r={};for(let[o,t]of Object.entries(e))if(t!==void 0){if(t instanceof Error){r[o]={name:t.name,message:t.message};continue}if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"){r[o]=t;continue}if(Array.isArray(t)){r[o]=t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?n:String(n));continue}r[o]=String(t);}return r}export{c as a,l as b,a as c,I as d,u as e,y as f,p as g};
@@ -1,33 +0,0 @@
1
- import {f,e,d,a as a$1,k as k$1,g as g$1,c}from'./chunk-Z5LKRG57.js';import {a}from'./chunk-2FIX2MDC.js';import ft from'crypto';import q from'os';import u from'path';import*as p from'fs-extra';import {execa}from'execa';var mt=["version","project","create","add","list","info","upgrade","diff","doctor","license","commands","reconcile","rollback","uninstall","checkpoint","optimize","snapshot","frameworks","modules","merge"],M=new Set(mt);var g=a();function O(){let t=[],e$1=i=>{let o=i?.trim();o&&t.push(o);};e$1(process.env.RAPIDKIT_BRIDGE_PYTHON),e$1(process.env.RAPIDKIT_PYTHON_CMD),e$1(process.env.POETRY_PYTHON);let r=_();(r.startsWith("/")||r.startsWith(".")||r.startsWith(".."))&&!r.startsWith("file:")&&e$1(f(u.join(u.resolve(r),".venv")));for(let i of e())i.args.length===1&&i.args[0]==="--version"&&e$1(i.command);for(let i of d())e$1(i);return [...new Set(t)]}function v(t,e){return t==="py"?["-3",...e]:e}function J(t){if(!t)return t;let e=["Installed Poetry version does not support '--no-update'. Falling back to 'poetry lock'."];return t.split(/\r?\n/).filter(i=>!e.some(o=>i.includes(o))).join(`
2
- `)}var w=class extends Error{code;constructor(e,r){super(r),this.code=e;}};function S(t){if(t instanceof w)switch(t.code){case "PYTHON_NOT_FOUND":return `RapidKit (npm) could not find Python (python3/python/py) on your PATH.
3
- Install Python 3.10+ and ensure \`${c()}\` is available, then retry.
4
- Tip: if you are inside a RapidKit project, use the local ./rapidkit launcher.`;case "BRIDGE_VENV_CREATE_FAILED":return `RapidKit (npm) failed to create its bridge virtual environment.
5
- `+(a$1()?`Ensure Python is installed with venv support.
6
- `:`Ensure Python venv support is installed (e.g., python3-venv).
7
- `)+`Details: ${t.message}`;case "BRIDGE_PIP_BOOTSTRAP_FAILED":return `RapidKit (npm) could not bootstrap pip inside the bridge virtual environment.
8
- `+(a$1()?`Ensure pip is available for your Python installation and retry.
9
- `:`Install python3-venv/python3-pip and retry.
10
- `)+`Details: ${t.message}`;case "BRIDGE_PIP_UPGRADE_FAILED":return `RapidKit (npm) could not upgrade pip in the bridge virtual environment.
11
- Check your network/proxy or disable RAPIDKIT_BRIDGE_UPGRADE_PIP.
12
- Details: ${t.message}`;case "BRIDGE_PIP_INSTALL_FAILED":return `RapidKit (npm) could not install rapidkit-core in the bridge virtual environment.
13
- Check your network/proxy, or install manually with: pipx install rapidkit-core.
14
- Details: ${t.message}`;default:return `RapidKit (npm) bridge error: ${t.message}`}return `RapidKit (npm) failed to run the Python core engine: ${t instanceof Error?t.message:String(t)}`}function _(){let t=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE;return t&&t.trim()?t.trim():"rapidkit-core"}function ht(){let t=_(),e=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE_ID,r=e&&e.trim()?`${t}|${e.trim()}`:t;return ft.createHash("sha256").update(r).digest("hex").slice(0,12)}function j(){let t=process.env.XDG_CACHE_HOME;return t&&t.trim()?t:u.join(q.homedir(),".cache")}function gt(){return u.join(j(),"rapidkit","npm-bridge","venv")}function Q(){let t=ht();return u.join(j(),"rapidkit","npm-bridge",`venv-${t}`)}function H(t){return f(t)}function U(t){return g$1(t)}async function tt(t=process.platform,e=process.env){let r=a$1(t)?["rapidkit.exe","rapidkit.cmd"]:["rapidkit"],n=k$1(e,t).flatMap(i=>r.map(o=>u.join(i,o)));for(let i of [...new Set(n)])try{if(!await p.pathExists(i))continue;let o=await execa(i,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(o.exitCode===0&&await D(o.stdout))return {cmd:i,baseArgs:[]}}catch{}return null}function et(t){return /[<>=!~]=|@|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(t)}function yt(t){return u.dirname(u.dirname(t))}function nt(){return u.join(j(),"rapidkit","npm-bridge","core-commands.json")}async function rt(t){let e=!!process.env.RAPIDKIT_DEBUG,r=n=>{e&&process.stderr.write(`[DEBUG] tryRapidkit(${t}): ${n}
15
- `);};try{r("probing interpreter-specific rapidkit script");let i=((await execa(t,v(t,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"]),{reject:false,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(r(`script path: ${i}`),i)try{if(await p.pathExists(i)){r(`found script at ${i}; invoking --version --json`);let o=await execa(i,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(r(`script exitCode=${o.exitCode}`),o.exitCode===0){let a=(o.stdout??"").toString().trim();try{let s=JSON.parse(a),c=!!s&&typeof s=="object"&&s!==null&&"version"in s;if(r(`script JSON parse ok=${c}`),c)return true}catch{r("script output not valid JSON");}}}}catch(o){r(`interpreter-specific script probe failed: ${String(o)}`);}}catch(n){r(`interpreter-specific script probe error: ${String(n)}`);}try{r('probing importlib.find_spec("rapidkit")');let n=await execa(t,v(t,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"]),{reject:false,stdio:"pipe",timeout:2e3});if(r(`import probe exitCode=${n.exitCode} stdout=${(n.stdout??"").toString().trim()}`),n.exitCode===0&&(n.stdout??"").toString().trim()==="1")return true}catch(n){r(`import probe error: ${String(n)}`);}try{r("probing python -m rapidkit");let n=await execa(t,v(t,["-m","rapidkit","--version","--json"]),{reject:false,stdio:"pipe",timeout:8e3});if(r(`-m probe exitCode=${n.exitCode}`),n.exitCode===0)return true}catch(n){r(`-m probe error: ${String(n)}`);}try{r("probing PATH for rapidkit executables");let n=(process.env.PATH??"").split(u.delimiter).filter(Boolean);for(let i of n){let o=u.join(i,a$1()?"rapidkit.exe":"rapidkit");try{if(await p.pathExists(o)){r(`found candidate on PATH: ${o}; invoking --version --json`);let a=await execa(o,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(r(`candidate exitCode=${a.exitCode}`),a.exitCode===0){let s=(a.stdout??"").toString().trim();try{let c=JSON.parse(s);if(c&&typeof c=="object"&&c!==null&&"version"in c)return true}catch{r("candidate output not valid JSON, skipping");}}}}catch(a){r(`error probing candidate ${o}: ${String(a)}`);}}return r("no valid rapidkit found on PATH"),false}catch(n){return r(`PATH probe error: ${String(n)}`),false}}async function D(t){let e=(t??"").toString().trim();if(!e)return false;try{let r=JSON.parse(e);return !!r&&typeof r=="object"&&r!==null&&"version"in r}catch{return false}}async function it(t,e=process.platform){let r=async o=>{try{let a=u.join(o,".rapidkit-workspace");if(!await p.pathExists(a))return null;let c=(await p.readJson(a))?.metadata?.python?.venvPath;return typeof c!="string"||!c.trim()?null:u.isAbsolute(c)?c:u.join(o,c)}catch{return null}},n=async(o,a)=>{let s=g$1(a,e);if(await p.pathExists(s)){let l=await execa(s,["--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:o});if(l.exitCode===0&&await D(l.stdout))return {cmd:s,baseArgs:[],workspaceDir:o}}let c=f(a,e);if(await p.pathExists(c)){let l=await execa(c,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:o});if(l.exitCode===0&&await D(l.stdout))return {cmd:c,baseArgs:["-m","rapidkit"],workspaceDir:o}}return null},i=t;for(let o=0;o<25;o+=1){let a=await r(i),s=[u.join(i,".venv"),a].filter(l=>!!l);for(let l of [...new Set(s)]){let P=await n(i,l);if(P)return P}let c=u.dirname(i);if(c===i)break;i=c;}return null}async function wt(t){try{let e=u.join(t,".python-version");if(await p.pathExists(e)){let n=(await p.readFile(e,"utf-8")).trim();if(n)return n}}catch{}try{let e=u.join(t,".rapidkit-workspace");if(await p.pathExists(e)){let r=await p.readJson(e);if(typeof r?.pythonVersion=="string"&&r.pythonVersion.trim())return r.pythonVersion.trim();let n=r?.metadata?.python?.pythonVersion;if(typeof n=="string"&&n.trim())return n.trim()}}catch{}return null}async function F(t){if(t&&t.trim())try{let a=await it(t);if(a){let s=a.workspaceDir??(u.dirname(a.cmd).includes(".venv")?u.dirname(u.dirname(u.dirname(a.cmd))):u.dirname(a.cmd)),c=await wt(s);return c&&(process.env.PYENV_VERSION=c),a}}catch{}let e=await xt();if(e.kind==="venv"){let a=yt(e.pythonPath),s=U(a);return await p.pathExists(s)?{cmd:s,baseArgs:[]}:{cmd:e.pythonPath,baseArgs:["-m","rapidkit"]}}try{if((await execa(e.cmd,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:4e3})).exitCode===0)return {cmd:e.cmd,baseArgs:["-m","rapidkit"]}}catch{}try{let s=((await execa(e.cmd,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"],{reject:false,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(s&&await p.pathExists(s))try{let c=await execa(s,["--version","--json"],{reject:false,stdio:"pipe",timeout:4e3});if(c.exitCode===0&&await D(c.stdout))return {cmd:s,baseArgs:[]}}catch{}}catch{}let r=await tt();if(r)return r;let n=Q(),i=await N(e.cmd),o=U(n);return await p.pathExists(o)?{cmd:o,baseArgs:[]}:{cmd:i,baseArgs:["-m","rapidkit"]}}async function ot(){for(let t of O())try{return await execa(t,v(t,["--version"]),{reject:false,stdio:"pipe",timeout:2e3}),t}catch{}return null}async function B(){let t=null;for(let e of O()){try{await execa(e,v(e,["--version"]),{reject:false,stdio:"pipe",timeout:2e3});}catch(r){t=r;continue}try{return await N(e)}catch(r){t=r;continue}}throw t instanceof w?t:t instanceof Error?new w("BRIDGE_VENV_BOOTSTRAP_FAILED",t.message):new w("PYTHON_NOT_FOUND","No Python interpreter found (python3/python/py).")}async function vt(){let t=!!process.env.RAPIDKIT_DEBUG,e$1=n=>{t&&process.stderr.write(`[DEBUG] checkRapidkitCore: ${n}
16
- `);},r=Array.from(new Set([...d(),...e(14,10).map(n=>n.command)]));for(let n of r)try{e$1(`Method 1: trying ${n} import`);let i=await execa(n,v(n,["-c","import rapidkit_core; print(1)"]),{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout?.trim()==="1")return e$1(`\u2713 Found via ${n} import`),true}catch{continue}for(let n of r)try{e$1(`Method 2: trying ${n} -m pip show`);let i=await execa(n,v(n,["-m","pip","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout?.includes("Name: rapidkit-core"))return e$1(`\u2713 Found via ${n} -m pip show`),true}catch{continue}for(let n of ["pip","pip3"])try{e$1(`Method 3: trying ${n} show`);let i=await execa(n,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout?.includes("Name: rapidkit-core"))return e$1(`\u2713 Found via ${n} show`),true}catch{continue}try{e$1("Method 4: checking pyenv versions");let n=await execa("pyenv",["versions","--bare"],{reject:false,stdio:"pipe",timeout:g});if(n.exitCode===0&&n.stdout){let i=n.stdout.split(`
17
- `).filter(o=>o.trim());e$1(`Found pyenv versions: ${i.join(", ")}`);for(let o of i){let a=process.env.PYENV_ROOT||u.join(q.homedir(),".pyenv"),s=u.join(a,"versions",o.trim(),"bin","pip");try{let c=await execa(s,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g});if(c.exitCode===0&&c.stdout?.includes("Name: rapidkit-core"))return e$1(`\u2713 Found in pyenv ${o}`),true}catch{try{let c=await execa("pyenv",["exec","pip","show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g,env:{...process.env,PYENV_VERSION:o.trim()}});if(c.exitCode===0&&c.stdout?.includes("Name: rapidkit-core"))return e$1(`\u2713 Found in pyenv ${o} via PYENV_VERSION`),true}catch{continue}}}}}catch{e$1("pyenv not available");}for(let n of r)try{e$1(`Method 5: checking ${n} user site`);let i=await execa(n,v(n,["-m","site","--user-site"]),{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout){let o=i.stdout.trim(),a=u.join(o,"rapidkit_core");if(await p.pathExists(a))return e$1("\u2713 Found in user site-packages"),true}}catch{continue}try{e$1("Method 6: checking pipx");let n=await execa("pipx",["list"],{reject:false,stdio:"pipe",timeout:g});if(n.exitCode===0&&n.stdout?.includes("rapidkit-core"))return e$1("\u2713 Found via pipx"),true}catch{e$1("pipx not available");}for(let n of r)try{e$1(`Method 6: checking ${n} -m pipx list`);let i=await execa(n,v(n,["-m","pipx","list"]),{reject:false,stdio:"pipe",timeout:g});if(i.exitCode===0&&i.stdout?.includes("rapidkit-core"))return e$1(`\u2713 Found via ${n} -m pipx list`),true}catch{continue}try{if(e$1("Method 7: checking poetry"),(await execa("poetry",["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g})).exitCode===0)return e$1("\u2713 Found via poetry"),true}catch{e$1("poetry check failed");}for(let n of r)try{if(e$1(`Method 7: checking ${n} -m poetry show rapidkit-core`),(await execa(n,v(n,["-m","poetry","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:g})).exitCode===0)return e$1(`\u2713 Found via ${n} -m poetry`),true}catch{continue}try{e$1("Method 8: checking conda");let n=await execa("conda",["list","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g});if(n.exitCode===0&&n.stdout?.includes("rapidkit-core"))return e$1("\u2713 Found via conda"),true}catch{e$1("conda not available");}return e$1("\u2717 Not found in any environment"),false}function Pt(t){let e=t.trim();if(!e||!e.startsWith("rapidkit-core"))return null;let r=e.slice(13).trim();return !r||/[\/@]|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(r)?null:r}function Y(t){let e=t.trim();if(!e)return null;let r=e.split("."),n=[];for(let i of r){let o=i.match(/^(\d+)/);if(!o){n.push(0);continue}n.push(Number.parseInt(o[1],10));}return n}function W(t,e){let r=Math.max(t.length,e.length);for(let n=0;n<r;n+=1){let i=n<t.length?t[n]:0,o=n<e.length?e[n]:0;if(i>o)return 1;if(i<o)return -1}return 0}function Ct(t){return t.length<=1?[t[0]+1]:t.length===2?[t[0]+1,0]:[t[0],t[1]+1,0]}function Et(t){let e=t.split(",").map(n=>n.trim()).filter(Boolean);if(e.length===0)return null;let r=[];for(let n of e){let i=n.match(/^(==|>=|<=|>|<|~=)\s*([0-9][0-9A-Za-z+._-]*)$/);if(!i)return null;r.push({op:i[1],version:i[2]});}return r}function st(t,e){let r=Y(t);if(!r)return false;let n=Et(e);if(!n)return false;for(let i of n){let o=Y(i.version);if(!o)return false;let a=W(r,o);if(i.op==="=="&&a!==0||i.op===">="&&a<0||i.op==="<="&&a>0||i.op===">"&&a<=0||i.op==="<"&&a>=0)return false;if(i.op==="~="){if(a<0)return false;let s=Ct(o);if(W(r,s)>=0)return false}}return true}async function _t(){let t=Array.from(new Set([...d(),...e(14,10).map(r=>r.command)])),e$1=r=>{let n=r.match(/^Version:\s*(.+)$/m);return n?n[1].trim():null};for(let r of t)try{let n=await execa(r,v(r,["-m","pip","show","rapidkit-core"]),{reject:false,stdio:"pipe",timeout:g});if(n.exitCode===0){let i=e$1(n.stdout||"");if(i)return i}}catch{continue}for(let r of ["pip","pip3"])try{let n=await execa(r,["show","rapidkit-core"],{reject:false,stdio:"pipe",timeout:g});if(n.exitCode===0){let i=e$1(n.stdout||"");if(i)return i}}catch{continue}try{let r=await execa("pipx",["list"],{reject:false,stdio:"pipe",timeout:g});if(r.exitCode===0&&r.stdout){let n=r.stdout.match(/rapidkit-core\s+([0-9][0-9A-Za-z+._-]*)/i);if(n?.[1])return n[1]}}catch{}return null}async function kt(){let t=_(),e=Pt(t);if(!e)return {isCompatible:false,installedVersion:null,expectedConstraint:null,reason:et(t)?"constraint-unsupported":"constraint-missing"};let r=await _t();if(!r)return {isCompatible:false,installedVersion:null,expectedConstraint:e,reason:"version-not-detected"};let n=st(r,e);return {isCompatible:n,installedVersion:r,expectedConstraint:e,reason:n?"compatible":"incompatible-version"}}async function N(t){let e=Q(),r=gt(),n=_(),i=[e];!et(n)&&!await p.pathExists(e)&&await p.pathExists(r)&&i.push(r);for(let m of i){let h=H(m);if(await p.pathExists(h))try{let f=await execa(h,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"],{reject:false,stdio:"pipe",timeout:2e3});if(f.exitCode===0&&(f.stdout??"").toString().trim()==="1")return h;await p.remove(m);}catch{await p.remove(m);}}let o=e,a={...process.env,PIP_DISABLE_PIP_VERSION_CHECK:"1",PIP_NO_PYTHON_VERSION_WARNING:"1"},s=Math.max(0,Number(process.env.RAPIDKIT_BRIDGE_PIP_RETRY??"2")),c=Math.max(200,Number(process.env.RAPIDKIT_BRIDGE_PIP_RETRY_DELAY_MS??"800")),l=Math.max(1e4,Number(process.env.RAPIDKIT_BRIDGE_PIP_TIMEOUT_MS??"120000")),P=m=>new Promise(h=>setTimeout(h,m)),C=async(m,h,f)=>{let y=await execa(m,h,{reject:false,stdio:["ignore","pipe","inherit"],env:a,timeout:f});if(y.exitCode===0)return;let T=(y.stdout??"").toString(),$=(y.stderr??"").toString(),R=[T,$].filter(Boolean).join(`
18
- `),pt=R?`${m} ${h.join(" ")}
19
- ${R}`:`${m} ${h.join(" ")}`;throw new Error(pt)},x=async(m,h,f)=>{let y=0;for(;;)try{await C(m,h,f);return}catch(T){if(y>=s)throw T;let $=Math.floor(Math.random()*200),R=c*Math.pow(2,y)+$;y+=1,await P(R);}};try{await p.ensureDir(u.dirname(o));try{await C(t,v(t,["-m","venv",o]),6e4);}catch(f){let y=f instanceof Error?f.message:String(f);throw new w("BRIDGE_VENV_CREATE_FAILED",y)}let m=H(o);if((await execa(m,["-m","pip","--version"],{reject:false,stdio:"pipe",timeout:2e3})).exitCode!==0&&(await execa(m,["-m","ensurepip","--default-pip"],{reject:false,stdio:["ignore","pipe","inherit"],env:a,timeout:6e4})).exitCode!==0)throw new w("BRIDGE_PIP_BOOTSTRAP_FAILED","ensurepip failed; install python3-venv/python3-pip and retry.");if(process.env.RAPIDKIT_BRIDGE_UPGRADE_PIP==="1")try{await x(m,["-m","pip","install","-U","pip"],l);}catch(f){let y=f instanceof Error?f.message:String(f);throw new w("BRIDGE_PIP_UPGRADE_FAILED",y)}try{await x(m,["-m","pip","install","-U",_()],l);}catch(f){let y=f instanceof Error?f.message:String(f);throw new w("BRIDGE_PIP_INSTALL_FAILED",y)}return m}catch(m){if(m instanceof w)throw m;let h=m instanceof Error?m.message:String(m);throw new w("BRIDGE_VENV_BOOTSTRAP_FAILED",h)}}async function xt(){if(process.env.RAPIDKIT_BRIDGE_FORCE_VENV==="1")return {kind:"venv",pythonPath:await B()};for(let r of O())if(await rt(r))return {kind:"system",cmd:r};let t=await ot();if(!t)throw new w("PYTHON_NOT_FOUND","No Python interpreter found (python3/python/py).");let e;try{e=await N(t);}catch{e=await B();}return {kind:"venv",pythonPath:e}}async function Bt(t,e){try{let r=await F(e?.cwd),n=r.cmd,i=[...r.baseArgs,...t];if(t[0]==="init"){let s=await execa(n,i,{cwd:e?.cwd,env:{...process.env,...e?.env},reject:false,stdio:"pipe"}),c=J((s.stdout??"").toString()),l=J((s.stderr??"").toString());return c&&process.stdout.write(c.endsWith(`
20
- `)?c:`${c}
21
- `),l&&process.stderr.write(l.endsWith(`
22
- `)?l:`${l}
23
- `),typeof s.exitCode=="number"?s.exitCode:1}let a=await execa(n,i,{cwd:e?.cwd,env:{...process.env,...e?.env},reject:false,stdio:"inherit"});return typeof a.exitCode=="number"?a.exitCode:1}catch(r){return process.stderr.write(`${S(r)}
24
- `),1}}var Rt=[{pattern:/RapidKitError:\s*Directory '([^']+)' exists and force is not set/,message:t=>`\u274C Directory "${u.basename(t[1])}" already exists.
25
- \u{1F4A1} Choose a different name, or remove the existing directory first:
26
- rm -rf ${t[1]}`},{pattern:/RapidKitError:\s*Project name '([^']+)' is (invalid|not allowed)/i,message:t=>`\u274C Invalid project name: "${t[1]}"
27
- \u{1F4A1} Use lowercase letters, numbers, and hyphens only (e.g. my-api).`},{pattern:/RapidKitError:\s*Kit '([^']+)' not found/i,message:t=>`\u274C Unknown kit: "${t[1]}"
28
- \u{1F4A1} Run "npx rapidkit list" to see available kits.`},{pattern:/RapidKitError:\s*(.+)/,message:t=>`\u274C ${t[1].trim()}`}];async function Ft(t,e){let{spawn:r}=await import('child_process');try{let n=await F(e?.cwd),i=n.cmd,o=[...n.baseArgs,...t];return await new Promise(a=>{let s=r(i,o,{cwd:e?.cwd,env:{...process.env,...e?.env},stdio:["inherit","inherit","pipe"]}),c=[];s.stderr?.on("data",l=>{c.push(l);}),s.on("close",l=>{let P=l??1;if(P!==0&&c.length>0){let C=Buffer.concat(c).toString("utf8");for(let{pattern:x,message:m}of Rt){let h=C.match(x);if(h){process.stderr.write(m(h)+`
29
- `),a(P);return}}process.stderr.write(C);}a(P);}),s.on("error",l=>{process.stderr.write(`${S(l)}
30
- `),a(1);});})}catch(n){return process.stderr.write(`${S(n)}
31
- `),1}}async function k(t,e){try{let r=await F(e?.cwd),n=r.cmd,i=[...r.baseArgs,...t],o=await execa(n,i,{cwd:e?.cwd,env:{...process.env,...e?.env},reject:false,stdio:"pipe"});return {exitCode:typeof o.exitCode=="number"?o.exitCode:1,stdout:(o.stdout??"").toString(),stderr:(o.stderr??"").toString()}}catch(r){return {exitCode:1,stdout:"",stderr:`${S(r)}
32
- `}}}function at(t){let e=new Set,r=t.split(`
33
- `),n=false;for(let i of r){let o=i.replace(/\r$/,"");if(!n){/^\s*Commands:\s*$/i.test(o)&&(n=true);let c=o.match(/^\s*rapidkit\s+([a-z0-9_-]+)\b/i);if(c){let l=c[1].trim();l&&!l.startsWith("-")&&e.add(l);}continue}if(!o.trim())break;if(/^\s*(Options|Arguments|Usage|Commands)\s*:/i.test(o))continue;let a=o.match(/^\s*([a-z0-9][a-z0-9_-]*)\b/i);if(!a)continue;let s=a[1].trim();s&&!s.startsWith("-")&&e.add(s);}return e}async function ct(){let t=nt();if(!await p.pathExists(t))return null;try{let e=await p.readJson(t);if(e&&e.schema_version===1&&Array.isArray(e.commands))return e}catch{}return null}async function z(t){let e=nt();await p.ensureDir(u.dirname(e)),await p.writeJson(e,t,{spaces:2});}async function bt(){let t=await k(["version","--json"],{cwd:process.cwd()});if(t.exitCode===0)try{let r=JSON.parse(t.stdout)?.version;return typeof r=="string"?r:void 0}catch{return}}async function At(){let t=await k(["commands","--json"],{cwd:process.cwd()});if(t.exitCode!==0)return null;try{let e=JSON.parse(t.stdout);if(e?.schema_version!==1||!Array.isArray(e.commands))return null;let r=e.commands.filter(n=>typeof n=="string");return r.length?r:null}catch{return null}}async function Gt(){let e=Date.now(),r=await ct(),n=await bt(),i=!!r?.commands?.length;if(i&&e-r.fetched_at<864e5&&(!n||!r.rapidkit_version||r.rapidkit_version===n))return new Set(r.commands);let o=await At();if(o?.length){let l=Array.from(new Set(o)).sort();return await z({schema_version:1,fetched_at:e,rapidkit_version:n,commands:l}),new Set(l)}let a=await k(["--help"],{cwd:process.cwd()});if(a.exitCode!==0)return i&&r?.commands?new Set(r.commands):new Set(M);let s=at(a.stdout);if(s.size===0)return new Set(M);let c=Array.from(s).sort();return await z({schema_version:1,fetched_at:e,rapidkit_version:n,commands:c}),s}async function Lt(){let e=Date.now(),r=await ct();return !r||e-r.fetched_at>=864e5||!r.commands?.length?null:new Set(r.commands)}function dt(){return u.join(j(),"rapidkit","npm-bridge","modules-catalog.json")}async function It(){let t=dt();if(!await p.pathExists(t))return null;try{let e=await p.readJson(t);if(e&&e.schema_version===1&&Array.isArray(e.modules))return e}catch{}return null}async function Z(t){let e=dt();await p.ensureDir(u.dirname(e)),await p.writeJson(e,t,{spaces:2});}function X(t){try{return JSON.parse(t)}catch{return null}}async function Kt(t={}){let e=typeof t.ttlMs=="number"?t.ttlMs:18e5,r=Date.now(),n=await It();if(n?.fetched_at&&r-n.fetched_at<e)return n;let i=["modules","list","--json-schema","1"];t.category&&i.push("--category",t.category),t.tag&&i.push("--tag",t.tag),t.detailed&&i.push("--detailed");let o=await k(i,{cwd:t.cwd,env:t.env});if(o.exitCode===0){let s=X(o.stdout);if(s&&s.schema_version===1&&Array.isArray(s.modules)){let c={...s,fetched_at:r};return await Z(c),c}}let a=await k(["modules","list","--json"],{cwd:t.cwd,env:t.env});if(a.exitCode===0){let s=X(a.stdout);if(Array.isArray(s)){let c={schema_version:1,generated_at:new Date().toISOString(),filters:{category:t.category??null,tag:t.tag??null,detailed:!!t.detailed},stats:{total:s.length,returned:s.length,invalid:0},modules:s,source:"legacy-json",fetched_at:r};return await Z(c),c}}return n||null}var Jt={pythonCommandCandidates:O,pickSystemPython:ot,ensureBridgeVenv:N,ensureBridgeVenvFromCandidates:B,parseCoreCommandsFromHelp:at,tryRapidkit:rt,findUserLocalRapidkitRunner:tt,findWorkspaceRunner:it,checkRapidkitCoreAvailable:vt,checkRapidkitCoreVersionCompatible:kt,isVersionSatisfyingConstraint:st};export{M as a,vt as b,kt as c,xt as d,Bt as e,Ft as f,k as g,Gt as h,Lt as i,Kt as j,Jt as k};
@@ -1 +0,0 @@
1
- import {a,b}from'./chunk-S5KTATOU.js';import {d}from'./chunk-X7PWDIQW.js';function f(r){let s=new Map;for(let n of r.projects)s.has(n.name)||s.set(n.name,d(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)??d({missing:t.id}),g=[...b(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:d({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,2 +0,0 @@
1
- import {e,a}from'./chunk-TYZPPUBH.js';import d from'path';import g from'fs-extra';var f="workspace-context.v1",w=".rapidkit/reports/workspace-context-agent.json";function h(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="orca"?t:"generic"}function y(e){return `npx --yes --package rapidkit rapidkit ${e}`.trim()}function j(e){return `npx rapidkit ${e}`.trim()}function i(e){return {id:e.id,scope:e.scope,display:j(e.args),execute:y(e.args),description:e.description,...e.project?{project:e.project}:{}}}function k(e,t){return `workspace run ${t} --scope project:${e.name}`}function C(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function v(e){return [e.name,e.path,d.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function x(e,t){let s=[i({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model."}),i({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification."}),i({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop."}),i({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges."}),i({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions."})],r=t?[t]:e.projects;for(let o of r)o.commands.fleetStages.includes("test")&&s.push(i({id:`project.${o.name}.test`,scope:"project",project:o.name,args:k(o,"test"),description:`Run tests for ${o.name} through workspace orchestration.`})),o.commands.fleetStages.includes("build")&&s.push(i({id:`project.${o.name}.build`,scope:"project",project:o.name,args:k(o,"build"),description:`Build ${o.name} through workspace orchestration.`}));return s}function W(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function b(e,t){if(!t?.startsWith("project:"))return;let s=C(t);if(s)return e.projects.find(r=>v(r).includes(s))}function S(e,t,s){let r=[...e.validation?.issues??[]];t?.startsWith("project:")&&!s&&r.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let o=r.filter(a=>a.severity==="error").length,c=r.filter(a=>a.severity==="warning").length;return {status:o>0?"failed":c>0?"warning":"passed",errors:o,warnings:c,issues:r}}function P(e){let t=[],s=[];for(let[r,o]of Object.entries(e.evidence))o?.exists?t.push(`${r}: ${o.path}`):s.push(r);return {available:t.sort(),missing:s.sort()}}function A(e){let t=e.summary.projectCount,s=e.summary.runtimes.length?e.summary.runtimes.join(", "):"no runtime",r=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${s} runtime coverage, and ${r}.`}function M(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&t.push("Some projects are observed rather than first-class; command support may be partial."),t}async function V(e$1){let t=e$1.model??await e({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),s=h(e$1.agent),r=b(t,e$1.scope),o=S(t,e$1.scope,r);if(e$1.strict===true&&o.status!=="passed"){let n=o.issues.map(p=>`${p.severity}:${p.code}:${p.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${n}`)}let c=(r?[r]:t.projects).map(n=>({name:n.name,path:n.path,kind:n.kind,runtime:n.runtime,framework:n.frameworkDisplayName,...n.generator?{generator:n.generator}:{},createCapability:n.createCapability,supportTier:n.supportTier,safeCommands:W(n),importantFiles:n.importantFiles})),a=P(t),m=A(t);return {schemaVersion:f,generatedAt:(e$1.now??new Date).toISOString(),agent:s,workspaceSummary:m,modelRef:".rapidkit/reports/workspace-model.json",workspace:{name:t.workspace.name,root:t.workspace.root,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e$1.scope??"workspace",...r?{activeProject:r.name}:{}},projects:c,safeCommands:x(t,r),evidence:a,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:o,agentInstructions:["Read `.rapidkit/reports/INDEX.json` first, then this context pack and linked evidence reports.","Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx rapidkit workspace agent-sync --write --refresh-context`."],unsafeAssumptions:M(t),humanSummary:[m,`Evidence available: ${a.available.length}. Missing evidence groups: ${a.missing.join(", ")||"none"}.`,r?`Active project scope: ${r.name} (${r.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
2
- `)}}async function N(e,t){let s=d.join(t,w);return await g.ensureDir(d.dirname(s)),await g.writeJSON(s,a(e),{spaces:2}),s}export{f as a,w as b,V as c,N as d};
@@ -1,2 +0,0 @@
1
- import {a as a$1}from'./chunk-HTYMXMQM.js';import {e,c,a,b as b$1}from'./chunk-TYZPPUBH.js';import {c as c$1}from'./chunk-S5KTATOU.js';import pe from'crypto';import u from'path';import w from'fs-extra';import {spawnSync}from'child_process';function S(e,t){let r=spawnSync("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return r.status!==0?{ok:false,stdout:""}:{ok:true,stdout:(r.stdout??"").trim()}}function ce(e){let t=[],r=[],n=[];for(let c of e.split(`
2
- `)){if(!c.trim())continue;let o=c.slice(0,2),i=c.slice(3).trim();if(i){if(o==="??"){r.push(i);continue}o.includes("D")&&n.push(i),t.push(i);}}return {changedFiles:[...new Set(t)].sort(),untrackedFiles:[...new Set(r)].sort(),deletedFiles:[...new Set(n)].sort()}}function z(e,t){let r={available:false,dirty:false,changedFiles:[],untrackedFiles:[],deletedFiles:[]},n=S(e,["rev-parse","--is-inside-work-tree"]);if(!n.ok||n.stdout!=="true")return r;let c=S(e,["rev-parse","--abbrev-ref","HEAD"]),o=S(e,["rev-parse","HEAD"]),i=S(e,["status","--porcelain=v1","--untracked-files=all"]),p=ce(i.stdout),m=p.changedFiles.length>0||p.untrackedFiles.length>0||p.deletedFiles.length>0;return {available:true,branch:c.ok?c.stdout:void 0,commit:o.ok?o.stdout:void 0,ref:t?.ref,dirty:m,changedFiles:p.changedFiles,untrackedFiles:p.untrackedFiles,deletedFiles:p.deletedFiles}}var Q="workspace-model-snapshot.v1",T="workspace-model-diff.v1",E=".rapidkit/reports/workspace-model-snapshot.json",X=".rapidkit/reports/workspace-model-diff-last-run.json",de="workspace-impact.v1",le=".rapidkit/reports/workspace-impact-last-run.json";function Z(e){let t=e.trim().toLowerCase();return t==="git"||t.startsWith("git:")}function me(e){let t=e.trim();return t.toLowerCase()==="git"?"HEAD":t.toLowerCase().startsWith("git:")&&t.slice(4).trim()||"HEAD"}function _(e){if(Array.isArray(e))return e.map(t=>_(t));if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=_(e[r]);return t}return e}function k(e){return JSON.stringify(_(e))}function $(e){let{runId:t,...r}=e,n={...r,generatedAt:"<ignored>",graph:e.graph?{...e.graph,generatedAt:"<ignored>"}:void 0,validation:e.validation?{...e.validation,issues:e.validation.issues.map(c=>({...c})).sort((c,o)=>{let i=`${c.severity}:${c.code}:${c.target}:${c.message}`,p=`${o.severity}:${o.code}:${o.target}:${o.message}`;return i.localeCompare(p)})}:void 0};return pe.createHash("sha256").update(k(n)).digest("hex")}function ee(e,t){return u.isAbsolute(t)?t:u.join(e,t)}async function fe(e){let t=await w.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace model input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion===Q){let n=r;if(!n.model||n.model.schemaVersion!==b$1)throw new Error(`Invalid workspace model snapshot: ${e}`);return {model:n.model,hash:n.modelHash||$(n.model)}}if(r.schemaVersion===b$1){let n=r;return {model:n,hash:$(n)}}throw r.schemaVersion===T?new Error(`workspace diff --from received a diff report (${u.basename(e)}). Use a workspace model snapshot or model report as baseline, e.g. ${E}. To analyze an existing diff report, run: npx rapidkit workspace impact --from ${u.basename(e)} --json`):new Error(`Unsupported workspace model input schema: ${String(r.schemaVersion)}`)}async function ue(e){let t=await w.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace diff input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==T)return null;let n=r;if(!n.currentModel||n.currentModel.schemaVersion!==b$1||!n.summary||!Array.isArray(n.changes))throw new Error(`Invalid workspace model diff report: ${e}`);return n}async function Ve(e$1){let t=e$1.model??await e({workspacePath:e$1.workspacePath,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now});return {schemaVersion:Q,generatedAt:(e$1.now??new Date).toISOString(),modelHash:$(t),modelRef:c,model:t}}async function Ge(e,t){let r=u.join(t,E);return await w.ensureDir(u.dirname(r)),await w.writeJson(r,a(e),{spaces:2}),r}function A(e){return {name:e.name,path:e.path,kind:e.kind,runtime:e.runtime,framework:e.framework,generator:e.generator,supportTier:e.supportTier,commands:e.commands,importantFiles:e.importantFiles}}function h(e,t){e.push(t);}function ge(e,t){let r=[],n=["name","profile","type"],c=["workspaceType","surfaces","runtimeFamilies","businessCapabilities"];for(let o of n){let i=e.workspace[o],p=t.workspace[o];k(i)!==k(p)&&h(r,{type:"workspace.changed",severity:"info",target:`workspace.${o}`,message:`Workspace metadata field changed: ${String(o)}`,before:i,after:p});}for(let o of c){let i=e.identity[o],p=t.identity[o];k(i)!==k(p)&&h(r,{type:"workspace.changed",severity:"info",target:`identity.${o}`,message:`Workspace identity field changed: ${String(o)}`,before:i,after:p});}return k(e.policies)!==k(t.policies)&&h(r,{type:"workspace.changed",severity:"warning",target:"policies",message:"Workspace policy summary changed.",before:e.policies,after:t.policies}),k(e.evidence)!==k(t.evidence)&&h(r,{type:"workspace.changed",severity:"info",target:"evidence",message:"Workspace evidence summary changed.",before:e.evidence,after:t.evidence}),k(e.discovery)!==k(t.discovery)&&h(r,{type:"workspace.changed",severity:"info",target:"discovery",message:"Workspace discovery settings changed.",before:e.discovery,after:t.discovery}),e.contracts.exists!==t.contracts.exists&&h(r,{type:"workspace.changed",severity:t.contracts.exists?"info":"warning",target:t.contracts.workspaceContractPath,message:"Workspace contract presence changed.",before:e.contracts.exists,after:t.contracts.exists}),r}function ke(e,t){let r=e.validation??null,n=t.validation??null;return k(r)===k(n)?[]:[{type:"validation.changed",severity:n?.status==="failed"?"critical":"warning",target:"validation",message:"Workspace model validation changed.",before:r,after:n}]}function he(e,t){let r=[],n=new Map(e.projects.map(o=>[o.path,o])),c=new Map(t.projects.map(o=>[o.path,o]));for(let[o,i]of c.entries()){let p=n.get(o);if(!p){h(r,{type:"project.added",severity:"info",target:o,message:`Project added: ${i.name}`,after:A(i)});continue}let m=A(p),l=A(i);if(k(m)!==k(l)){let f=p.runtime!==i.runtime||p.framework!==i.framework;h(r,{type:"project.changed",severity:f?"warning":"info",target:o,message:`Project changed: ${i.name}`,before:m,after:l});}}for(let[o,i]of n.entries())c.has(o)||h(r,{type:"project.removed",severity:"warning",target:o,message:`Project removed: ${i.name}`,before:A(i)});return r.sort((o,i)=>`${o.type}:${o.target}`.localeCompare(`${i.type}:${i.target}`))}async function we(e$1){let t=u.resolve(e$1.workspacePath),r=Z(e$1.fromPath),n=r?me(e$1.fromPath):void 0,c$1=e$1.fromPath;if(r){let g=u.join(t,E);if(!await w.pathExists(g))throw new Error("Git-aware workspace diff requires an existing snapshot at .rapidkit/reports/workspace-model-snapshot.json. Run: npx rapidkit workspace snapshot --json");c$1=E;}let o=ee(t,c$1),i=await fe(o),p=e$1.model??await e({workspacePath:t,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),m=$(p),l=[...ge(i.model,p),...he(i.model,p),...ke(i.model,p)],f;e$1.includeGitObservation!==false&&(f=e$1.gitObservation??z(t,{ref:n}),f.available&&ve(l,f,p));let v=l.filter(g=>g.type.startsWith("git.")).length,I=i.hash!==m,y=r?`git:${n??"HEAD"}`:u.relative(t,o).split(u.sep).join("/");return {schemaVersion:T,generatedAt:(e$1.now??new Date).toISOString(),fromRef:y,toRef:c,fromHash:i.hash,toHash:m,summary:{changed:I||v>0,addedProjects:l.filter(g=>g.type==="project.added").length,removedProjects:l.filter(g=>g.type==="project.removed").length,changedProjects:l.filter(g=>g.type==="project.changed").length,workspaceChanges:l.filter(g=>g.type==="workspace.changed").length,validationChanges:l.filter(g=>g.type==="validation.changed").length,gitChangedFiles:v},git:f?.available?je(f,n):{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:l,currentModel:p}}async function Ne(e,t){let r=u.join(t,X);return await w.ensureDir(u.dirname(r)),await w.writeJson(r,a(e),{spaces:2}),r}function M(e){return {none:0,low:1,medium:2,high:3,critical:4}[e]}function q(e){return e.reduce((t,r)=>M(r)>M(t)?r:t,"none")}var H=["none","low","medium","high","critical"];function ye(e){let t=Math.max(1,M(e)-1);return H[t]}function We(e){let t=Math.min(H.length-1,M(e)+1);return H[t]}function J(e){return e.join(" ")}function b(e,t,r,n){return {id:e,label:t,scope:n.scope,project:n.project,display:J(["npx","rapidkit",...r]),execute:J(["npx","--yes","--package","rapidkit","rapidkit",...r]),required:n.required!==false}}function U(e){let t=`project:${e.name}`;return [b(`project.${e.name}.test`,`Run tests for ${e.name}`,["workspace","run","test","--scope",t,"--json"],{scope:"project",project:e.name,required:e.commands.fleetStages.includes("test")}),b(`project.${e.name}.build`,`Run build for ${e.name}`,["workspace","run","build","--scope",t,"--json"],{scope:"project",project:e.name,required:e.commands.fleetStages.includes("build")})]}function D(){return [b("workspace.doctor","Run workspace doctor",["doctor","workspace","--json"],{scope:"workspace"}),b("workspace.contract.verify","Verify workspace contract",["workspace","contract","verify","--json"],{scope:"workspace"}),b("workspace.readiness","Run release readiness",["readiness","--json"],{scope:"workspace"}),b("workspace.analyze","Run workspace analyze",["analyze","--json"],{scope:"workspace",required:false}),b("workspace.pipeline","Run governance pipeline",["pipeline","--json"],{scope:"workspace",required:false})]}function be(e,t){let r=t.split(u.sep).join("/");return e.projects.filter(c=>{let o=c.path.split(u.sep).join("/");return r===o||r.startsWith(`${o}/`)}).sort((c,o)=>o.path.length-c.path.length)[0]}function ve(e,t,r){let n=new Set(e.map(o=>o.target)),c=(o,i)=>{let p=i.split(u.sep).join("/"),m=`git:${p}`;if(n.has(m))return;let l=be(r,p),f=l?`${l.name} (${l.path})`:"workspace";h(e,{type:o,severity:o==="git.deleted"?"warning":"info",target:m,message:`Git ${o==="git.untracked"?"untracked":o==="git.deleted"?"deleted":"changed"} file affects ${f}: ${p}`,after:{path:p,project:l?.name,projectPath:l?.path}}),n.add(m);};for(let o of t.changedFiles)c("git.file.changed",o);for(let o of t.untrackedFiles)c("git.untracked",o);for(let o of t.deletedFiles)c("git.deleted",o);}function je(e,t){return {available:true,ref:t??e.ref,branch:e.branch,commit:e.commit,dirty:e.dirty,changedFiles:e.changedFiles.length,untrackedFiles:e.untrackedFiles.length,deletedFiles:e.deletedFiles.length}}function Me(e){let t=new Set,r=[];for(let n of e){let c=`${n.scope}:${n.project??""}:${n.display}`;t.has(c)||(t.add(c),r.push(n));}return r}function Pe(e){return e.type==="project.removed"?"high":e.severity==="critical"?"critical":e.severity==="warning"?"high":("medium")}function Ie(e,t){return e.severity==="critical"?"critical":e.target==="policies"||e.target.includes("contract")?"high":e.type==="validation.changed"?(t?.projectCount??0)===0?"low":"high":e.target==="evidence"?"low":e.severity==="warning"?"medium":"low"}function Ce(e){return e.affectedProjects>0||e.projectCount>0||!e.changes.every(r=>r.severity==="critical"?false:r.type.startsWith("git.")||r.type==="validation.changed")?e.risk:M(e.risk)>=M("high")||e.risk==="medium"?"low":e.risk}function Y(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return [t.name,t.path,u.basename(t.path),t.absolutePath].filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim().toLowerCase()).includes(r)}function Re(e){if(!e.changed)return {headline:"No workspace model impact detected.",bullets:["The current workspace model matches the provided snapshot/report."],unsafeAssumptions:["Do not claim runtime verification passed unless a report exists."]};let t=e.affectedProjects.map(r=>r.project?.name??r.target);return {headline:`Workspace impact risk: ${e.risk}.`,bullets:[`Affected projects: ${t.length?t.join(", "):"none"}.`,`Workspace-level items: ${e.workspaceImpact.length}.`,"Use the verification plan before recommending apply, rollback, or release actions."],unsafeAssumptions:["Do not infer test/build success from impact alone.","Do not apply fixes without project scope and verification evidence.","Use display commands for users and execute commands for automation."]}}async function Be(e){let t=u.resolve(e.workspacePath),r=Z(e.fromPath),n=e.diff;if(!n&&!r){let a=ee(t,e.fromPath);n=await ue(a)??void 0;}n||(n=await we({workspacePath:t,fromPath:e.fromPath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,includeGitObservation:e.includeGitObservation,gitObservation:e.gitObservation,now:e.now,model:e.model}));let c=new Map(n.currentModel.projects.map(a=>[a.path,a])),o=new Map(n.currentModel.projects.map(a=>[a.name,a])),i=n.changes.filter(a=>a.type.startsWith("project.")),p=new Map;for(let a of i){let d=(c.get(a.target)??(typeof a.before?.name=="string"?o.get(a.before.name):void 0))?.path??a.target,W=p.get(d)??[];W.push(a),p.set(d,W);}let m=[];for(let[a,s]of p.entries()){let d=c.get(a);if(d&&!Y(e.scope,d))continue;let W=q(s.map(Pe)),C=d?.name??(typeof s[0]?.before?.name=="string"?String(s[0].before.name):a);m.push({id:`project:${C}`,scope:"project",target:a,title:`Project impact: ${C}`,summary:s.map(j=>j.message).join(" "),risk:W,reasons:s.map(j=>`${j.type}: ${j.message}`),project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?U(d):D()});}let l=n.currentModel.graph,f=l?a$1(l):void 0,v=new Set(m.map(a=>a.project?.name).filter(a=>typeof a=="string")),I=new Map;for(let a of m)if(a.project?.name){let s=f?.byId.get(a.project.name);s&&(a.centrality={fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness,isHotspot:s.isHotspot},s.isHotspot&&(a.risk=We(a.risk),a.reasons=[...a.reasons,`graph.hotspot: critical-path project with ${s.reach} transitive dependent(s); risk escalated.`])),a.origin="direct",a.distance=0,I.set(a.project.name,a.risk);}let y=[],g=0;if(l&&v.size>0){let a=c$1(l,v);for(let s of a.values()){if(s.distance===0||v.has(s.id))continue;let d=o.get(s.id);if(d&&!Y(e.scope,d))continue;let W=s.path[0],C=s.path[s.path.length-2]??W,j=I.get(W)??"medium",ae=ye(j);g=Math.max(g,s.distance),y.push({id:`transitive:${s.id}`,scope:"project",target:d?.path??s.id,title:`Transitive impact: ${s.id}`,summary:`Depends on changed project ${W}${s.via?` via ${s.via}`:""} (distance ${s.distance}).`,risk:ae,reasons:[`graph.dependent: depends on ${C}${s.via?` via ${s.via}`:""} (path ${s.path.join(" -> ")})`],project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?U(d):D(),origin:"transitive",distance:s.distance,path:s.path,via:s.via,...f?.byId.get(s.id)?{centrality:{fanIn:f.byId.get(s.id).fanIn,fanOut:f.byId.get(s.id).fanOut,reach:f.byId.get(s.id).reach,betweenness:f.byId.get(s.id).betweenness,isHotspot:f.byId.get(s.id).isHotspot}}:{}});}}y.sort((a,s)=>a.target.localeCompare(s.target));let te=f?f.hotspots.map(a=>{let s=f.byId.get(a);return {project:a,fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness}}):[],re=n.changes.filter(a=>!a.type.startsWith("project.")),V=n.currentModel.summary?.projectCount??n.currentModel.projects.length,P=re.map(a=>({id:`workspace:${a.target}`,scope:"workspace",target:a.target,title:`Workspace impact: ${a.target}`,summary:a.message,risk:Ie(a,{projectCount:V}),reasons:[`${a.type}: ${a.message}`],verification:D()})),G=Me([...m.flatMap(a=>a.verification),...y.flatMap(a=>a.verification),...P.flatMap(a=>a.verification),...n.summary.changed?D():[]]).filter(a=>a.required),ne=q([...m.map(a=>a.risk),...y.map(a=>a.risk),...P.map(a=>a.risk)]),N=Ce({risk:ne,affectedProjects:m.length,projectCount:V,changes:n.changes}),B={changed:n.summary.changed,risk:N,affectedProjects:m.length,workspaceItems:P.length,recommendedCommands:G.length,blastRadius:{directlyAffected:m.length,transitivelyAffected:y.length,maxDistance:g,graphEdges:l?.edges.length??0}};return {schemaVersion:de,generatedAt:(e.now??new Date).toISOString(),fromRef:n.fromRef,diffRef:X,workspace:{name:n.currentModel.workspace.name,profile:n.currentModel.workspace.profile,type:n.currentModel.workspace.type},summary:B,affectedProjects:m.sort((a,s)=>a.target.localeCompare(s.target)),transitiveImpact:y,criticalPathHotspots:te,workspaceImpact:P.sort((a,s)=>a.target.localeCompare(s.target)),verificationPlan:G,agentBrief:Re({changed:B.changed,risk:N,affectedProjects:m,workspaceImpact:P}),diff:n}}async function Ke(e,t){let r=u.join(t,le);return await w.ensureDir(u.dirname(r)),await w.writeJson(r,a(e),{spaces:2}),r}export{Q as a,T as b,E as c,X as d,de as e,le as f,Z as g,me as h,Ve as i,Ge as j,we as k,Ne as l,D as m,Be as n,Ke as o};
@@ -1 +0,0 @@
1
- import {e as e$1,a as a$4,d}from'./chunk-X7PWDIQW.js';import {g,a as a$5}from'./chunk-GDGATWR5.js';import {a}from'./chunk-RV6HBTFC.js';import {a as a$3,q as q$1,k}from'./chunk-YBS2HGO3.js';import {i,h}from'./chunk-UZW5QFRW.js';import {a as a$2}from'./chunk-VKLL63TL.js';import {e}from'./chunk-GOM3RFB3.js';import {a as a$1}from'./chunk-HHJAANUC.js';import m from'path';import P from'fs-extra';import rt from'crypto';import {createRequire}from'module';var Ve="unknown-run";function we(t){let e$1=e();return !e$1||e$1===Ve?t:{...t,runId:e$1}}var Ee="workspace-dependency-graph.v1",Pe=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"];var je=".rapidkit/workspace-graph.overrides.json",$e=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),Ke=new Set([".git",".hg",".svn",".rapidkit",".venv","node_modules","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),be=600,Se=5,He=256*1024,ve={inferred:1,contract:2,manual:3};function Be(t){return t.split(m.sep).join("/")}function H(t,e){return Be(m.relative(t,e)||".")}function Ce(t){let e=new Map;for(let n of t.projects)e.has(n.name)||e.set(n.name,{id:n.name,path:n.path,...n.runtime?{runtime:n.runtime}:{},...n.framework?{framework:n.framework}:{},...n.kind?{kind:n.kind}:{}});return [...e.values()].sort((n,s)=>n.id.localeCompare(s.id))}function We(t,e){let n=new Map,s=new Map;for(let r of e.projects){if(n.has(r.name))continue;let a=r.absolutePath?m.resolve(r.absolutePath):m.resolve(t,r.path);n.set(r.name,a),s.has(a)||s.set(a,r.name);}let o=[...s.entries()].map(([r,a])=>({dir:r,id:a})).sort((r,a)=>a.dir.length-r.dir.length||r.dir.localeCompare(a.dir));return {idToDir:n,dirToId:s,sortedDirs:o}}function B(t,e){let n=m.resolve(e);for(let{dir:s,id:o}of t.sortedDirs)if(n===s||n.startsWith(`${s}${m.sep}`))return o;return null}async function ee(t){try{if(!await P.pathExists(t))return null;let e=await P.readJSON(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}async function ne(t){try{return await P.pathExists(t)?await P.readFile(t,"utf8"):null}catch{return null}}async function Re(t,e){let n=[],s=new Map;for(let[o,r]of e.idToDir.entries()){let a=await ee(m.join(r,"package.json")),i=typeof a?.name=="string"?a.name.trim():"";i&&!s.has(i)&&s.set(i,o);}for(let[o,r]of e.idToDir.entries()){let a=await ee(m.join(r,"package.json"));if(a){let i=["dependencies","devDependencies","peerDependencies","optionalDependencies"],c=new Set;for(let p of i){let l=a[p];if(!(!l||typeof l!="object"||Array.isArray(l)))for(let d of Object.keys(l)){let u=s.get(d);!u||u===o||c.has(u)||(c.add(u),n.push({from:o,to:u,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:H(t,m.join(r,"package.json")),detail:`declares dependency ${d}`}]}));}}}n.push(...await Le(t,e,o,r)),n.push(...await ze(t,e,o,r));}return n}async function Le(t,e,n,s){let o=await ne(m.join(s,"pyproject.toml"));if(!o)return [];let r=[],a=new Set,i=/path\s*=\s*["']([^"']+)["']/g,c;for(;(c=i.exec(o))!==null;){let p=B(e,m.resolve(s,c[1]));!p||p===n||a.has(p)||(a.add(p),r.push({from:n,to:p,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:H(t,m.join(s,"pyproject.toml")),detail:`path dependency ${c[1]}`}]}));}return r}async function ze(t,e,n,s){let o=await ne(m.join(s,"go.mod"));if(!o)return [];let r=[],a=new Set,i=/replace\s+\S+\s+=>\s+(\.[^\s]+)/g,c;for(;(c=i.exec(o))!==null;){let p=B(e,m.resolve(s,c[1]));!p||p===n||a.has(p)||(a.add(p),r.push({from:n,to:p,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:H(t,m.join(s,"go.mod")),detail:`go.mod replace ${c[1]}`}]}));}return r}async function Je(t,e){let n=[],s=[t];for(;s.length>0&&n.length<e;){let o=s.shift();if(!o)continue;let r=[];try{r=await P.readdir(o,{withFileTypes:true});}catch{continue}let a=[],i=[];for(let c of r)if(c.isDirectory()){if(Ke.has(c.name)||c.name.startsWith("."))continue;a.push(m.join(o,c.name));}else c.isFile()&&$e.has(m.extname(c.name))&&i.push(m.join(o,c.name));i.sort((c,p)=>c.localeCompare(p)),a.sort((c,p)=>c.localeCompare(p));for(let c of i){if(n.length>=e)break;n.push(c);}s.push(...a);}return n}var qe=[/\bfrom\s+["']([^"']+)["']/g,/\bimport\s+["']([^"']+)["']/g,/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g];function Ue(t){let e=new Set;for(let n of qe){n.lastIndex=0;let s;for(;(s=n.exec(t))!==null;){let o=s[1];o.startsWith(".")&&e.add(o);}}return [...e]}async function te(t,e,n,s){let o=new Map;for(let[r,a]of e.idToDir.entries()){if(s&&!s.has(r))continue;let i=await Je(a,n);for(let c of i){let p=await P.stat(c).catch(()=>null);if(!p||p.size>He)continue;let l=await ne(c);if(l)for(let d of Ue(l)){let u=m.resolve(m.dirname(c),d),k=B(e,u);if(!k||k===r)continue;let j=`${r}\0${k}`,y=o.get(j);y||(y={from:r,to:k,evidence:[]},o.set(j,y)),y.evidence.length<Se&&y.evidence.push({file:H(t,c),detail:`imports ${d}`});}}}return [...o.values()].map(r=>({from:r.from,to:r.to,kind:"code-import",source:"inferred",confidence:"medium",evidence:r.evidence}))}function Xe(t,e,n){let s=new Map;for(let o of n.projects){let r=Ye(t,e,o);r&&s.set(o.slug,r);}return s}function Ye(t,e,n){let s=[n.relativePath,n.externalPath].filter(o=>typeof o=="string"&&o.length>0);for(let o of s){let r=m.resolve(t,o),a=e.dirToId.get(r)??B(e,r);if(a)return a}return e.idToDir.has(n.slug)?n.slug:null}function Me(t,e,n){let s=[],o=Xe(t,e,n),r=a$5,a=new Map,i=new Map;for(let c of n.projects){let p=o.get(c.slug);if(!p)continue;let l=c.contracts??{publishes:[],consumes:[],dependsOn:[]};for(let d of l.dependsOn??[]){let u=o.get(d);!u||u===p||s.push({from:p,to:u,kind:"service-dependsOn",source:"contract",confidence:"high",evidence:[{file:r,detail:`dependsOn ${d}`}]});}for(let d of l.publishes??[])a.has(d)||a.set(d,new Set),a.get(d)?.add(p);for(let d of l.consumes??[])i.has(d)||i.set(d,new Set),i.get(d)?.add(p);}for(let[c,p]of a.entries()){let l=i.get(c);if(l)for(let d of l)for(let u of p)d!==u&&s.push({from:d,to:u,kind:"event-pub-sub",source:"contract",confidence:"high",evidence:[{file:r,detail:`consumes event ${c}`}]});}return s.push(...Qe(n,o)),s}function Z(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}function Qe(t,e){let n=[],s=t.projects.map(o=>({project:o,id:e.get(o.slug)})).filter(o=>!!o.id).filter(o=>Z(o.project.slug).length>=3);for(let o of t.projects){let r=e.get(o.slug);if(!r)continue;let a=o.contracts?.env??[];if(a.length===0)continue;let i=new Set;for(let c of a){let p=Z(c);for(let l of s)l.id===r||i.has(l.id)||!(p.includes(Z(l.project.slug))&&(l.project.ports?.length??0)>0)||(i.add(l.id),n.push({from:r,to:l.id,kind:"shared-resource",source:"inferred",confidence:"low",evidence:[{file:a$5,detail:`env ${c} references ${l.project.slug}`}]}));}}return n}async function xe(t,e){let n=await ee(m.join(t,je)),s=Array.isArray(n?.edges)?n?.edges:[],o=[],r=new Set(Pe);for(let a of s){if(!a||typeof a!="object"||Array.isArray(a))continue;let i=a,c=typeof i.from=="string"?i.from:"",p=typeof i.to=="string"?i.to:"",l=typeof i.kind=="string"?i.kind:"";if(!e.has(c)||!e.has(p)||c===p||!r.has(l))continue;let d=Array.isArray(i.evidence)?i.evidence.map(u=>u&&typeof u=="object"&&typeof u.file=="string"?{file:u.file,...typeof u.detail=="string"?{detail:u.detail}:{}}:null).filter(u=>!!u):[];o.push({from:c,to:p,kind:l,source:"manual",confidence:"high",evidence:d.length>0?d:[{file:je,detail:"manual edge"}]});}return o}function Ze(t){return `${t.from}\0${t.to}\0${t.kind}`}function et(t){let e=new Set,n=[];for(let s of t){let o=`${s.file}\0${s.detail??""}`;e.has(o)||(e.add(o),n.push(s));}return n.sort((s,o)=>s.file.localeCompare(o.file)||(s.detail??"").localeCompare(o.detail??"")).slice(0,Se)}function tt(t){let e=new Map;for(let n of t){let s=Ze(n),o=e.get(s);if(!o){e.set(s,{...n,evidence:[...n.evidence]});continue}let r=ve[o.source],a=ve[n.source];a>r?e.set(s,{...n,evidence:[...n.evidence,...o.evidence]}):a===r&&o.evidence.push(...n.evidence);}return [...e.values()].map(n=>({from:n.from,to:n.to,kind:n.kind,source:n.source,confidence:n.confidence,evidence:et(n.evidence)})).sort((n,s)=>n.from.localeCompare(s.from)||n.to.localeCompare(s.to)||n.kind.localeCompare(s.kind)||n.source.localeCompare(s.source))}function nt(t,e){let n=new Map;for(let c of t)n.set(c.id,[]);for(let c of e)n.has(c.from)||n.set(c.from,[]),n.get(c.from)?.push(c.to);let s=0,o=1,r=2,a=new Map;for(let c of n.keys())a.set(c,s);let i=c=>{let p=[{id:c,index:0}];for(a.set(c,o);p.length>0;){let l=p[p.length-1],d=n.get(l.id)??[];if(l.index>=d.length){a.set(l.id,r),p.pop();continue}let u=d[l.index];l.index+=1;let k=a.get(u)??s;if(k===o)return true;k===s&&(a.set(u,o),p.push({id:u,index:0}));}return false};for(let c of [...n.keys()].sort())if(a.get(c)===s&&i(c))return true;return false}function Ae(t,e,n,s){let o=tt(n.filter(r=>e.has(r.from)&&e.has(r.to)));return {schemaVersion:Ee,generatedAt:(s??new Date).toISOString(),nodes:t,edges:o,stats:{nodeCount:t.length,edgeCount:o.length,inferredEdges:o.filter(r=>r.source==="inferred").length,contractEdges:o.filter(r=>r.source==="contract").length,manualEdges:o.filter(r=>r.source==="manual").length,hasCycle:nt(t,o)}}}async function Ie(t){let e=m.resolve(t.workspacePath),n=t.maxImportFilesPerProject??be,s=Ce(t.model),o=new Set(s.map(i=>i.id)),r=We(e,t.model),a=[];return a.push(...await Re(e,r)),a.push(...await te(e,r,n)),t.contract&&a.push(...Me(e,r,t.contract)),a.push(...await xe(e,o)),Ae(s,o,a,t.now)}async function De(t){let e=m.resolve(t.workspacePath),n=t.maxImportFilesPerProject??be,s=Ce(t.model),o=new Set(s.map(i=>i.id)),r=We(e,t.model),a=[];if(a.push(...await Re(e,r)),t.structuralChange)a.push(...await te(e,r,n));else {a.push(...await te(e,r,n,t.changedProjectIds));for(let i of t.previousGraph.edges)i.kind==="code-import"&&i.source==="inferred"&&!t.changedProjectIds.has(i.from)&&o.has(i.from)&&o.has(i.to)&&a.push({from:i.from,to:i.to,kind:"code-import",source:"inferred",confidence:i.confidence,evidence:i.evidence});}return t.contract&&a.push(...Me(e,r,t.contract)),a.push(...await xe(e,o)),Ae(s,o,a,t.now)}var re="workspace-model-cache.v1",_e=".rapidkit/cache/workspace-model.v1.json",Oe=["package.json","pyproject.toml","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","rapidkit.project.json",".rapidkit/project.json"],st=[".rapidkit/workspace.contract.json",".rapidkit/workspace.json","rapidkit.workspace.json",".rapidkit/policies.yml",".rapidkit/policies.yaml"],at=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),it=new Set([".git",".rapidkit","node_modules","dist","build","out","target","coverage",".next",".turbo",".cache",".venv"]),ct=1500,_=null;function oe(){if(_)return _;try{_=createRequire(import.meta.url)("../package.json")?.version??"0.0.0";}catch{_="0.0.0";}return _}async function L(t){try{let e=await P.readFile(t);return rt.createHash("sha256").update(e).digest("hex")}catch{return null}}async function dt(t){let e={};for(let o of Oe){let r=await L(m.join(t,o));r&&(e[o]=r);}let n=[],s=[t];for(;s.length>0&&n.length<ct;){let o=s.shift();if(!o)continue;let r=[];try{r=await P.readdir(o,{withFileTypes:true});}catch{continue}let a=[];for(let i of r)if(i.isDirectory()){if(it.has(i.name)||i.name.startsWith("."))continue;a.push(m.join(o,i.name));}else if(i.isFile()&&at.has(m.extname(i.name))){let c=m.join(o,i.name),p=await P.stat(c).catch(()=>null);if(p){let l=m.relative(t,c).split(m.sep).join("/");n.push(`${l}:${p.size}:${Math.round(p.mtimeMs)}`);}}a.sort((i,c)=>i.localeCompare(c)),s.push(...a);}return n.sort((o,r)=>o.localeCompare(r)),d({manifests:e,source:n})}async function z(t,e){let n=m.resolve(t),s={},o=[...new Set(e.map(r=>m.relative(n,m.resolve(r)).split(m.sep).join("/")))].sort((r,a)=>r.localeCompare(a));for(let r of o)s[r]=await dt(m.join(n,r));return s}async function J(t){let e=m.resolve(t),n={};for(let s of st){let o=await L(m.join(e,s));o&&(n[s]=o);}return n}async function q(t){let e=m.resolve(t.workspacePath),n=[...new Set(t.projectPaths.map(r=>m.relative(e,m.resolve(r)).split(m.sep).join("/")))].sort((r,a)=>r.localeCompare(a)),s=[];for(let r of n){let a={};for(let i of Oe){let c=await L(m.join(e,r,i));c&&(a[i]=c);}s.push({project:r,manifests:a});}let o={};for(let r of [".rapidkit/workspace.contract.json",".rapidkit/workspace.json","rapidkit.workspace.json",".rapidkit/policies.yml",".rapidkit/policies.yaml"]){let a=await L(m.join(e,r));a&&(o[r]=a);}return d({cacheSchema:re,cliVersion:t.cliVersion,flags:t.flags,workspaceJson:t.workspaceJson??null,marker:t.marker??null,projects:s,workspaceFiles:o})}async function se(t){let e=m.join(m.resolve(t),_e);try{if(!await P.pathExists(e))return null;let n=await P.readJson(e);return !n||n.schemaVersion!==re||typeof n.inputsHash!="string"||typeof n.cliVersion!="string"||!n.model?null:n}catch{return null}}async function U(t,e){let n=m.join(m.resolve(t),_e);await P.ensureDir(m.dirname(n));let s={schemaVersion:re,...e};return await P.writeJson(n,s,{spaces:2}),n}var pt="workspace-model.v1",lt=".rapidkit/reports/workspace-model.json",ut=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","bun.lock","bun.lockb","deps.edn","project.clj","build.sbt","docker-compose.yml","docker-compose.yaml","terraform.tf"],mt=new Set([".git",".hg",".svn",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next",".turbo"]);function Ne(t,e){return (m.relative(t,e)||".").split(m.sep).join("/")}async function Te(t){try{if(!await P.pathExists(t))return null;let e=await P.readJSON(t);return e&&typeof e=="object"?e:null}catch{return null}}async function gt(t,e){for(let n of e)if(await P.pathExists(m.join(t,n)))return true;return false}function ae(t){let e=Number.parseInt(process.env.RAPIDKIT_WORKSPACE_MODEL_SCAN_DEPTH??"",10),n=typeof t=="number"&&Number.isFinite(t)?t:Number.isFinite(e)?e:4;return Math.min(12,Math.max(1,Math.trunc(n)))}async function ie(t,e){let n=m.resolve(t),s=[{dirPath:n,depth:0}],o=new Set,r=new Set;for(;s.length>0;){let a=s.shift();if(!a)continue;let i=m.resolve(a.dirPath);if(r.has(i))continue;if(r.add(i),i!==n&&await gt(i,ut)){o.add(i);continue}if(a.depth>=e)continue;let c=[];try{c=await P.readdir(i,{withFileTypes:true});}catch{continue}for(let p of c)!p.isDirectory()||mt.has(p.name)||p.name.startsWith(".")&&p.name!==".config"||s.push({dirPath:m.join(i,p.name),depth:a.depth+1});}return Array.from(o).sort((a,i)=>a.localeCompare(i))}function ce(t){let e=new Set,n=[];for(let s of t){let o=m.resolve(s);e.has(o)||(e.add(o),n.push(o));}return n.sort((s,o)=>s.localeCompare(o))}function Ge(t,e){let n=t?.[e];return typeof n=="string"&&n.trim()?n.trim():void 0}function ft(t,e){return t?.[e]===true}function ht(t,e,n){let s=t?.frontend&&typeof t.frontend=="object"&&!Array.isArray(t.frontend)?t.frontend:void 0,o=Ge(s,"generator"),r=Ge(s,"command_display"),a=typeof e=="string"&&e.startsWith("frontend.");if(!(!o&&!a))return {...o?{id:o}:{},...e?{kit:e}:{},displayName:n,source:ft(s,"official_generator")?"official-generator":"metadata",...r?{commandDisplay:r}:{}}}async function kt(t){let e=[".rapidkit/project.json",".rapidkit/context.json","package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","Dockerfile","docker-compose.yml","README.md"],n=[];for(let s of e)await P.pathExists(m.join(t,s))&&n.push(s);return n}async function v(t,e,n){let s=m.join(t,e),o=await P.pathExists(s),r={path:e.split(m.sep).join("/"),exists:o};if(o&&n){let a=await Te(s);typeof a?.generatedAt=="string"&&(r.generatedAt=a.generatedAt);let i=a?.status??a?.result??a?.verdict;typeof i=="string"&&(r.status=i);}return r}async function yt(t,e,n){let o=`${Ne(t,e)}/.rapidkit/reports`,r=await v(t,`${o}/doctor-project-last-run.json`,n);return {doctor:r?.exists===true?r:await v(t,`${o}/doctor-last-run.json`,n),analyze:await v(t,`${o}/analyze-last-run.json`,n),readiness:await v(t,`${o}/release-readiness-last-run.json`,n)}}async function wt(t,e,n){let s=a$3(e),o=i(e,s),r=q$1(e),a=k(o.runtime),i$1=await e$1(e,s),c=typeof s?.name=="string"&&s.name.trim()?s.name.trim():m.basename(e),p=typeof s?.kit_name=="string"?s.kit_name:typeof s?.kit=="string"?s.kit:void 0,l=typeof s?.engine=="string"?s.engine:r.engine!=="unknown"?r.engine:void 0,d=ht(s,p,o.displayName),u=a$4({kitId:p,framework:o.key,runtime:o.runtime});return {name:c,path:Ne(t,e),...n.includeAbsolutePaths?{absolutePath:e}:{},kind:i$1,runtime:o.runtime,runtimeCandidates:h(e),framework:o.key,frameworkDisplayName:o.displayName,confidence:o.confidence,detectionSource:o.source,supportTier:o.supportTier,runtimeSupportTier:a.tier,runtimeDoctorSupport:a.doctorSupport,moduleSupport:r.moduleSupport,...p?{kit:p}:{},...l?{engine:l}:{},...d?{generator:d}:{},createCapability:u,commands:{supported:r.supportedCommands,unsupported:r.unsupportedCommands,global:r.globalCommands,fleetStages:r.fleetStages,localOnly:r.localOnlyCommands,map:r.commandMap},importantFiles:await kt(e),evidence:await yt(t,e,n.includeEvidence),provenance:{path:"filesystem discovery",runtime:o.source,framework:o.source,commands:"project command capability matrix",createCapability:"create planner capability contract",evidence:"project .rapidkit/reports"}}}async function de(t){return Te(m.join(t,".rapidkit","workspace.json"))}function Et(t){return t.some(e=>e.kind==="frontend")&&t.length>1?"full-stack-workspace":t.some(e=>e.kind==="frontend")?"frontend-workspace":t.length>1?"backend-platform":"backend-workspace"}function Pt(t){let e=new Set;for(let n of t){let s=`${n.name} ${n.path}`.toLowerCase();for(let o of ["auth","billing","payment","notification","order","admin","report","search","analytics"])s.includes(o)&&e.add(o);}return Array.from(e).sort()}function E(t,e,n,s){return {severity:t,code:e,message:n,target:s}}function Fe(t){let e=[];t.workspace.name.trim()||e.push(E("error","workspace.name.missing","Workspace name could not be resolved.","workspace")),t.workspace.type==="observed-workspace"&&e.push(E("warning","workspace.marker.missing","Workspace marker is missing; model is based on filesystem observation.","workspace.marker")),t.summary.projectCount===0&&e.push(E("warning","workspace.projects.empty","No project roots were detected in this workspace.","projects")),t.contracts.exists||e.push(E("warning","workspace.contract.missing","Workspace contract is missing; dependency and API edges may be incomplete.",t.contracts.workspaceContractPath));let n=new Map;for(let r of t.projects){let a=r.name.toLowerCase(),i=n.get(a)??[];i.push(r),n.set(a,i),r.importantFiles.length||e.push(E("warning","project.markers.missing",`Project ${r.name} has no important manifest files recorded.`,r.path)),r.runtime==="unknown"&&e.push(E("warning","project.runtime.unknown",`Project ${r.name} runtime could not be confidently detected.`,r.path));let c=["test","build"];for(let d of c)r.commands.supported.includes(d)&&r.commands.unsupported.includes(d)&&e.push(E("error","project.commands.conflict",`Project ${r.name} marks ${d} as both supported and unsupported.`,r.path));let p=new Set(r.commands.fleetStages),l=new Set(r.commands.localOnly);for(let d of r.commands.fleetStages){l.has(d)&&e.push(E("error","project.commands.scope-conflict",`Project ${r.name} marks ${d} as both fleet and local-only.`,r.path));let u=r.commands.map[d];(!u||u.status!=="supported"||u.fleetEligible!==true||u.executionScope!=="fleet")&&e.push(E("error","project.commands.fleet-stage-invalid",`Project ${r.name} advertises ${d} as a fleet stage without a supported fleet capability.`,r.path));}for(let d of r.commands.localOnly){let u=r.commands.map[d];(!u||u.status!=="supported"||u.executionScope!=="local-only"||u.fleetEligible===true)&&e.push(E("error","project.commands.local-only-invalid",`Project ${r.name} advertises ${d} as local-only without a matching local-only capability.`,r.path));}for(let d of Object.values(r.commands.map))d.status==="supported"&&(d.fleetEligible===true&&!p.has(d.command)&&e.push(E("error","project.commands.fleet-stage-missing",`Project ${r.name} capability ${d.command} is fleet-eligible but missing from fleetStages.`,r.path)),d.executionScope==="local-only"&&d.fleetEligible!==true&&!l.has(d.command)&&e.push(E("error","project.commands.local-only-missing",`Project ${r.name} capability ${d.command} is local-only but missing from localOnly commands.`,r.path)));}for(let[r,a]of n.entries())a.length>1&&e.push(E("error","project.name.duplicate",`Project name "${r}" is ambiguous across ${a.length} project roots.`,a.map(i=>i.path).join(", ")));let s=e.filter(r=>r.severity==="error").length,o=e.filter(r=>r.severity==="warning").length;return {status:s>0?"failed":o>0?"warning":"passed",errors:s,warnings:o,issues:e}}function an(t){return Fe(t)}async function X(t){let e=m.resolve(t.workspacePath),n=t.includeAbsolutePaths===true,s=t.includeEvidence===true,o=ae(t.observableScanDepth),r=t.now??new Date,[a$3,i,c,p,l]=await Promise.all([a(e),de(e),a$1(e),a$2(e,{descendIntoMatchedProjects:false}),ie(e,o)]),d=ce([...p,...l,...c.map(g=>m.isAbsolute(g.path)?g.path:m.join(e,g.path))]),u=t.reuseProjectModels,k=await Promise.all(d.map(g=>{if(u){let W=m.relative(e,m.resolve(g)).split(m.sep).join("/"),R=u.get(W);if(R)return Promise.resolve(R)}return wt(e,g,{includeAbsolutePaths:n,includeEvidence:s})})),j=typeof i?.workspace_name=="string"?i.workspace_name:typeof i?.name=="string"?i.name:a$3?.name||m.basename(e),y=typeof i?.profile=="string"?i.profile:typeof i?.mode=="string"?i.mode:void 0,x=Array.from(new Set(k.map(g=>g.kind))).sort(),C=Array.from(new Set(k.map(g=>g.runtime))).sort(),Y=Array.from(new Set(k.map(g=>g.framework))).sort(),A=[".rapidkit/policies.yml",".rapidkit/policies.yaml"].find(g=>P.existsSync(m.join(e,g))),I=".rapidkit/workspace.contract.json",b=await P.pathExists(m.join(e,I)),O={schemaVersion:pt,generatedAt:r.toISOString(),workspace:{name:j,root:e,...y?{profile:y}:{},type:a$3?"rapidkit-workspace":"observed-workspace",...a$3?{marker:{createdBy:a$3.createdBy,version:a$3.version,createdAt:a$3.createdAt}}:{}},identity:{workspaceType:Et(k),surfaces:x,runtimeFamilies:C,businessCapabilities:Pt(k)},discovery:{observableScanDepth:o},projects:k,policies:{mode:typeof i?.policy_mode=="string"?i.policy_mode:typeof i?.policyMode=="string"?i.policyMode:"warn",source:A??null,exists:!!A},contracts:{workspaceContractPath:I,exists:b,status:b?"known":"missing"},evidence:{doctor:await v(e,".rapidkit/reports/doctor-last-run.json",s),analyze:await v(e,".rapidkit/reports/analyze-last-run.json",s),readiness:await v(e,".rapidkit/reports/release-readiness-last-run.json",s),pipeline:await v(e,".rapidkit/reports/pipeline-last-run.json",s)},summary:{projectCount:k.length,runtimes:C,frameworks:Y,firstClassProjects:k.filter(g=>g.supportTier==="first-class").length,observedProjects:k.filter(g=>g.supportTier==="observed").length}},D=await St(e,O,{contractExists:b,now:r,incrementalGraph:t.incrementalGraph}),G={...O,graph:D},w=Fe(G);return {...G,validation:w}}async function cn(t){if(t.cache!==true)return {model:await X(t),cache:"disabled"};let e=m.resolve(t.workspacePath),n=ae(t.observableScanDepth),s=oe(),[o,r,a$3,i,c]=await Promise.all([a(e),de(e),a$1(e),a$2(e,{descendIntoMatchedProjects:false}),ie(e,n)]),p=ce([...i,...c,...a$3.map(y=>m.isAbsolute(y.path)?y.path:m.join(e,y.path))]),l=await q({workspacePath:e,cliVersion:s,flags:{includeAbsolutePaths:t.includeAbsolutePaths===true,includeEvidence:t.includeEvidence===true,observableScanDepth:n},projectPaths:p,workspaceJson:r,marker:o}),d=await se(e);if(d&&d.cliVersion===s&&d.inputsHash===l)return {model:d.model,cache:"hit"};let u=await X({...t}),[k,j]=await Promise.all([z(e,p),J(e)]);return await U(e,{cliVersion:s,inputsHash:l,generatedAt:(t.now??new Date).toISOString(),model:u,projectSignatures:k,workspaceFileSignatures:j}),{model:u,cache:"miss"}}function jt(t,e){let n=new Set,s=new Set,o=new Set;for(let[r,a]of Object.entries(e))r in t?t[r]!==a&&n.add(r):s.add(r);for(let r of Object.keys(t))r in e||o.add(r);return {changed:n,added:s,removed:o}}function vt(t={},e={}){let n=new Set([...Object.keys(t),...Object.keys(e)]);for(let s of n)if(t[s]!==e[s])return false;return true}async function dn(t){let e=m.resolve(t.workspacePath),n=ae(t.observableScanDepth),s=oe(),o=t.now??new Date,[r,a$3,i,c,p]=await Promise.all([a(e),de(e),a$1(e),a$2(e,{descendIntoMatchedProjects:false}),ie(e,n)]),l=ce([...c,...p,...i.map(w=>m.isAbsolute(w.path)?w.path:m.join(e,w.path))]),d=await se(e),u=async()=>{let w=await X({...t}),g=await q({workspacePath:e,cliVersion:s,flags:{includeAbsolutePaths:t.includeAbsolutePaths===true,includeEvidence:t.includeEvidence===true,observableScanDepth:n},projectPaths:l,workspaceJson:a$3,marker:r}),[W,R]=await Promise.all([z(e,l),J(e)]);return await U(e,{cliVersion:s,inputsHash:g,generatedAt:o.toISOString(),model:w,projectSignatures:W,workspaceFileSignatures:R}),{model:w,mode:"full"}};if(!d||d.cliVersion!==s||!d.projectSignatures||!d.model?.graph)return u();let k=await J(e);if(!vt(d.workspaceFileSignatures,k))return u();let j=await z(e,l),{changed:y,added:x,removed:C}=jt(d.projectSignatures,j);if(y.size===0&&x.size===0&&C.size===0)return {model:d.model,mode:"unchanged"};let Y=new Set([...y,...x]),A=new Map;for(let w of d.model.projects){let g=w.path.split(m.sep).join("/");!Y.has(g)&&!C.has(g)&&A.set(g,w);}let I=new Set,b=false;for(let w of d.model.projects){let g=w.path.split(m.sep).join("/");y.has(g)&&I.add(w.name);}let O=x.size>0||C.size>0,D=await X({...t,reuseProjectModels:A,incrementalGraph:{previousGraph:d.model.graph,changedProjectIds:I,structuralChange:O||b}});for(let w of d.model.projects){let g=w.path.split(m.sep).join("/");if(!y.has(g))continue;let W=D.projects.find(R=>R.path.split(m.sep).join("/")===g);if(W&&W.name!==w.name){b=true;break}}if(b)return u();let G=await q({workspacePath:e,cliVersion:s,flags:{includeAbsolutePaths:t.includeAbsolutePaths===true,includeEvidence:t.includeEvidence===true,observableScanDepth:n},projectPaths:l,workspaceJson:a$3,marker:r});return await U(e,{cliVersion:s,inputsHash:G,generatedAt:o.toISOString(),model:D,projectSignatures:j,workspaceFileSignatures:k}),{model:D,mode:"incremental"}}async function bt(t){try{let{contract:e}=await g({workspacePath:t});return e&&typeof e=="object"?e:null}catch{return null}}async function St(t,e,n){let s=n.contractExists?await bt(t):null;try{return n.incrementalGraph?await De({workspacePath:t,model:e,contract:s,now:n.now,previousGraph:n.incrementalGraph.previousGraph,changedProjectIds:n.incrementalGraph.changedProjectIds,structuralChange:n.incrementalGraph.structuralChange}):await Ie({workspacePath:t,model:e,contract:s,now:n.now})}catch{let o=e.projects.map(r=>({id:r.name,path:r.path}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:n.now.toISOString(),nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,hasCycle:false}}}}async function pn(t,e){let n=m.join(e,lt);return await P.ensureDir(m.dirname(n)),await P.writeJSON(n,we(t),{spaces:2}),n}export{we as a,pt as b,lt as c,an as d,X as e,cn as f,dn as g,pn as h};
@@ -1,9 +0,0 @@
1
- import {a,b}from'./chunk-KMUWWZRT.js';import {f as f$1,e}from'./chunk-4Q2ZZKGB.js';import {h as h$1,i}from'./chunk-UZW5QFRW.js';import {a as a$1}from'./chunk-VKLL63TL.js';import h from'fs';import o from'path';import s from'chalk';var S=new Set([".git",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function y(e){try{return await h.promises.access(e,h.constants.F_OK),true}catch{return false}}async function z(e){try{let n=JSON.parse(await h.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function T(e){try{return await h.promises.readFile(e,"utf-8")}catch{return ""}}function N(e){return a(e)}async function K(e,n){return await y(o.join(e,".rapidkit","project.json"))||await y(o.join(e,".rapidkit","context.json"))?true:b(e)?false:o.resolve(e)===o.resolve(n)?h$1(e).length>0:h$1(e).length>0}async function O(e){let n=await a$1(e,{skipDirs:S,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:K});return n.length>0?n:b(e)?[]:h$1(e).length>0?[e]:[]}function _(e,n){return o.relative(e,n).replace(/\\/g,"/")||"."}async function A(e,n){for(let t of n)if(await y(o.join(e,t)))return true;return false}async function M(e){return A(e,["health","health.ts","health.js","health.py","health.go","health.kt","health.rb","health.php","healthcheck","health-check","src/health.ts","src/health.js","src/health.py","src/health.go","src/health.kt","src/health.rb","src/health.php","src/healthcheck.ts","src/healthcheck.js","src/liveness.ts","src/readiness.ts","src/ping.ts"])}async function J(e){if(await A(e,["tests","test","__tests__","src/__tests__","pytest.ini","vitest.config.ts","jest.config.ts"]))return true;let t=await z(o.join(e,"package.json")),i=t?.scripts&&typeof t.scripts=="object"?t.scripts:{};return typeof i.test=="string"&&i.test.trim().length>0}async function W(e){let n=await z(o.join(e,"package.json")),t=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return Object.keys(t).sort()}function f(e,n,t,i,r,c){return {id:e,severity:n,target:t,title:i,detail:r,remediation:c}}function H(e){let n=e.reduce((t,i)=>i.severity==="fail"?t+28:i.severity==="warn"?t+12:t+3,0);return Math.max(0,100-n)}async function B(e,n){let t=await z(o.join(n,".rapidkit","project.json")),i$1=i(n,t),r=h$1(n),c=i$1.runtime==="unknown"?r[0]||"unknown":i$1.runtime,a=_(e,n),d=a,u=await W(n),g=await y(o.join(n,".rapidkit","project.json"))||await y(o.join(n,".rapidkit","context.json")),m=await J(n),k=await A(n,["Dockerfile","dockerfile"]),w=await A(n,[".env.example","env.example","config/env.example"]),P=await A(n,[".github/workflows/ci.yml",".github/workflows/ci.yaml",".github/workflows/main.yml",".github/workflows/build.yml",".github/workflows/test.yml",".github/workflows/deploy.yml",".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml"]),R=await M(n),l=[];return i$1.key==="unknown"&&l.push(f("project.stack.unknown","fail",d,"Project stack is unknown","RapidKit cannot confidently classify this backend project.","Add .rapidkit/project.json metadata or import the project with `rapidkit import`.")),g||l.push(f("project.marker.missing","warn",d,"RapidKit marker is missing","The project can be detected by files, but it is not registered with RapidKit metadata.","Run `rapidkit import <path>` from a workspace or create the project through RapidKit.")),m||l.push(f("project.tests.missing","warn",d,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `rapidkit workspace run test --affected` can gate changes.")),w||l.push(f("project.env.example.missing","info",d,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.")),P||l.push(f("project.ci.missing","warn",d,"Continuous integration is missing","No recognized CI/CD configuration file was detected for this project.","Add CI configuration so tests and checks run automatically for every change.")),R||l.push(f("project.health.missing","info",d,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),k||l.push(f("project.container.missing","info",d,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.")),{name:o.basename(n),path:n,relativePath:a,runtime:c,framework:i$1.key,confidence:i$1.confidence,supportTier:i$1.supportTier,hasRapidKitMarker:g,hasTests:m,hasDockerfile:k,hasEnvExample:w,hasCiConfig:P,hasHealthEndpoint:R,scripts:u,findings:l,score:H(l)}}function U(e){return e.name.toLowerCase()}async function V(e){let n=new Map(e.map(r=>[U(r),r])),t=[];for(let r of e){let c=await z(o.join(r.path,"package.json")),a={...c?.dependencies??{},...c?.devDependencies??{},...c?.peerDependencies??{}};for(let u of Object.keys(a)){let g=u.replace(/^@[^/]+\//,"").toLowerCase(),m=n.get(g);m&&m.relativePath!==r.relativePath&&t.push({from:r.relativePath,to:m.relativePath,kind:"package"});}let d=await T(o.join(r.path,"pyproject.toml"));for(let u of e)u.relativePath!==r.relativePath&&d.includes(u.name)&&t.push({from:r.relativePath,to:u.relativePath,kind:"workspace-reference"});}let i=new Set;return t.filter(r=>{let c=`${r.from}\0${r.to}\0${r.kind}`;return i.has(c)?false:(i.add(c),true)})}function L(e,n){let t=new Map;for(let i of e)t.set(i.relativePath,{project:i.relativePath,directDependents:0,directDependencies:0});for(let i of n){let r=t.get(i.from),c=t.get(i.to);r&&(r.directDependencies+=1),c&&(c.directDependents+=1);}return Array.from(t.values()).sort((i,r)=>r.directDependents-i.directDependents||r.directDependencies-i.directDependencies)}async function q(e){let n=await z(o.join(e,".rapidkit","workspace.json"));return typeof n?.profile=="string"?n.profile:null}function Q(e){return {fail:e.filter(n=>n.severity==="fail").length,warn:e.filter(n=>n.severity==="warn").length,info:e.filter(n=>n.severity==="info").length}}function X(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx rapidkit create project <name> --kit <kit>","Import an existing service: npx rapidkit import <path>"]:["Create a RapidKit workspace: npx rapidkit create workspace my-workspace --profile polyglot","Import an existing service: npx rapidkit import ../service"];let n=[];return e.findings.some(t=>t.id==="workspace.marker.missing")&&n.push("Initialize workspace metadata with `rapidkit bootstrap --profile polyglot`."),e.findings.some(t=>t.id==="project.marker.missing")&&n.push("Register detected projects with `rapidkit import <path>` or recreate them via `rapidkit create project`."),e.findings.some(t=>t.id==="project.tests.missing")&&n.push("Add test entrypoints, then gate changes with `rapidkit workspace run test --affected --strict`."),e.findings.some(t=>t.id==="project.ci.missing")&&n.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(t=>t.id==="project.health.missing")&&n.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasGraph||n.push("Create `.rapidkit/workspace-dependency-graph.json` or use analyze output as the first graph seed."),n.push("Run `rapidkit autopilot release --mode audit --json` before release."),Array.from(new Set(n))}async function ae(e$1={}){let n=o.resolve(e$1.workspacePath||process.cwd());if(!await y(n))throw new Error(`Workspace path does not exist: ${n}`);let t=N(n)??n,i=await y(o.join(t,".rapidkit-workspace"))||await y(o.join(t,".rapidkit","workspace.json")),r=await q(t),c=await O(t),a=await Promise.all(c.map(p=>B(t,p))),d=await V(a),u=L(a,d),g=[];i||g.push(f("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered RapidKit workspace.","Run `rapidkit create workspace` or `rapidkit bootstrap --profile polyglot` in a workspace root.")),a.length===0&&g.push(f("workspace.projects.missing","warn",".","No backend projects detected","RapidKit did not find runtime markers or project metadata under this root.","Create a project with `rapidkit create project` or import one with `rapidkit import <path>`."));let m=[...g,...a.flatMap(p=>p.findings)],k=Q(m),w={};for(let p of a)w[p.runtime]=(w[p.runtime]||0)+1;let P=a.length>0?Math.round(a.reduce((p,v)=>p+v.score,0)/a.length):0,R=g.reduce((p,v)=>p+(v.severity==="fail"?20:v.severity==="warn"?8:2),0),l=Math.max(0,P-R),E=k.fail>0||e$1.strict&&k.warn>0?"blocked":k.warn>0?"needs-attention":"ready",j={schemaVersion:"rapidkit-analyze-v1",generatedAt:new Date().toISOString(),workspacePath:t,workspaceDetected:i,profile:r,summary:{score:l,verdict:E,projectCount:a.length,runtimeCount:Object.keys(w).length,findings:k},runtimes:w,projects:a,dependencyGraph:{status:d.length>0?"generated":"empty",edges:d,topImpactedProjects:u.slice(0,5)},findings:m,nextActions:X({findings:m,projectCount:a.length,hasGraph:d.length>0,workspaceDetected:i}),enterpriseControls:{jsonReady:true,ciGateCommand:"rapidkit analyze --json --strict",releaseGateCommand:"rapidkit autopilot release --mode enforce --json",evidencePath:".rapidkit/reports/analyze-last-run.json"}};if(e$1.output&&(await h.promises.mkdir(o.dirname(o.resolve(e$1.output)),{recursive:true}),await h.promises.writeFile(o.resolve(e$1.output),`${JSON.stringify(j,null,2)}
2
- `)),!e$1.output&&i){let p=o.join(t,".rapidkit","reports","analyze-last-run.json");await h.promises.mkdir(o.dirname(p),{recursive:true});let v=f$1(j,{commandId:"workspaceAnalyze",exitCode:j.summary.verdict==="blocked"?2:j.summary.verdict==="needs-attention"?1:0,generatedAt:j.generatedAt,blockers:j.findings.filter(x=>x.severity==="fail").map(x=>x.title).slice(0,12),runId:e()});await h.promises.writeFile(p,`${JSON.stringify(v,null,2)}
3
- `);}return j}function ce(e){let n=e.summary.verdict==="ready"?s.green:e.summary.verdict==="needs-attention"?s.yellow:s.red;if(console.log(s.bold(`
4
- RapidKit Workspace Analysis
5
- `)),console.log(s.cyan("Workspace:"),e.workspacePath),console.log(s.cyan("Profile:"),e.profile||"not configured"),console.log(s.cyan("Score:"),`${e.summary.score}/100`),console.log(s.cyan("Verdict:"),n(e.summary.verdict)),console.log(s.gray(`Projects: ${e.summary.projectCount}, runtimes: ${e.summary.runtimeCount}, findings: ${e.summary.findings.fail} fail / ${e.summary.findings.warn} warn / ${e.summary.findings.info} info`)),e.projects.length>0){console.log(s.bold(`
6
- Projects`));for(let t of e.projects){let i=t.score>=85?s.green("pass"):t.score>=65?s.yellow("watch"):s.red("risk");console.log(` ${t.relativePath} ${s.gray(`${t.runtime}/${t.framework}`)} ${i} ${t.score}/100`);}}if(e.dependencyGraph.status==="generated"&&(console.log(s.bold(`
7
- Dependency Graph`)),console.log(s.gray(` edges: ${e.dependencyGraph.edges.length}`)),e.dependencyGraph.topImpactedProjects.length>0)){console.log(s.gray(" Top impacted projects:"));for(let t of e.dependencyGraph.topImpactedProjects.slice(0,3))console.log(` ${t.project} (${t.directDependents} dependents, ${t.directDependencies} dependencies)`);}if(e.findings.length>0){console.log(s.bold(`
8
- Top Findings`));for(let t of e.findings.slice(0,8)){let i=t.severity==="fail"?s.red:t.severity==="warn"?s.yellow:s.gray;console.log(` ${i(t.severity.toUpperCase())} ${t.target}: ${t.title}`),console.log(s.gray(` ${t.remediation}`));}}console.log(s.bold(`
9
- Next Actions`));for(let t of e.nextActions.slice(0,5))console.log(s.gray(` - ${t}`));console.log();}export{ae as a,ce as b};