@codeyam/codeyam-cli 0.1.0-staging.1669d45 → 0.1.0-staging.27d5a59

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 (898) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +26 -26
  4. package/analyzer-template/packages/ai/index.ts +16 -2
  5. package/analyzer-template/packages/ai/package.json +3 -3
  6. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +110 -52
  7. package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
  8. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +132 -12
  9. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +139 -23
  10. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.ts +10 -17
  11. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +6 -126
  12. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +656 -28
  13. package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
  14. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +94 -7
  15. package/analyzer-template/packages/ai/src/lib/completionCall.ts +229 -64
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +1358 -254
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +5 -1
  18. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +205 -0
  19. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +10 -2
  20. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
  21. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +54 -3
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +124 -17
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
  25. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.ts +62 -0
  26. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +140 -14
  27. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
  28. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
  29. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +393 -97
  30. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
  31. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  32. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +183 -0
  33. package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
  34. package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
  35. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +58 -3
  36. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1012 -7
  37. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +35 -6
  38. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +515 -6
  39. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +1 -1
  40. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +1540 -75
  41. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
  42. package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +51 -3
  43. package/analyzer-template/packages/ai/src/lib/mergeJsonTypeDefinitions.ts +5 -0
  44. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +90 -96
  45. package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
  46. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +10 -7
  47. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
  48. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
  49. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +44 -7
  50. package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
  51. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +179 -45
  52. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +26 -4
  53. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +114 -2
  54. package/analyzer-template/packages/analyze/index.ts +2 -0
  55. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +65 -59
  56. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +132 -33
  57. package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
  58. package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
  59. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  60. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
  61. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
  62. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
  63. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
  64. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
  65. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
  66. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +99 -22
  67. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +27 -4
  68. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +12 -0
  69. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
  70. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
  71. package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
  72. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +14 -12
  73. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1352 -0
  74. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +193 -76
  75. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +87 -25
  76. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +352 -22
  77. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +118 -10
  78. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +667 -74
  79. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
  80. package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
  81. package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
  82. package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
  83. package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
  84. package/analyzer-template/packages/aws/package.json +10 -10
  85. package/analyzer-template/packages/database/index.ts +1 -0
  86. package/analyzer-template/packages/database/package.json +4 -4
  87. package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +1 -1
  88. package/analyzer-template/packages/database/src/lib/analysisToDb.ts +1 -1
  89. package/analyzer-template/packages/database/src/lib/branchToDb.ts +1 -1
  90. package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +1 -1
  91. package/analyzer-template/packages/database/src/lib/commitToDb.ts +1 -1
  92. package/analyzer-template/packages/database/src/lib/fileToDb.ts +1 -1
  93. package/analyzer-template/packages/database/src/lib/kysely/db.ts +22 -1
  94. package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
  95. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +1 -1
  96. package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +62 -0
  97. package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
  98. package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
  99. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
  100. package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
  101. package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
  102. package/analyzer-template/packages/database/src/lib/loadCommits.ts +58 -19
  103. package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
  104. package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
  105. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +0 -5
  106. package/analyzer-template/packages/database/src/lib/projectToDb.ts +1 -1
  107. package/analyzer-template/packages/database/src/lib/saveFiles.ts +1 -1
  108. package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +1 -1
  109. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +153 -144
  110. package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatus.ts +58 -42
  111. package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.ts +81 -65
  112. package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +1 -1
  113. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +29 -1
  114. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +33 -5
  115. package/analyzer-template/packages/github/dist/database/index.d.ts +1 -0
  116. package/analyzer-template/packages/github/dist/database/index.d.ts.map +1 -1
  117. package/analyzer-template/packages/github/dist/database/index.js +1 -0
  118. package/analyzer-template/packages/github/dist/database/index.js.map +1 -1
  119. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +1 -1
  120. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -1
  121. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +1 -1
  122. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -1
  123. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +1 -1
  124. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -1
  125. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +1 -1
  126. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -1
  127. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +1 -1
  128. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -1
  129. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +1 -1
  130. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -1
  131. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +4 -0
  132. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  133. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +16 -1
  134. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  135. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  136. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +1 -0
  137. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
  138. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
  139. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  140. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +1 -1
  141. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +20 -0
  142. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -0
  143. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +45 -0
  144. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
  145. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
  146. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
  147. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  148. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  149. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +5 -0
  150. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  151. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +2 -0
  152. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
  153. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
  154. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
  155. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  156. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
  157. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  158. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
  159. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
  160. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
  161. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
  162. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
  163. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
  164. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  165. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +45 -14
  166. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  167. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
  168. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  169. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
  170. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  171. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
  172. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
  173. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -1
  174. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  175. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +1 -4
  176. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  177. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +1 -1
  178. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -1
  179. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +1 -1
  180. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -1
  181. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +1 -1
  182. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -1
  183. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +2 -2
  184. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  185. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +100 -88
  186. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  187. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.d.ts.map +1 -1
  188. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js +41 -30
  189. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js.map +1 -1
  190. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.d.ts.map +1 -1
  191. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +68 -57
  192. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -1
  193. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -1
  194. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +29 -1
  195. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -1
  196. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  197. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +33 -5
  198. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  199. package/analyzer-template/packages/github/dist/types/index.d.ts +1 -1
  200. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  201. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  202. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +25 -1
  203. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  204. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts +2 -0
  205. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts.map +1 -1
  206. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +8 -0
  207. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  208. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +10 -0
  209. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  210. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +56 -6
  211. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  212. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  213. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  214. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
  215. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  216. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
  217. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
  218. package/analyzer-template/packages/github/package.json +2 -2
  219. package/analyzer-template/packages/types/index.ts +1 -0
  220. package/analyzer-template/packages/types/src/types/Analysis.ts +25 -0
  221. package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
  222. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +8 -0
  223. package/analyzer-template/packages/types/src/types/Scenario.ts +10 -0
  224. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +70 -6
  225. package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
  226. package/analyzer-template/packages/utils/dist/types/index.d.ts +1 -1
  227. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  228. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  229. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +25 -1
  230. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  231. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts +2 -0
  232. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts.map +1 -1
  233. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +8 -0
  234. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  235. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +10 -0
  236. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  237. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +56 -6
  238. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  239. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  240. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  241. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  242. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +98 -3
  243. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  244. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
  245. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  246. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
  247. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
  248. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +121 -3
  249. package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
  250. package/analyzer-template/playwright/capture.ts +20 -8
  251. package/analyzer-template/playwright/captureFromUrl.ts +89 -82
  252. package/analyzer-template/playwright/captureStatic.ts +1 -1
  253. package/analyzer-template/project/analyzeBaselineCommit.ts +5 -0
  254. package/analyzer-template/project/analyzeRegularCommit.ts +5 -0
  255. package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
  256. package/analyzer-template/project/constructMockCode.ts +572 -87
  257. package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
  258. package/analyzer-template/project/loadReadyToBeCaptured.ts +65 -41
  259. package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
  260. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +18 -7
  261. package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
  262. package/analyzer-template/project/orchestrateCapture.ts +75 -7
  263. package/analyzer-template/project/reconcileMockDataKeys.ts +158 -10
  264. package/analyzer-template/project/runAnalysis.ts +4 -0
  265. package/analyzer-template/project/start.ts +38 -11
  266. package/analyzer-template/project/startScenarioCapture.ts +9 -0
  267. package/analyzer-template/project/writeClientLogRoute.ts +125 -0
  268. package/analyzer-template/project/writeMockDataTsx.ts +312 -10
  269. package/analyzer-template/project/writeScenarioComponents.ts +271 -37
  270. package/analyzer-template/project/writeSimpleRoot.ts +21 -11
  271. package/analyzer-template/scripts/comboWorkerLoop.cjs +98 -50
  272. package/analyzer-template/tsconfig.json +13 -1
  273. package/background/src/lib/local/createLocalAnalyzer.js +1 -1
  274. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  275. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +5 -0
  276. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
  277. package/background/src/lib/virtualized/project/analyzeRegularCommit.js +5 -0
  278. package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
  279. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
  280. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
  281. package/background/src/lib/virtualized/project/constructMockCode.js +474 -48
  282. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  283. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js +73 -1
  284. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js.map +1 -1
  285. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +19 -8
  286. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  287. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js +2 -2
  288. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js.map +1 -1
  289. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +7 -5
  290. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  291. package/background/src/lib/virtualized/project/orchestrateCapture.js +62 -7
  292. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  293. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +133 -10
  294. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  295. package/background/src/lib/virtualized/project/runAnalysis.js +3 -0
  296. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  297. package/background/src/lib/virtualized/project/start.js +34 -11
  298. package/background/src/lib/virtualized/project/start.js.map +1 -1
  299. package/background/src/lib/virtualized/project/startScenarioCapture.js +5 -0
  300. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  301. package/background/src/lib/virtualized/project/writeClientLogRoute.js +110 -0
  302. package/background/src/lib/virtualized/project/writeClientLogRoute.js.map +1 -0
  303. package/background/src/lib/virtualized/project/writeMockDataTsx.js +263 -6
  304. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  305. package/background/src/lib/virtualized/project/writeScenarioComponents.js +200 -35
  306. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  307. package/background/src/lib/virtualized/project/writeSimpleRoot.js +21 -11
  308. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  309. package/codeyam-cli/scripts/apply-setup.js +386 -9
  310. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  311. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js +196 -0
  312. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js.map +1 -0
  313. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js +114 -0
  314. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js.map +1 -0
  315. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js +149 -0
  316. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js.map +1 -0
  317. package/codeyam-cli/src/cli.js +35 -24
  318. package/codeyam-cli/src/cli.js.map +1 -1
  319. package/codeyam-cli/src/codeyam-cli.js +18 -2
  320. package/codeyam-cli/src/codeyam-cli.js.map +1 -1
  321. package/codeyam-cli/src/commands/analyze.js +21 -9
  322. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  323. package/codeyam-cli/src/commands/baseline.js +2 -0
  324. package/codeyam-cli/src/commands/baseline.js.map +1 -1
  325. package/codeyam-cli/src/commands/debug.js +9 -5
  326. package/codeyam-cli/src/commands/debug.js.map +1 -1
  327. package/codeyam-cli/src/commands/default.js +37 -21
  328. package/codeyam-cli/src/commands/default.js.map +1 -1
  329. package/codeyam-cli/src/commands/editor.js +1982 -0
  330. package/codeyam-cli/src/commands/editor.js.map +1 -0
  331. package/codeyam-cli/src/commands/init.js +81 -260
  332. package/codeyam-cli/src/commands/init.js.map +1 -1
  333. package/codeyam-cli/src/commands/memory.js +278 -0
  334. package/codeyam-cli/src/commands/memory.js.map +1 -0
  335. package/codeyam-cli/src/commands/recapture.js +2 -0
  336. package/codeyam-cli/src/commands/recapture.js.map +1 -1
  337. package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
  338. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
  339. package/codeyam-cli/src/commands/setup-simulations.js +284 -0
  340. package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
  341. package/codeyam-cli/src/commands/test-startup.js +2 -0
  342. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  343. package/codeyam-cli/src/commands/verify.js +14 -2
  344. package/codeyam-cli/src/commands/verify.js.map +1 -1
  345. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +246 -0
  346. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -0
  347. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +126 -0
  348. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -0
  349. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +295 -0
  350. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -0
  351. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js +270 -0
  352. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js.map +1 -0
  353. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js +100 -0
  354. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js.map +1 -0
  355. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +147 -0
  356. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
  357. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +76 -0
  358. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
  359. package/codeyam-cli/src/utils/__tests__/git.editor.test.js +134 -0
  360. package/codeyam-cli/src/utils/__tests__/git.editor.test.js.map +1 -0
  361. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +185 -0
  362. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  363. package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js +9 -0
  364. package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js.map +1 -1
  365. package/codeyam-cli/src/utils/__tests__/project.test.js +65 -0
  366. package/codeyam-cli/src/utils/__tests__/project.test.js.map +1 -0
  367. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js +121 -0
  368. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js.map +1 -0
  369. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +154 -82
  370. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  371. package/codeyam-cli/src/utils/analysisRunner.js +21 -2
  372. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  373. package/codeyam-cli/src/utils/analyzer.js +7 -0
  374. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  375. package/codeyam-cli/src/utils/backgroundServer.js +109 -22
  376. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  377. package/codeyam-cli/src/utils/buildFlags.js +4 -0
  378. package/codeyam-cli/src/utils/buildFlags.js.map +1 -0
  379. package/codeyam-cli/src/utils/devModeEvents.js +40 -0
  380. package/codeyam-cli/src/utils/devModeEvents.js.map +1 -0
  381. package/codeyam-cli/src/utils/editorAudit.js +82 -0
  382. package/codeyam-cli/src/utils/editorAudit.js.map +1 -0
  383. package/codeyam-cli/src/utils/editorDevServer.js +98 -0
  384. package/codeyam-cli/src/utils/editorDevServer.js.map +1 -0
  385. package/codeyam-cli/src/utils/editorJournal.js +137 -0
  386. package/codeyam-cli/src/utils/editorJournal.js.map +1 -0
  387. package/codeyam-cli/src/utils/editorMockState.js +248 -0
  388. package/codeyam-cli/src/utils/editorMockState.js.map +1 -0
  389. package/codeyam-cli/src/utils/editorPreloadHelpers.js +64 -0
  390. package/codeyam-cli/src/utils/editorPreloadHelpers.js.map +1 -0
  391. package/codeyam-cli/src/utils/editorPreview.js +66 -0
  392. package/codeyam-cli/src/utils/editorPreview.js.map +1 -0
  393. package/codeyam-cli/src/utils/editorScenarios.js +56 -0
  394. package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
  395. package/codeyam-cli/src/utils/fileMetadata.js +5 -0
  396. package/codeyam-cli/src/utils/fileMetadata.js.map +1 -1
  397. package/codeyam-cli/src/utils/fileWatcher.js +25 -9
  398. package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
  399. package/codeyam-cli/src/utils/generateReport.js +2 -2
  400. package/codeyam-cli/src/utils/git.js +103 -0
  401. package/codeyam-cli/src/utils/git.js.map +1 -1
  402. package/codeyam-cli/src/utils/install-skills.js +120 -39
  403. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  404. package/codeyam-cli/src/utils/interactiveSyncWatcher.js +126 -0
  405. package/codeyam-cli/src/utils/interactiveSyncWatcher.js.map +1 -0
  406. package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
  407. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
  408. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  409. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  410. package/codeyam-cli/src/utils/pathIgnoring.js +19 -7
  411. package/codeyam-cli/src/utils/pathIgnoring.js.map +1 -1
  412. package/codeyam-cli/src/utils/progress.js +7 -0
  413. package/codeyam-cli/src/utils/progress.js.map +1 -1
  414. package/codeyam-cli/src/utils/project.js +15 -5
  415. package/codeyam-cli/src/utils/project.js.map +1 -1
  416. package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js +11 -11
  417. package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js.map +1 -1
  418. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +22 -0
  419. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  420. package/codeyam-cli/src/utils/queue/heartbeat.js +13 -5
  421. package/codeyam-cli/src/utils/queue/heartbeat.js.map +1 -1
  422. package/codeyam-cli/src/utils/queue/job.js +75 -1
  423. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  424. package/codeyam-cli/src/utils/queue/manager.js +7 -0
  425. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  426. package/codeyam-cli/src/utils/requireSimulations.js +10 -0
  427. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
  428. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
  429. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
  430. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +229 -0
  431. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
  432. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
  433. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
  434. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
  435. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
  436. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
  437. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
  438. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
  439. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
  440. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +74 -0
  441. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
  442. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +376 -0
  443. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
  444. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +113 -0
  445. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
  446. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
  447. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
  448. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
  449. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
  450. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +116 -0
  451. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
  452. package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
  453. package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
  454. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +44 -0
  455. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
  456. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
  457. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
  458. package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
  459. package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
  460. package/codeyam-cli/src/utils/rules/__tests__/parser.test.js +83 -0
  461. package/codeyam-cli/src/utils/rules/__tests__/parser.test.js.map +1 -0
  462. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +118 -0
  463. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
  464. package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js +72 -0
  465. package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js.map +1 -0
  466. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
  467. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
  468. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js +76 -0
  469. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
  470. package/codeyam-cli/src/utils/rules/index.js +7 -0
  471. package/codeyam-cli/src/utils/rules/index.js.map +1 -0
  472. package/codeyam-cli/src/utils/rules/parser.js +93 -0
  473. package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
  474. package/codeyam-cli/src/utils/rules/pathMatcher.js +49 -0
  475. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
  476. package/codeyam-cli/src/utils/rules/rulePlacement.js +65 -0
  477. package/codeyam-cli/src/utils/rules/rulePlacement.js.map +1 -0
  478. package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
  479. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
  480. package/codeyam-cli/src/utils/rules/sourceFiles.js +43 -0
  481. package/codeyam-cli/src/utils/rules/sourceFiles.js.map +1 -0
  482. package/codeyam-cli/src/utils/rules/staleness.js +137 -0
  483. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
  484. package/codeyam-cli/src/utils/scenarioMarkers.js +134 -0
  485. package/codeyam-cli/src/utils/scenarioMarkers.js.map +1 -0
  486. package/codeyam-cli/src/utils/serverState.js +64 -12
  487. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  488. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +61 -41
  489. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  490. package/codeyam-cli/src/utils/simulationGateMiddleware.js +159 -0
  491. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  492. package/codeyam-cli/src/utils/syncMocksMiddleware.js +5 -24
  493. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  494. package/codeyam-cli/src/utils/testRunner.js +158 -0
  495. package/codeyam-cli/src/utils/testRunner.js.map +1 -0
  496. package/codeyam-cli/src/utils/transcriptPruning.js +67 -0
  497. package/codeyam-cli/src/utils/transcriptPruning.js.map +1 -0
  498. package/codeyam-cli/src/utils/versionInfo.js +46 -0
  499. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  500. package/codeyam-cli/src/utils/webappDetection.js +14 -2
  501. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  502. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  503. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  504. package/codeyam-cli/src/webserver/app/lib/database.js +63 -33
  505. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  506. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  507. package/codeyam-cli/src/webserver/backgroundServer.js +166 -16
  508. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  509. package/codeyam-cli/src/webserver/bootstrap.js +51 -0
  510. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -1
  511. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-DmJveP3T.js +1 -0
  512. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-C76mRRiF.js +11 -0
  513. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-COi5OvsN.js → EntityTypeBadge-g3saevPb.js} +1 -1
  514. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-BwdQv49w.js → EntityTypeIcon-CobE682z.js} +1 -1
  515. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-Bu6c6aDe.js +1 -0
  516. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-D68KarMg.js → InteractivePreview-DYFW3lDD.js} +3 -3
  517. package/codeyam-cli/src/webserver/build/client/assets/{LibraryFunctionPreview-L75Wvqgw.js → LibraryFunctionPreview-DLeucoVX.js} +1 -1
  518. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-C53WM8qn.js → LoadingDots-BU_OAEMP.js} +1 -1
  519. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-CrNkmy4i.js → LogViewer-ceAyBX-H.js} +1 -1
  520. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-djPLI-WV.js +11 -0
  521. package/codeyam-cli/src/webserver/build/client/assets/{SafeScreenshot-CQifa1n-.js → SafeScreenshot-BED4B6sP.js} +1 -1
  522. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-CyaBFX7l.js → ScenarioViewer-B76aig_2.js} +3 -13
  523. package/codeyam-cli/src/webserver/build/client/assets/Spinner-Bb5uFQ5V.js +34 -0
  524. package/codeyam-cli/src/webserver/build/client/assets/Terminal-nZNBALox.js +41 -0
  525. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-D36O1rzU.js → TruncatedFilePath-C8OKAR5x.js} +1 -1
  526. package/codeyam-cli/src/webserver/build/client/assets/_index-C96V0n15.js +11 -0
  527. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-BpKzcsJz.js +27 -0
  528. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-CUXOrorO.js +1 -0
  529. package/codeyam-cli/src/webserver/build/client/assets/addon-web-links-Duc5hnl7.js +1 -0
  530. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-D9hemwl6.js +22 -0
  531. package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
  532. package/codeyam-cli/src/webserver/build/client/assets/api.dev-mode-events-l0sNRNKZ.js +1 -0
  533. package/codeyam-cli/src/webserver/build/client/assets/api.editor-audit-l0sNRNKZ.js +1 -0
  534. package/codeyam-cli/src/webserver/build/client/assets/api.editor-capture-scenario-l0sNRNKZ.js +1 -0
  535. package/codeyam-cli/src/webserver/build/client/assets/api.editor-client-errors-l0sNRNKZ.js +1 -0
  536. package/codeyam-cli/src/webserver/build/client/assets/api.editor-commit-l0sNRNKZ.js +1 -0
  537. package/codeyam-cli/src/webserver/build/client/assets/api.editor-dev-server-l0sNRNKZ.js +1 -0
  538. package/codeyam-cli/src/webserver/build/client/assets/api.editor-entity-status-l0sNRNKZ.js +1 -0
  539. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-l0sNRNKZ.js +1 -0
  540. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-entry-l0sNRNKZ.js +1 -0
  541. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-image._-l0sNRNKZ.js +1 -0
  542. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-l0sNRNKZ.js +1 -0
  543. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-screenshot-l0sNRNKZ.js +1 -0
  544. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-update-l0sNRNKZ.js +1 -0
  545. package/codeyam-cli/src/webserver/build/client/assets/api.editor-load-commit-l0sNRNKZ.js +1 -0
  546. package/codeyam-cli/src/webserver/build/client/assets/api.editor-refresh-l0sNRNKZ.js +1 -0
  547. package/codeyam-cli/src/webserver/build/client/assets/api.editor-register-scenario-l0sNRNKZ.js +1 -0
  548. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-data-l0sNRNKZ.js +1 -0
  549. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-image._-l0sNRNKZ.js +1 -0
  550. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenarios-l0sNRNKZ.js +1 -0
  551. package/codeyam-cli/src/webserver/build/client/assets/api.editor-switch-scenario-l0sNRNKZ.js +1 -0
  552. package/codeyam-cli/src/webserver/build/client/assets/api.editor-test-results-l0sNRNKZ.js +1 -0
  553. package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
  554. package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-l0sNRNKZ.js +1 -0
  555. package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
  556. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  557. package/codeyam-cli/src/webserver/build/client/assets/api.rule-path-l0sNRNKZ.js +1 -0
  558. package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
  559. package/codeyam-cli/src/webserver/build/client/assets/book-open-D_nMCFmP.js +6 -0
  560. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-DgTPh8H-.js → chevron-down-BH2h1Ea2.js} +1 -1
  561. package/codeyam-cli/src/webserver/build/client/assets/{chunk-EPOLDU6W-DdQKK6on.js → chunk-JZWAC4HX-C4pqxYJB.js} +12 -12
  562. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-Dmr2bb1R.js → circle-check-DyIKORY6.js} +1 -1
  563. package/codeyam-cli/src/webserver/build/client/assets/copy-NDbZjXao.js +11 -0
  564. package/codeyam-cli/src/webserver/build/client/assets/{createLucideIcon-Do4ZLUYa.js → createLucideIcon-CMT1jU2q.js} +1 -1
  565. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BiM6z3Do.js +1 -0
  566. package/codeyam-cli/src/webserver/build/client/assets/editor-B2KwhQph.js +8 -0
  567. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CbdFyxZh.js → entity._sha._-CrjR3zZW.js} +12 -12
  568. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-DjACbfdI.js +6 -0
  569. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-C28BiQzt.js +6 -0
  570. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-p9hhkjJM.js +6 -0
  571. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-BMbl7MeQ.js → entity._sha_.edit._scenarioId-BMvVHNXU.js} +2 -2
  572. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-5wRKRIH9.js → entry.client-DTvKq3TY.js} +1 -1
  573. package/codeyam-cli/src/webserver/build/client/assets/{fileTableUtils-DD3SDH7t.js → fileTableUtils-cPo8LiG3.js} +1 -1
  574. package/codeyam-cli/src/webserver/build/client/assets/files-DO4CZ16O.js +1 -0
  575. package/codeyam-cli/src/webserver/build/client/assets/{git-zXjT7J0G.js → git-CFCTYk9I.js} +8 -8
  576. package/codeyam-cli/src/webserver/build/client/assets/globals-B17TBSS6.css +1 -0
  577. package/codeyam-cli/src/webserver/build/client/assets/{index-DLbXwndH.js → index-10oVnAAH.js} +1 -1
  578. package/codeyam-cli/src/webserver/build/client/assets/{index-gPZ-lad1.js → index-BcvgDzbZ.js} +1 -1
  579. package/codeyam-cli/src/webserver/build/client/assets/labs-Zk7ryIM1.js +1 -0
  580. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BsPXJ81F.js → loader-circle-BAXYRVEO.js} +1 -1
  581. package/codeyam-cli/src/webserver/build/client/assets/manifest-af20abcd.js +1 -0
  582. package/codeyam-cli/src/webserver/build/client/assets/memory-Dg0mvYrI.js +96 -0
  583. package/codeyam-cli/src/webserver/build/client/assets/pause-DTAcYxBt.js +11 -0
  584. package/codeyam-cli/src/webserver/build/client/assets/root-DUKqhFlb.js +67 -0
  585. package/codeyam-cli/src/webserver/build/client/assets/{search-P2FKIUql.js → search-fKo7v0Zo.js} +1 -1
  586. package/codeyam-cli/src/webserver/build/client/assets/settings-DfuTtcJP.js +1 -0
  587. package/codeyam-cli/src/webserver/build/client/assets/{simulations-L18M6-kN.js → simulations-B3aOzpCZ.js} +1 -1
  588. package/codeyam-cli/src/webserver/build/client/assets/terminal-BG4heKCG.js +11 -0
  589. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-BDz7kbVA.js → triangle-alert-DtSmdtM4.js} +1 -1
  590. package/codeyam-cli/src/webserver/build/client/assets/{useCustomSizes-29dDmbH8.js → useCustomSizes-ByhSyh0W.js} +1 -1
  591. package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-C14nCb1q.js +2 -0
  592. package/codeyam-cli/src/webserver/build/client/assets/{useReportContext-CkIOKTrZ.js → useReportContext-O-jkvSPx.js} +1 -1
  593. package/codeyam-cli/src/webserver/build/client/assets/{useToast-KKw5kTn-.js → useToast-9FIWuYfK.js} +1 -1
  594. package/codeyam-cli/src/webserver/build/client/assets/xterm-BqvuqXEL.js +27 -0
  595. package/codeyam-cli/src/webserver/build/server/assets/index-D_kZbNJs.js +1 -0
  596. package/codeyam-cli/src/webserver/build/server/assets/server-build-CWy5OIH9.js +366 -0
  597. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  598. package/codeyam-cli/src/webserver/build-info.json +5 -5
  599. package/codeyam-cli/src/webserver/devServer.js +39 -5
  600. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  601. package/codeyam-cli/src/webserver/editorProxy.js +440 -0
  602. package/codeyam-cli/src/webserver/editorProxy.js.map +1 -0
  603. package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +175 -0
  604. package/codeyam-cli/src/webserver/scripts/journalCapture.ts +140 -0
  605. package/codeyam-cli/src/webserver/server.js +226 -1
  606. package/codeyam-cli/src/webserver/server.js.map +1 -1
  607. package/codeyam-cli/src/webserver/terminalServer.js +698 -0
  608. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -0
  609. package/codeyam-cli/templates/codeyam-editor-claude.md +68 -0
  610. package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
  611. package/codeyam-cli/templates/commands/codeyam-diagnose.md +481 -0
  612. package/codeyam-cli/templates/editor-step-hook.py +147 -0
  613. package/codeyam-cli/templates/hooks/staleness-check.sh +43 -0
  614. package/codeyam-cli/templates/isolation-route/next-app.tsx.template +80 -0
  615. package/codeyam-cli/templates/isolation-route/next-pages.tsx.template +79 -0
  616. package/codeyam-cli/templates/isolation-route/vite-react.tsx.template +78 -0
  617. package/codeyam-cli/templates/msw/browser-setup.ts.template +47 -0
  618. package/codeyam-cli/templates/msw/handler-router.ts.template +47 -0
  619. package/codeyam-cli/templates/msw/server-setup.ts.template +52 -0
  620. package/codeyam-cli/templates/nextjs-prisma-sqlite/PRISMA_SETUP.md +84 -0
  621. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/api/todos/route.ts +17 -0
  622. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/globals.css +26 -0
  623. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/layout.tsx +34 -0
  624. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +19 -0
  625. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/page.tsx +10 -0
  626. package/codeyam-cli/templates/nextjs-prisma-sqlite/eslint.config.mjs +11 -0
  627. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +43 -0
  628. package/codeyam-cli/templates/nextjs-prisma-sqlite/next.config.ts +14 -0
  629. package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +35 -0
  630. package/codeyam-cli/templates/nextjs-prisma-sqlite/postcss.config.mjs +7 -0
  631. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/schema.prisma +27 -0
  632. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +37 -0
  633. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma.config.ts +12 -0
  634. package/codeyam-cli/templates/nextjs-prisma-sqlite/tsconfig.json +34 -0
  635. package/codeyam-cli/templates/prompts/conversation-guidance.txt +44 -0
  636. package/codeyam-cli/templates/prompts/conversation-prompt.txt +28 -0
  637. package/codeyam-cli/templates/prompts/interruption-prompt.txt +31 -0
  638. package/codeyam-cli/templates/prompts/stale-rules-prompt.txt +24 -0
  639. package/codeyam-cli/templates/rule-notification-hook.py +83 -0
  640. package/codeyam-cli/templates/rule-reflection-hook.py +647 -0
  641. package/codeyam-cli/templates/rules-instructions.md +78 -0
  642. package/codeyam-cli/templates/{codeyam:debug.md → skills/codeyam-debug/SKILL.md} +48 -4
  643. package/codeyam-cli/templates/skills/codeyam-dev-mode/SKILL.md +237 -0
  644. package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +69 -0
  645. package/codeyam-cli/templates/skills/codeyam-memory/SKILL.md +611 -0
  646. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/deprecated-prompt.md +100 -0
  647. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.mjs +139 -0
  648. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.mjs +52 -0
  649. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/misleading-api-prompt.md +117 -0
  650. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/read-json-field.mjs +61 -0
  651. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/ripgrep-fallback.mjs +155 -0
  652. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/analyze-prompt.md +46 -0
  653. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.mjs +13 -0
  654. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter-session.mjs +95 -0
  655. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.mjs +160 -0
  656. package/codeyam-cli/templates/skills/codeyam-new-rule/SKILL.md +11 -0
  657. package/codeyam-cli/templates/{codeyam:setup.md → skills/codeyam-setup/SKILL.md} +13 -1
  658. package/codeyam-cli/templates/{codeyam:sim.md → skills/codeyam-sim/SKILL.md} +1 -1
  659. package/codeyam-cli/templates/{codeyam:test.md → skills/codeyam-test/SKILL.md} +1 -1
  660. package/codeyam-cli/templates/{codeyam:verify.md → skills/codeyam-verify/SKILL.md} +1 -1
  661. package/package.json +27 -22
  662. package/packages/ai/index.js +7 -3
  663. package/packages/ai/index.js.map +1 -1
  664. package/packages/ai/src/lib/analyzeScope.js +91 -30
  665. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  666. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  667. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  668. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +100 -12
  669. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  670. package/packages/ai/src/lib/astScopes/methodSemantics.js +109 -23
  671. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  672. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
  673. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
  674. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +1 -102
  675. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  676. package/packages/ai/src/lib/astScopes/processExpression.js +518 -28
  677. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  678. package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
  679. package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
  680. package/packages/ai/src/lib/completionCall.js +171 -37
  681. package/packages/ai/src/lib/completionCall.js.map +1 -1
  682. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1082 -174
  683. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  684. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +5 -1
  685. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  686. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +179 -0
  687. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -1
  688. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +7 -1
  689. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  690. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  691. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  692. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  693. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  694. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +52 -3
  695. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  696. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +106 -13
  697. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  698. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
  699. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
  700. package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js +54 -0
  701. package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js.map +1 -0
  702. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +122 -12
  703. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  704. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
  705. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  706. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  707. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  708. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +333 -86
  709. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  710. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  711. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  712. package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js +34 -0
  713. package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js.map +1 -0
  714. package/packages/ai/src/lib/dataStructureChunking.js +130 -0
  715. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  716. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  717. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  718. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  719. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  720. package/packages/ai/src/lib/generateEntityDataStructure.js +46 -2
  721. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  722. package/packages/ai/src/lib/generateEntityScenarioData.js +789 -8
  723. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  724. package/packages/ai/src/lib/generateEntityScenarios.js +26 -2
  725. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  726. package/packages/ai/src/lib/generateExecutionFlows.js +376 -4
  727. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  728. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1124 -59
  729. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -1
  730. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  731. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  732. package/packages/ai/src/lib/isolateScopes.js +39 -3
  733. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  734. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
  735. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
  736. package/packages/ai/src/lib/mergeStatements.js +70 -51
  737. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  738. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
  739. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
  740. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +10 -4
  741. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  742. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  743. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  744. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +30 -7
  745. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  746. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  747. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  748. package/packages/ai/src/lib/resolvePathToControllable.js +155 -41
  749. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -1
  750. package/packages/ai/src/lib/worker/SerializableDataStructure.js +7 -0
  751. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  752. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +94 -1
  753. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  754. package/packages/analyze/index.js +1 -0
  755. package/packages/analyze/index.js.map +1 -1
  756. package/packages/analyze/src/lib/FileAnalyzer.js +60 -36
  757. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  758. package/packages/analyze/src/lib/ProjectAnalyzer.js +109 -30
  759. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  760. package/packages/analyze/src/lib/analysisContext.js +30 -5
  761. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  762. package/packages/analyze/src/lib/asts/index.js +4 -2
  763. package/packages/analyze/src/lib/asts/index.js.map +1 -1
  764. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  765. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  766. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  767. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  768. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  769. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  770. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  771. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  772. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  773. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  774. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  775. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  776. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  777. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  778. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +72 -10
  779. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  780. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +24 -4
  781. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  782. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +9 -0
  783. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  784. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  785. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  786. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
  787. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  788. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  789. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  790. package/packages/analyze/src/lib/files/getImportedExports.js +11 -7
  791. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  792. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +907 -0
  793. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
  794. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +164 -68
  795. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -1
  796. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +75 -21
  797. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  798. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +250 -20
  799. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  800. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +57 -9
  801. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
  802. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +558 -55
  803. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  804. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  805. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  806. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  807. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  808. package/packages/analyze/src/lib/index.js +1 -0
  809. package/packages/analyze/src/lib/index.js.map +1 -1
  810. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  811. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  812. package/packages/database/index.js +1 -0
  813. package/packages/database/index.js.map +1 -1
  814. package/packages/database/src/lib/analysisBranchToDb.js +1 -1
  815. package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
  816. package/packages/database/src/lib/analysisToDb.js +1 -1
  817. package/packages/database/src/lib/analysisToDb.js.map +1 -1
  818. package/packages/database/src/lib/branchToDb.js +1 -1
  819. package/packages/database/src/lib/branchToDb.js.map +1 -1
  820. package/packages/database/src/lib/commitBranchToDb.js +1 -1
  821. package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
  822. package/packages/database/src/lib/commitToDb.js +1 -1
  823. package/packages/database/src/lib/commitToDb.js.map +1 -1
  824. package/packages/database/src/lib/fileToDb.js +1 -1
  825. package/packages/database/src/lib/fileToDb.js.map +1 -1
  826. package/packages/database/src/lib/kysely/db.js +16 -1
  827. package/packages/database/src/lib/kysely/db.js.map +1 -1
  828. package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
  829. package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  830. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +45 -0
  831. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
  832. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  833. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  834. package/packages/database/src/lib/loadAnalyses.js +45 -2
  835. package/packages/database/src/lib/loadAnalyses.js.map +1 -1
  836. package/packages/database/src/lib/loadAnalysis.js +8 -0
  837. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  838. package/packages/database/src/lib/loadBranch.js +11 -1
  839. package/packages/database/src/lib/loadBranch.js.map +1 -1
  840. package/packages/database/src/lib/loadCommit.js +7 -0
  841. package/packages/database/src/lib/loadCommit.js.map +1 -1
  842. package/packages/database/src/lib/loadCommits.js +45 -14
  843. package/packages/database/src/lib/loadCommits.js.map +1 -1
  844. package/packages/database/src/lib/loadEntities.js +23 -4
  845. package/packages/database/src/lib/loadEntities.js.map +1 -1
  846. package/packages/database/src/lib/loadEntityBranches.js +9 -0
  847. package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
  848. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +1 -4
  849. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  850. package/packages/database/src/lib/projectToDb.js +1 -1
  851. package/packages/database/src/lib/projectToDb.js.map +1 -1
  852. package/packages/database/src/lib/saveFiles.js +1 -1
  853. package/packages/database/src/lib/saveFiles.js.map +1 -1
  854. package/packages/database/src/lib/scenarioToDb.js +1 -1
  855. package/packages/database/src/lib/scenarioToDb.js.map +1 -1
  856. package/packages/database/src/lib/updateCommitMetadata.js +100 -88
  857. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  858. package/packages/database/src/lib/updateFreshAnalysisStatus.js +41 -30
  859. package/packages/database/src/lib/updateFreshAnalysisStatus.js.map +1 -1
  860. package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +68 -57
  861. package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -1
  862. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +29 -1
  863. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -1
  864. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +33 -5
  865. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  866. package/packages/types/index.js.map +1 -1
  867. package/packages/utils/src/lib/fs/rsyncCopy.js +98 -3
  868. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  869. package/packages/utils/src/lib/safeFileName.js +29 -3
  870. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  871. package/scripts/npm-post-install.cjs +34 -0
  872. package/codeyam-cli/src/commands/detect-universal-mocks.js +0 -118
  873. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +0 -1
  874. package/codeyam-cli/src/commands/list.js +0 -31
  875. package/codeyam-cli/src/commands/list.js.map +0 -1
  876. package/codeyam-cli/src/commands/webapp-info.js +0 -146
  877. package/codeyam-cli/src/commands/webapp-info.js.map +0 -1
  878. package/codeyam-cli/src/utils/universal-mocks.js +0 -152
  879. package/codeyam-cli/src/utils/universal-mocks.js.map +0 -1
  880. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-vauWK972.js +0 -1
  881. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-CEleMv_j.js +0 -34
  882. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-DzJRkCkr.js +0 -11
  883. package/codeyam-cli/src/webserver/build/client/assets/_index-Be83mo_j.js +0 -11
  884. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-BN6wu6Y-.js +0 -37
  885. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-Bn6aCAy_.js +0 -1
  886. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-B4iCfs5M.js +0 -6
  887. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-wDWZZO1W.js +0 -6
  888. package/codeyam-cli/src/webserver/build/client/assets/files-DKyMFI90.js +0 -1
  889. package/codeyam-cli/src/webserver/build/client/assets/globals-DTTQ3gY7.css +0 -1
  890. package/codeyam-cli/src/webserver/build/client/assets/manifest-22590fcf.js +0 -1
  891. package/codeyam-cli/src/webserver/build/client/assets/root-BsAarjAM.js +0 -57
  892. package/codeyam-cli/src/webserver/build/client/assets/settings-B2eDuBj8.js +0 -1
  893. package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-BUm0UVJm.js +0 -2
  894. package/codeyam-cli/src/webserver/build/server/assets/index-BND5I5fv.js +0 -1
  895. package/codeyam-cli/src/webserver/build/server/assets/server-build-CFXnd7MG.js +0 -228
  896. package/codeyam-cli/templates/codeyam-stop-hook.sh +0 -284
  897. package/codeyam-cli/templates/codeyam:diagnose.md +0 -625
  898. package/scripts/finalize-analyzer.cjs +0 -81
@@ -0,0 +1,366 @@
1
+ var Tl=Object.defineProperty;var Ba=e=>{throw TypeError(e)};var $l=(e,t,r)=>t in e?Tl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Gn=(e,t,r)=>$l(e,typeof t!="symbol"?t+"":t,r),Rl=(e,t,r)=>t.has(e)||Ba("Cannot "+r);var Ya=(e,t,r)=>(Rl(e,t,"read from private field"),r?r.call(e):t.get(e)),Ua=(e,t,r)=>t.has(e)?Ba("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as l,Fragment as ue}from"react/jsx-runtime";import{PassThrough as Il}from"node:stream";import{createReadableStreamFromReadable as Dl}from"@react-router/node";import{ServerRouter as Ll,useFetcher as Oe,useLocation as Pr,useNavigate as Ct,Link as de,UNSAFE_withComponentProps as He,Meta as Ol,Links as Fl,ScrollRestoration as zl,Scripts as Bl,useLoaderData as qe,useRevalidator as mt,Outlet as Yl,data as G,useSearchParams as fn,useRouteLoaderData as Ul,useParams as Ho,useActionData as Wl,redirect as Wa}from"react-router";import{isbot as Hl}from"isbot";import{renderToPipeableStream as Jl}from"react-dom/server";import{useState as _,useEffect as ee,useCallback as ie,createContext as Vs,useContext as _r,useRef as ve,useMemo as re,forwardRef as Vl,useImperativeHandle as ql}from"react";import{Settings as Ha,CheckCircle2 as qs,Bug as Jo,AlertTriangle as hr,Check as pt,Copy as wt,Loader2 as dt,PencilRuler as Gl,HomeIcon as Kl,GitCommitIcon as Ja,File as Ql,RefreshCw as Zl,BookOpen as mr,FlaskConical as Xl,SettingsIcon as ec,PanelsTopLeftIcon as tc,ComponentIcon as nc,FileText as Va,Code as qa,Box as rc,List as sc,BarChart3 as ac,Tag as oc,Image as Rn,Code2 as Vo,Activity as os,ChevronDown as ot,CircleEqual as ic,ArrowLeft as lc,Terminal as pr,Search as On,ChevronLeft as cc,ChevronRight as Ot,Save as dc,MessageSquare as uc,Pause as qo,ListTodo as hc,PauseCircle as mc,FileCode as fr,GripVertical as pc,Ban as fc,CheckCircle as gc,FolderOpen as yc,CodeXml as xc,Zap as bc,Pencil as vc,Trash2 as wc,X as Fn,Folder as Go,Info as Ms,Plus as Gs,Eye as Nc,FolderTree as Cc,ChevronsUpDown as Ko,ChevronsDownUp as Qo}from"lucide-react";import"fetch-retry";import Sc from"better-sqlite3";import{Pool as kc}from"pg";import*as K from"fs";import Se,{existsSync as $t,readdirSync as Ec,rmSync as is}from"fs";import*as O from"path";import Z,{join as Ga}from"path";import{OperationNodeTransformer as Ac,Kysely as Zo,ParseJSONResultsPlugin as Pc,SqliteDialect as _c,PostgresDialect as Mc,sql as at}from"kysely";import*as jc from"kysely/helpers/sqlite";import*as Tc from"kysely/helpers/postgres";import Be from"typescript";import*as Ne from"fs/promises";import be,{writeFile as _n,readFile as js,mkdir as $c}from"fs/promises";import*as Ks from"os";import Ts from"os";import Rc from"prompts";import gr from"chalk";import*as Ic from"crypto";import zn,{randomUUID as Qs,createHmac as Dc}from"crypto";import{execSync as _e,spawn as St,exec as Zs}from"child_process";import{fileURLToPath as Mr}from"url";import{promisify as Xs}from"util";import Lc from"dotenv";import Oc,{EventEmitter as jr}from"events";import{v4 as Fc}from"uuid";import ea from"http";import zc from"net";import{WebSocket as Xo}from"ws";import"node-pty";import Bc from"openai";import Yc from"p-queue";import Ka from"p-retry";import{DynamoDBClient as Tr,PutItemCommand as Uc}from"@aws-sdk/client-dynamodb";import{LRUCache as ta}from"lru-cache";import"pluralize";import"piscina";import Wc from"json5";import{marshall as Hc}from"@aws-sdk/util-dynamodb";import Jc from"v8";import{Prism as Vc}from"react-syntax-highlighter";import{vscDarkPlus as qc}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Gc}from"node:crypto";import{minimatch as $s}from"minimatch";import Kc from"react-markdown";import Qc from"remark-gfm";import Zc from"react-diff-viewer-continued";const ei=5e3;function Xc(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let c=!1,d=e.headers.get("user-agent"),h=d&&Hl(d)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),ei+1e3);const{pipe:m,abort:p}=Jl(n(Ll,{context:s,url:e.url}),{[h](){c=!0;const f=new Il({final(g){clearTimeout(u),u=void 0,g()}}),y=Dl(f);r.set("Content-Type","text/html"),m(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,c&&console.error(f)}})})}const ed=Object.freeze(Object.defineProperty({__proto__:null,default:Xc,streamTimeout:ei},Symbol.toStringTag,{value:"Module"}));function td({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=_(!1);ee(()=>{i(!0)},[]);const c=ie(()=>{r==null||r(e)},[r,e]);return l("button",{className:`
2
+ w-full px-1.5 py-2 cursor-pointer focus:outline-none
3
+ flex flex-col items-center justify-center gap-1 transition-colors
4
+ ${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
5
+ `,onClick:c,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:a})]})}const $r="/assets/cy-logo-cli-CCKUIm0S.svg";function nd(e){return e.scenarioName&&e.entityName?`${e.entityName} → "${e.scenarioName}"`:e.entityName?e.entityName:e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function rd({content:e,className:t=""}){const[r,s]=_(!1),a=ie(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:a,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?l(ue,{children:[n(pt,{size:14}),"Copied"]}):l(ue,{children:[n(wt,{size:14}),"Copy"]})})}function ti({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=_(""),[c,d]=_(s),[h,u]=_(!1),[m,p]=_(!1),[f,y]=_(null),[g,x]=_(null),v=Oe(),b=v.state!=="idle",N=!!(r.scenarioId||r.analysisId),w=r.analysisId||r.scenarioId||"",E=()=>{const P=`/codeyam-diagnose ${w}`;return o.trim()?`${P} ${o.trim()}`:P};if(v.data&&!m&&!g){const P=v.data;P.success&&P.reportId?(p(!0),y(P.reportId)):P.error&&x(P.error)}const C=async()=>{x(null);const P=new FormData;if(P.append("issueType","other"),P.append("description",o),P.append("email",c),P.append("source",r.source),P.append("entitySha",r.entitySha||""),P.append("scenarioId",r.scenarioId||""),P.append("analysisId",r.analysisId||""),P.append("currentUrl",r.currentUrl),P.append("entityName",r.entityName||""),P.append("entityType",r.entityType||""),P.append("scenarioName",r.scenarioName||""),P.append("errorMessage",r.errorMessage||""),a)try{const j=await(await fetch(a)).blob();P.append("screenshot",j,"screenshot.jpg")}catch(I){console.error("Failed to convert screenshot:",I)}v.submit(P,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},S=()=>{i(""),u(!1),p(!1),y(null),x(null),t()},k=P=>{P.key==="Escape"&&S()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:k,children:l("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[l("div",{className:"flex items-center justify-between mb-6",children:[l("div",{className:"flex items-center gap-3",children:[b?n("div",{className:"animate-spin",children:n(Ha,{size:24,style:{strokeWidth:1.5}})}):m?n(qs,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Jo,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:m?"Report Submitted":"Report Issue"})]}),n("button",{onClick:S,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),m?l("div",{children:[l("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),l("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:S,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):l("div",{children:[l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[l("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:nd(r)}),n("button",{type:"button",onClick:()=>u(!h),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:h?"Hide":"Details"})]}),h&&l("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[l("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),l("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&l("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:a,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:P=>i(P.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),N&&l(ue,{children:[l("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),l("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:E()}),n(rd,{content:E(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),l("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),l("div",{className:N?"opacity-75":"",children:[N&&l("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:c,onChange:P=>d(P.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),l("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(hr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),l("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),b&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:v.formData?"Uploading report...":"Creating archive..."})}),g&&l("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(hr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),l("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),l("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:S,disabled:b,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void C(),disabled:b,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:b?l(ue,{children:[n("div",{className:"animate-spin",children:n(Ha,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Qa={source:"navbar"},na=Vs(void 0);function sd({children:e}){const[t,r]=_(Qa),s=ie(o=>{r(o)},[]),a=ie(()=>{r(Qa)},[]);return n(na.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function ft(e){const t=_r(na),r=ve(t);ee(()=>{if(r.current)return r.current.setContextData(e),()=>{var s;(s=r.current)==null||s.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function ad(){const e=_r(na),t=Pr();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:t.pathname}}function od({labs:e,isAdmin:t,editorMode:r}){var C;const s=Pr(),a=Ct(),[o,i]=_(),[c,d]=_(!1),[h,u]=_(!1),[m,p]=_(null),f=Oe();ee(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const y=((C=f.data)==null?void 0:C.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,v=[{id:"editor",icon:n(Gl,{style:g}),link:"/editor",name:"Editor",hidden:!r},{id:"dashboard",icon:n(Kl,{style:g}),link:"/",name:"Dashboard",hidden:!x},{id:"simulations",icon:l("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:g,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!x},{id:"git",icon:n(Ja,{style:g}),link:"/git",name:"Git",hidden:!x},{id:"files",icon:n(Ql,{style:g}),link:"/files",name:"Files",hidden:!x},{id:"activity",icon:n(Zl,{style:g}),link:"/activity",name:"Activity",hidden:!x},{id:"memory",icon:n(mr,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Xl,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(ec,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Ja,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(tc,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(nc,{style:g}),link:"/components",name:"Components",hidden:!0}],b=ie(S=>{const k=v.find(P=>P.id===S);k!=null&&k.link&&a(k.link),i(P=>P===S?void 0:S)},[v,a]);ee(()=>{const S={editor:["editor"],dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[k,P]of Object.entries(S))if(P.some(I=>I==="/"?s.pathname==="/":s.pathname.includes(I))){i(k);return}i(void 0)},[s]);const N=async()=>{u(!0);try{const{default:S}=await import("html2canvas-pro"),P=(await S(document.body)).toDataURL("image/jpeg",.8);p(P),d(!0)}catch(S){console.error("Screenshot capture failed:",S),d(!0)}finally{u(!1)}},w=()=>{d(!1),p(null)},E=ad();return l(ue,{children:[l("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[l("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(de,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:$r,alt:"CodeYam",className:"h-6"})})}),v.filter(S=>!S.hidden).map(S=>n(td,{id:S.id,selected:S.id===o,onClick:b,icon:S.icon,name:S.name},`sidebar-button-${S.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:l("button",{onClick:()=>void N(),disabled:h,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:h?n(dt,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Jo,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:h?"Capturing...":`Report
6
+ Bug`})]})})]}),c&&n(ti,{isOpen:!0,onClose:w,context:E,defaultEmail:y,screenshotDataUrl:m??void 0})]})}const ni=Vs(void 0);function id({children:e}){const[t,r]=_([]),s=ie((o,i="info",c=5e3)=>{const h={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:c};r(u=>[...u,h])},[]),a=ie(o=>{r(i=>i.filter(c=>c.id!==o))},[]);return n(ni.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function ra(){const e=_r(ni);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function ld({toast:e,onClose:t}){ee(()=>{const a=e.duration||5e3;if(a>0){const o=setTimeout(()=>{t(e.id)},a);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return l("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function cd({toasts:e,onClose:t}){return e.length===0?null:l("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
7
+ @keyframes slideIn {
8
+ from {
9
+ transform: translateX(400px);
10
+ opacity: 0;
11
+ }
12
+ to {
13
+ transform: translateX(0);
14
+ opacity: 1;
15
+ }
16
+ }
17
+ `}),e.map(r=>n(ld,{toast:r,onClose:t},r.id))]})}function kt(e,t){const[r,s]=_(""),[a,o]=_(!1),[i,c]=_(null),[d,h]=_(!1);ee(()=>{t&&(h(!1),o(!1),c(null))},[t]),ee(()=>{if(!e||!t){t||s("");return}const m=async()=>{if(!d)try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const g=(await f.text()).trim().split(`
18
+ `).filter(b=>b.length>0);if(g.length<3){o(!1),h(!1),c(null),s("");return}const x=g.filter(b=>b.includes("CodeYam Log Level 1"));if(x.length>0){const b=x[x.length-1];s(b.replace(/.*CodeYam Log Level 1: /,""))}const v=g.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(v){const b=v.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();c(b),h(!0)}g.some(b=>b.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};m().catch(()=>{});const p=setInterval(()=>{m().catch(()=>{})},500);return()=>clearInterval(p)},[e,t,d]);const u=ie(()=>{s(""),o(!1),c(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:a,resetLogs:u}}function It({projectSlug:e,onClose:t}){const[r,s]=_("Loading logs..."),[a,o]=_(!0),[i,c]=_(!0),[d,h]=_("all"),u=ve(null);return ee(()=>{const m=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")s(f);else{const y=f.trim().split(`
19
+ `).filter(g=>{if(g.length===0)return!1;const x=g.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=d});s(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
20
+ `))}i&&u.current&&setTimeout(()=>{var y;(y=u.current)==null||y.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else s(`Error: ${p.status} - ${await p.text()}`)}catch(p){s(`Error fetching logs: ${p.message}`)}};if(m().catch(()=>{}),a){const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,a,i,d]),ee(()=>{const m=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:l("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:m=>m.stopPropagation(),children:[l("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[l("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),l("div",{className:"flex items-center gap-4",children:[l("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),l("select",{value:d,onChange:m=>h(m.target.value==="all"?"all":Number(m.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:a,onChange:m=>o(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:m=>c(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function et({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},s=r[e]||r.other,a=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(Vo,{size:a,color:s.iconColor});case"visual":return n(Rn,{size:a,color:s.iconColor});case"type":return n(oc,{size:a,color:s.iconColor});case"data":return n(ac,{size:a,color:s.iconColor});case"index":return n(sc,{size:a,color:s.iconColor});case"functionCall":return n(qa,{size:a,color:s.iconColor});case"class":return n(rc,{size:a,color:s.iconColor});case"method":return n(qa,{size:a,color:s.iconColor});case"other":return n(Va,{size:a,color:s.iconColor});default:return n(Va,{size:a,color:s.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${s.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function ri({filePath:e,maxLength:t=60,className:r,style:s}){const o=((c,d)=>{if(c.length<=d)return c;const h="...",u=d-h.length,m=Math.ceil(u*.4),p=Math.floor(u*.6),f=c.slice(0,m),y=c.slice(-p),g=f.lastIndexOf("/"),x=y.indexOf("/"),v=g>m*.5?f.slice(0,g+1):f,b=x!==-1&&x<p*.5?y.slice(x):y;return`${v}${h}${b}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function ls({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:a=!1,scenarioCount:o=0,additionalContent:i}){return l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"flex items-center gap-1",children:[n(et,{type:e.entityType||"other"}),l(de,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,a&&o>0&&` (${o})`]}),n(ri,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const cs={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function dd({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:c=[]}){var q,Y,U;const[d,h]=_(!1),[u,m]=_(!1),[p,f]=_(null),[y,g]=_(new Set),[x,v]=_(new Set),[b,N]=_(!1),w=!!i||o.length>0,E=!!i,C=(i==null?void 0:i.entities)||r,S=!!(e!=null&&e.analysisCompletedAt),k=(e==null?void 0:e.readyToBeCaptured)??0,P=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||S&&(k===0||P>=k);const I=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,j=w,{lastLine:A}=kt(t,j),T=E||o.length>0,R=new Set(((q=i==null?void 0:i.entities)==null?void 0:q.map(H=>H.sha))||[]),$=c.filter(H=>!(H.currentEntityShas||[]).some(M=>R.has(M))),J=(()=>{const D=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&I){const M=e.analysisCompletedAt||e.createdAt;if(new Date(M).getTime()>D)return!0}if($.length>0){const M=$[0],Q=M.analysisCompletedAt||M.archivedAt||M.createdAt;if(Q&&new Date(Q).getTime()>D)return!0}return!1})();return ee(()=>{const H=(i==null?void 0:i.id)||null;w&&!u&&H!==p&&m(!0),!w&&p!==null&&f(null)},[w,i==null?void 0:i.id,u,p]),l(ue,{children:[l("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&l("div",{onClick:()=>{m(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[T?n(dt,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(os,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:T?"Analyzing...":"Activity: No Activity Yet"}),T&&n("button",{onClick:H=>{H.stopPropagation(),h(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&l("div",{children:[l("div",{className:"flex items-center justify-between px-3 py-2",children:[l("div",{className:"flex items-center gap-2",children:[T?n(dt,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(os,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:T?"Analyzing...":"Activity"})]}),l("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>h(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{m(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(ot,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),l("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[T&&i&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(os,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:C.length>0?l("div",{className:"space-y-1.5",children:[(b?C:C.slice(0,3)).map(H=>n(ls,{entity:H,nameSize:"11px",pathSize:"10px",pathMaxLength:150},H.sha)),C.length>3&&n("button",{onClick:()=>N(H=>!H),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:cs,"aria-label":b?"Show fewer entities":`Show ${C.length-3} more entities`,children:b?"Show less":`+${C.length-3} more`}),A&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:A})]}):l("div",{children:[i.entityNames&&i.entityNames.length>0?l("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((H,D)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:H},D)),i.entityNames.length>5&&l("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):l("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((Y=i.entityShas)==null?void 0:Y.length)||0," ",((U=i.entityShas)==null?void 0:U.length)===1?"entity":"entities","..."]}),A&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:A})]})})]}),o.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ic,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map(H=>{var Q,W;const D=y.has(H.id),M=D?H.entities:H.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:H.entities.length>0?l("div",{className:"space-y-1.5",children:[M.map(F=>n(ls,{entity:F,nameSize:"10px",pathSize:"9px",pathMaxLength:120},F.sha)),H.entities.length>3&&n("button",{onClick:()=>{g(F=>{const te=new Set(F);return te.has(H.id)?te.delete(H.id):te.add(H.id),te})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:cs,"aria-label":D?"Show fewer entities":`Show ${H.entities.length-3} more entities`,children:D?"Show less":`+${H.entities.length-3} more`})]}):l("div",{style:{fontSize:"10px",color:"#343434"},children:[H.type==="analysis"&&n(ue,{children:H.entityNames&&H.entityNames.length>0?l("div",{className:"space-y-0.5",children:[H.entityNames.slice(0,5).map((F,te)=>n("div",{children:F},te)),H.entityNames.length>5&&l("div",{className:"italic",children:["+",H.entityNames.length-5," more"]})]}):`Analyzing ${((Q=H.entityShas)==null?void 0:Q.length)||0} ${((W=H.entityShas)==null?void 0:W.length)===1?"entity":"entities"}`}),H.type==="recapture"&&"Recapturing scenario",H.type==="debug-setup"&&"Setting up debug environment"]})},H.id)})})]}),J&&$.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(qs,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:$.slice(0,3).map((H,D)=>{const M=H.entities||[],Q=H.analysisCompletedAt||H.archivedAt||H.createdAt||"",W=(()=>{if(!Q)return"";const L=Date.now()-new Date(Q).getTime(),V=Math.floor(L/6e4),B=Math.floor(L/36e5);return B>0?`${B}h ago`:V>0?`${V}m ago`:"just now"})(),F=x.has(D),z=(F?M:M.slice(0,3)).map(L=>{var V,B,X;return{...L,scenarioCount:((X=(B=(V=L.analyses)==null?void 0:V[0])==null?void 0:B.scenarios)==null?void 0:X.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:M.length>0&&l("div",{className:"space-y-1.5",children:[z.map((L,V)=>l("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(ls,{entity:L,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:L.scenarioCount})}),V===0&&W&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:W})]},L.sha)),M.length>3&&n("button",{onClick:()=>{v(L=>{const V=new Set(L);return V.has(D)?V.delete(D):V.add(D),V})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:cs,"aria-label":F?"Show fewer entities":`Show ${M.length-3} more entities`,children:F?"Show less":`+${M.length-3} more`})]})},D)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(de,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(It,{projectSlug:t,onClose:()=>h(!1)})]})}function tt(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Bn(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:c,commit:d,created_at:h,updated_at:u,...m}=e,p=(i??[]).map(g=>g.branch_id),f=c?c.map(Et):void 0,y=d?Xt(d):void 0;return tt({...m,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:y,analyses:f,branchIds:p,createdAt:h,updatedAt:u})}function sa(e){return tt({id:e.id,projectId:e.project_id,name:e.name,path:e.path,deleted:!!e.deleted,metadata:e.metadata??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0})}function aa(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:c,configuration:d,team_id:h,...u}=e;return tt({...u,branches:t?t.map(hn):void 0,files:r?r.map(sa):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function ud(e){const{id:t,project_id:r,user_id:s,scenario_id:a,thumbs_up:o,user:i}=e,c=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return tt({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:c})}function hd(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:c,user:d}=e,h=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return tt({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:c,user:h})}function si(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:c,...d}=e,h=a?Et(a):void 0,u=o?o.map(ud):void 0,m=i?i.map(hd):void 0;return tt({...d,projectId:t,analysisId:r,previousVersionId:s,analysis:h,userScenarios:u,comments:m})}function md(e){return tt({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?Et(e.analysis):void 0,entity:e.entity?Bn(e.entity):void 0,branch:e.branch?hn(e.branch):void 0,createdAt:e.created_at})}function Et(e){const{project_id:t,commit_id:r,file_id:s,file_path:a,entity_sha:o,entity_type:i,entity_name:c,previous_analysis_id:d,file:h,entity:u,commit:m,project:p,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:v,committed_at:b,completed_at:N,created_at:w,updated_at:E,indirect:C,...S}=e,k=u?Bn(u):void 0,P=h?sa(h):void 0,I=p?aa(p):void 0,j=m?Xt(m):void 0,A=f?f.map(si):void 0,T=y?y.map(md):void 0,R=T?T.map($=>$.branch):void 0;return tt({...S,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:c,previousAnalysisId:d,entity:k,file:P,commit:j,project:I,scenarios:A,analysisBranches:T,branches:R,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:v,committedAt:b,completedAt:N,createdAt:w,updatedAt:E,indirect:!!C})}function oa(e){return tt({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Xt(e.commit):void 0,branch:e.branch?hn(e.branch):void 0})}function pd(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return tt({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function Xt(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:c,html_url:d,author:h,analyses:u,entities:m,commit_branches:p,committed_at:f,analyzed_at:y,...g}=e,x=s?hn(s):void 0,v=i?hn(i):void 0,b=(a==null?void 0:a.length)>0?pd(a[a.length-1]):void 0,N=(u??[]).map(Et),w=(m??[]).map(Bn),E=(p==null?void 0:p.length)>0?p.map(oa):void 0;return h&&(h.username=h.preferredUsername??h.username),tt({...g,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:o,mergedBranch:v,aiMessage:c,htmlUrl:d,author:h,analyses:N,entities:w,commitBranches:E,committedAt:f,analyzedAt:y})}function hn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:c,primary:d,...h}=e,u=s?s.map(Xt):void 0,m=a?a.flatMap(p=>Et(p.analysis)):void 0;return tt({...h,projectId:t,contentChangedAt:r,commits:u,analyses:m,activeAt:o,createdAt:i,updatedAt:c,primary:!!d})}var Er;class fd{constructor(){Ua(this,Er,new gd)}transformQuery(t){return Ya(this,Er).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Er=new WeakMap;class gd extends Ac{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const oe=()=>null,yd={analyzed_at:oe(),configuration:oe(),content_changed_at:oe(),created_at:oe(),description:oe(),github_token:oe(),id:oe(),metadata:oe(),name:oe(),path:oe(),slug:oe(),team_id:oe(),updated_at:oe()},xd=Object.keys(yd),bd={active:oe(),analysis_id:oe(),branch_id:oe(),created_at:oe(),entity_sha:oe(),id:oe()},vd=Object.keys(bd),wd={active_at:oe(),content_changed_at:oe(),created_at:oe(),id:oe(),metadata:oe(),name:oe(),primary:oe(),project_id:oe(),ref:oe(),sha:oe(),updated_at:oe()},ai=Object.keys(wd),Nd={ai_message:oe(),analyzed_at:oe(),author_github_username:oe(),branch_id:oe(),committed_at:oe(),created_at:oe(),files:oe(),html_url:oe(),id:oe(),merged_branch_id:oe(),message:oe(),metadata:oe(),project_id:oe(),sha:oe(),title:oe(),url:oe()},oi=Object.keys(Nd),Cd=oi.filter(e=>e!=="files"),Sd={commit_id:oe(),created_at:oe(),description:oe(),documentation:oe(),entity_type:oe(),file_id:oe(),file_path:oe(),metadata:oe(),name:oe(),project_id:oe(),quality:oe(),sha:oe(),updated_at:oe()},ii=Object.keys(Sd),kd={active:oe(),branch_id:oe(),entity_sha:oe()},Ed=Object.keys(kd),Ad={created_at:oe(),deleted:oe(),id:oe(),metadata:oe(),name:oe(),path:oe(),project_id:oe(),updated_at:oe()},Pd=Object.keys(Ad),_d={analysis_id:oe(),approved:oe(),created_at:oe(),description:oe(),id:oe(),metadata:oe(),name:oe(),previous_version_id:oe(),project_id:oe()},yr=Object.keys(_d),Md=!!en("ENABLE_QUERY_LOGGING"),jd=!!en("ENABLE_QUERY_ERROR_LOGGING");en("USE_LOCAL_POSTGRESQL_FOR_TESTING");let Kn;function Te(){if(!Kn){const e=ci();if(e==="sqlite")Kn=Td();else if(e==="postgresql")Kn=$d();else throw new Error(`Unknown database type: ${e}`)}return Kn}function Td(e){if(e||(e=en("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=K.existsSync(e),r=O.dirname(e);if(!K.existsSync(r))K.mkdirSync(r,{recursive:!0,mode:493});else try{K.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new Sc(e,{readonly:!1,fileMustExist:!1});if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const a=s.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&a.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(a){console.error("CodeYam DB ERROR: Failed to verify database schema:",a)}return new Zo({dialect:new _c({database:s}),plugins:[new Pc,new fd],log:li})}function $d(){const e=Id();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new kc({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Zo({dialect:new Mc({pool:t}),log:li})}let ds=null;function nn(){return ds||(ds=Rd(ci())),ds}function li(e){e.level==="error"?jd&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Md&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Rd(e){if(e==="sqlite")return jc;if(e==="postgresql")return Tc;throw new Error(`Unknown database type: ${e}`)}function ci(){if(en("SQLITE_PATH"))return"sqlite";if(en("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Id(){const e=en("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function en(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var Ke=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(Ke||{});const Rr="Default Scenario";let Dd="<main>";function Ld(){return Dd}function Za(e,...t){Pe(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function Pe(...e){const t=Ld(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
21
+ ${a.stack}`:typeof a=="object"?Od(a):String(a)}).filter(Boolean).join(`
22
+ `),s=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(s+`
23
+ `);return}console.log(s.replace(/\n/g,"\r"))}function Od(e,t=2){function r(s,a=new WeakMap){return s===null||typeof s!="object"?s:a.has(s)?`"[Circular: ${s.constructor.name}]"`:(a.set(s,!0),Array.isArray(s)?`[${s.map(c=>{const d=r(c,a);return typeof c=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(s).map(([i,c])=>{let d;return typeof c>"u"?null:(typeof c=="function"?d=`"(function: ${c.name||"anonymous"})"`:c instanceof Date?d=`"${c.toISOString()}"`:typeof c=="object"&&c!==null?d=r(c,a):typeof c=="string"?d=`"${c.replace(/"/g,'\\"')}"`:d=JSON.stringify(c),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const a=r(e);if(!t)return a;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:s,serialized:a}),a}}}function xr(e,t){try{let r=function(o){var i,c;if(Be.isFunctionDeclaration(o)&&kn(o)){const d=((i=o.name)==null?void 0:i.text)||"default",h=o.getText(s),u=us(o);a.push({name:d,code:h,sha:Ht(t,d,h),entityType:"function",isDefault:u})}else if(Be.isClassDeclaration(o)&&kn(o)){const d=((c=o.name)==null?void 0:c.text)||"default",h=o.getText(s),u=us(o),m=h.includes("React.")||h.includes("jsx")||h.includes("tsx");a.push({name:d,code:h,sha:Ht(t,d,h),entityType:m?"component":"class",isDefault:u})}else if(Be.isInterfaceDeclaration(o)&&kn(o)){const d=o.name.text,h=o.getText(s);a.push({name:d,code:h,sha:Ht(t,d,h),entityType:"interface",isDefault:!1})}else if(Be.isTypeAliasDeclaration(o)&&kn(o)){const d=o.name.text,h=o.getText(s);a.push({name:d,code:h,sha:Ht(t,d,h),entityType:"type",isDefault:!1})}else if(Be.isVariableStatement(o)&&kn(o)){const d=us(o);o.declarationList.declarations.forEach(h=>{var u;if(Be.isIdentifier(h.name)){const m=h.name.text,p=o.getText(s),f=((u=h.initializer)==null?void 0:u.getText(s))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));a.push({name:m,code:p,sha:Ht(t,m,p),entityType:y?"component":"variable",isDefault:d})}})}else if(Be.isExportAssignment(o)){const d=o.getText(s);a.push({name:"default",code:d,sha:Ht(t,"default",d),entityType:"unknown",isDefault:!0})}else if(Be.isExportDeclaration(o)&&o.exportClause&&Be.isNamedExports(o.exportClause)){const d=o.getText(s);for(const h of o.exportClause.elements){const u=h.name.text;a.push({name:u,code:d,sha:Ht(t,u,d),entityType:"unknown",isDefault:!1})}}Be.forEachChild(o,r)};const s=Be.createSourceFile(t,e,Be.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function kn(e){if(!Be.canHaveModifiers(e))return!1;const t=Be.getModifiers(e);return t?t.some(r=>r.kind===Be.SyntaxKind.ExportKeyword):!1}function us(e){if(!Be.canHaveModifiers(e))return!1;const t=Be.getModifiers(e);return t?t.some(r=>r.kind===Be.SyntaxKind.DefaultKeyword):!1}function Ht(e,t,r){const s=zn.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function Fd(e){var h;const{webapp:t,port:r,environmentVariables:s,packageManager:a}=e,o=t==null?void 0:t.startCommand;if(!o)return`${a} ${a==="npm"?"run ":""}dev`;const i=((h=o.args)==null?void 0:h.map(u=>u.replace(/\$PORT/g,String(r))))??[],c=[];for(const u of s)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");c.push(`${u.key}='${m}'`)}if(o.env)for(const[u,m]of Object.entries(o.env)){const f=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");c.push(`${u}='${f}'`)}const d=c.length>0?c.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function zd(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=O.normalize(e),s=[...t].sort((a,o)=>{var i,c;return(((i=o.path)==null?void 0:i.length)??0)-(((c=a.path)==null?void 0:c.length)??0)});for(const a of s){const o=O.normalize(a.path??".");if(o==="."||r.startsWith(o+O.sep)||r===o)return a}return t[0]}function Bd(e){const{filePath:t,webapps:r,environmentVariables:s,port:a,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=zd(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const c=Fd({webapp:i,port:a,environmentVariables:s,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:c,url:`http://localhost:${a}/static/codeyam-sample`}}function Ir(e,t,r=[]){const s=Array.isArray(t)?t:[t];return a=>a.columns(s).doUpdateSet(o=>{const i=Object.keys(e).filter(c=>c!==t&&!r.includes(c));return Object.fromEntries(i.map(c=>[c,o.ref(`excluded.${c}`)]))})}function Yd(e){const{jsonObjectFrom:t}=nn();return t(e.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",e.ref("commits.author_github_username")))}async function Ud({ids:e,analysisId:t}){const r=Te();try{let s=r.deleteFrom("scenarios");if(e){if(e.length===0)return;s=s.where("id","in",e)}else if(t)s=s.where("analysis_id","=",t);else throw Pe("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await s.execute()}catch(s){throw Pe("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function Wd(...e){try{const t=zn.createHash("sha256");for(const r of e)t.update(r);return t.digest("hex")}catch(t){throw console.log("CodeYam Error: Error generating sha",e),t}}function hs(e,t){return t.map(r=>Hd(e,r))}function Hd(e,t){return at` ${at.ref(e)}.${at.ref(t)}`.as(t)}function Jd(e,t,r){return t.map(s=>Vd(e,s,r))}function Vd(e,t,r){return at` ${at.ref(e)}.${at.ref(t)}`.as(`_cy_${r}:${t}`)}function qd(e,...t){const r={};for(const[s,a]of Object.entries(e)){const o=s.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,c]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][c]=a;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=a}return r}const Gd=50;function Kd(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,s)=>e.slice(s*t,s*t+t))}function Xa({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:c,excludeMetadata:d}){const h=Te(),{jsonObjectFrom:u,jsonArrayFrom:m}=nn();let p=d?h.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):h.selectFrom("analyses").selectAll("analyses");if(e&&(p=p.where("project_id","=",e)),t){if(t.length===0)return null;p=p.where("id","in",t)}if(r){if(r.length===0)return null;p=p.where("file_id","in",r)}if(o){if(o.length===0)return null;p=p.where("commit_id","in",o)}return s&&(p=p.where("entity_name","=",s)),a&&(p=p.where("entity_sha","in",a)),i&&(p=p.where("branch_commit_sha","=",i)),c&&(p=p.limit(c)),d?h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[m(f.selectFrom("scenarios").select(hs("scenarios",yr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):h.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(hs("entities",ii)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),m(f.selectFrom("scenarios").select(hs("scenarios",yr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function Dt(e){const{ids:t,fileIds:r,entityShas:s,commitIds:a}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:a,key:"commitIds"}}).find(([d,{arr:h}])=>(h==null?void 0:h.length)>0);let c=[];if(i){const[d,{arr:h,key:u}]=i,m=Kd(h,Gd),p=[];for(let f=0;f<m.length;f++){const y=m[f],x=await Xa({...e,[u]:y}).execute();x&&p.push(...x)}c=p}else{const h=await Xa(e).execute();if(!h||h.length===0)return Pe("CodeYam: No analyses found",null,e),null;c=h}return c.length===0?null:c.map(Et)}catch(o){return Pe("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Qd(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=nn();let a=e.selectFrom("analysis_branches").select(vd).select(o=>s(o.selectFrom("branches").select(ai).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(a=t(a)),r(a)}async function At({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}){const f=Te(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):c?g=g.where("analyzed_tree_sha","=",c):s&&(g=g.where("file_id","=",s)),o&&(g=g.where("entity_name","=",o)),a?g=g.where("commit_id","=",a):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:v}=nn();g=g.select(w=>{const E=[];return E.push(x(w.selectFrom("entities").select(ii).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&E.push(x(w.selectFrom("files").select(Pd).whereRef("files.id","=","analyses.file_id")).as("file")),h&&E.push(x(w.selectFrom("projects").select(xd).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&E.push(v(w.selectFrom("scenarios").select(yr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&E.push(Qd(w,C=>C.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&E.push(x(w.selectFrom("commits").select(oi).select(C=>Yd(C).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),E});const b=await g.executeTakeFirst(),N=Date.now()-y;if(!b)return Pe("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null;if(N>100&&u){const w=b.commit,E=w!=null&&w.files?JSON.stringify(w.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${N}ms (files: ${Math.round(E/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return Et(b)}catch(g){return Pe("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null}}async function di({projectId:e,ids:t,names:r,includeInactive:s}){const a=Te();try{let o=a.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return s||(o=o.where("active_at","is not",null)),(await o.execute()).map(hn)}catch(o){return Pe("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function Zd({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=Te();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,h=>h.select(Jd("branches",ai,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const c=await i.execute();return!c||c.length===0?null:c.map(h=>qd(h,"branch")).map(oa)}catch(i){return Pe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function Xd(e){if(e.length===0)return new Map;const t=Te();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),s=new Set;if(r.forEach(o=>{o.branch_id&&s.add(o.branch_id),o.merged_branch_id&&s.add(o.merged_branch_id)}),s.size===0)return new Map;const a=await t.selectFrom("branches").selectAll().where("id","in",Array.from(s)).execute();return new Map(a.map(o=>[o.id,o]))}catch(r){return Pe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function eu(e){if(e.length===0)return new Map;const t=Te(),{jsonObjectFrom:r,jsonArrayFrom:s}=nn();try{const a=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),s(i.selectFrom("scenarios").select(yr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return a.forEach(i=>{const c=o.get(i.commit_id)||[];c.push(i),o.set(i.commit_id,c)}),o}catch(a){return Pe("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function tu(e){if(e.length===0)return new Map;const t=Te();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),s=new Map;return r.forEach(a=>{const o=s.get(a.commit_id)||[];o.push(a),s.set(a.commit_id,o)}),s}catch(r){return Pe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function br({projectId:e,branchId:t,ids:r,shas:s,fileNames:a,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const c=Te(),{jsonObjectFrom:d}=nn(),h=Date.now();try{let u;if(i){const b=Cd.map(N=>`commits.${N}`);u=c.selectFrom("commits").select(b)}else u=c.selectFrom("commits").selectAll("commits").select(b=>[d(b.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",b.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(s){if(s.length===0)return[];u=u.where("sha","in",s)}if(a&&a.length>0){const b=at.join(a.map(N=>at`${N}`),at`, `);u=u.where(at`
24
+ EXISTS (
25
+ SELECT 1
26
+ FROM json_each(${at.ref("commits.files")}) AS f
27
+ WHERE json_extract(f.value, '$.fileName') IN (${b})
28
+ )
29
+ `)}t&&(u=u.where("branch_id","=",t));const m=await u.orderBy("committed_at","desc").limit(o).execute(),p=Date.now()-h;if(!m||m.length===0)return[];if(p>100){const b=m.reduce((N,w)=>N+(w.files?JSON.stringify(w.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${p}ms (${m.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return m.map(N=>({...N,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Xt);const f=m.map(b=>b.id),[y,g,x]=await Promise.all([Xd(f),eu(f),tu(f)]);return m.map(b=>{const N=b.branch_id?y.get(b.branch_id):void 0,w=b.merged_branch_id?y.get(b.merged_branch_id):void 0,E=g.get(b.id)||[],C=x.get(b.id)||[];return{...b,branch:N,mergedBranch:w,analyses:E,entities:C}}).map(Xt)}catch(u){return Pe("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function ut({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:o,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||a&&a.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let h=0;h<o.length;h+=50){const u=o.slice(h,h+50),m=await ut({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:u,excludeMetadata:i});m&&d.push(...m)}return d}const c=Te();try{const u=await(i?c.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):c.selectFrom("entities").selectAll("entities")).$if(!!t,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!o,m=>m.where("entities.sha","in",o)).$if(!!s,m=>m.where("entities.file_path","in",s)).$if(!!a,m=>m.where("entities.name","in",a)).$if(!!r,m=>m.where("entities.file_id","in",r)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:s,shas:o}),null):u.map(Bn)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function nu(e,t){const{jsonArrayFrom:r}=nn();let s=e.selectFrom("entity_branches").select(Ed);return t&&(s=t(s)),r(s)}async function ui({projectId:e,sha:t}){const r=Te();try{const s=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(a=>nu(a,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return s?Bn(s):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&Pe("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(s){return Pe("CodeYam Error: Load Entity: Database error",s,{projectId:e,sha:t}),null}}const ms=1e3;async function hi({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const c=[];for(let d=0;d<t.length;d+=50){const h=t.slice(d,d+50),u=await hi({projectId:e,filePaths:h,fileIds:r,fileNames:s});u&&c.push(...u)}return c}const a=Te(),o=[];let i=0;try{for(;;){let c=a.selectFrom("files").selectAll().where("project_id","=",e).limit(ms).offset(i);if(t){if(t.length===0)return[];c=c.where("path","in",t)}if(r){if(r.length===0)return[];c=c.where("id","in",r)}if(s){if(s.length===0)return[];c=c.where("name","in",s)}const d=await c.execute();if(!d||d.length===0||(o.push(...d),d.length<ms))break;i+=ms}return o==null?void 0:o.map(sa)}catch(c){return console.log("CodeYam Error: Error loading project files in loadFiles",c),null}}async function ru({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=Te().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const c=await i.executeTakeFirst();if(!c)return a||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:s}),null;const d=aa(c);return s&&(d.files=await hi({projectId:d.id})),r&&(d.branches=await di({projectId:d.id,includeInactive:!1})),d}catch(o){return a||console.log("CodeYam Error: Error loading project",o),null}}function vr(e,t){const r={...e};for(const s in t){const a=t[s],o=e[s];a!=null&&typeof a=="object"&&!Array.isArray(a)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[s]=vr(o,a):a!==void 0&&(r[s]=a)}return r}async function Rt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let d=0;d<=4;d++)try{return await Te().transaction().execute(async h=>{var f,y;const u=await h.selectFrom("commits").select(["id","metadata"]).$if(!!e,g=>g.where("id","=",e)).$if(!!t,g=>g.where("sha","=",t)).executeTakeFirst();if(!u)return Pe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const m=u.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),s.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(f=m.currentRun)==null?void 0:f.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",s.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",a)),r=vr(r??{},{currentRun:s});else if(!r&&!o)return m;const p=r?vr(m,r):m;if(a&&p.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",p.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${p.currentRun.analyzerPid}, capture=${p.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${p.currentRun.analysesCompleted}, captures=${p.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((y=p.historicalRuns)==null?void 0:y.length)||0}`);const g={...p.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(g,null,2)),p.historicalRuns=[...p.historicalRuns||[],g],console.log(`[updateCommitMetadata] Historical runs after archiving: ${p.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(p.historicalRuns.map(x=>({entityShas:x.currentEntityShas,archivedAt:x.archivedAt,completed:{analyses:x.analysesCompleted,captures:x.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(p);try{return await h.updateTable("commits").set({metadata:JSON.stringify(p)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?p:(Pe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),m)}catch(g){return Pe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,g),m}})}catch(h){const u=h instanceof Error&&h.message.includes("database is locked");if(u&&d<4){const m=250*Math.pow(2,d);await new Promise(p=>setTimeout(p,m));continue}return Pe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${d+1} attempts`:""}`,h),null}return null}async function mi(e,t,r="analysis"){try{return await Te().transaction().execute(async s=>{const a=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!a)return Pe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=Et(a);return t(o.metadata,o),await s.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(Pe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return Pe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function gn(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await Te().transaction().execute(async i=>{const c=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!c)return Pe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const d=Et(c);return t(d.status,d),await i.updateTable("analyses").set({status:JSON.stringify(d.status)}).where("id","=",e).returningAll().executeTakeFirst()?d.status:(Pe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const c=i instanceof Error&&i.message.includes("database is locked");if(c&&o<4){const d=250*Math.pow(2,o);await new Promise(h=>setTimeout(h,d));continue}return Pe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${c?` after ${o+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function mn({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await Te().transaction().execute(async a=>{const o=await a.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return Pe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const c=r?vr(i,r):i;s&&await s(c,aa(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(c)}).where("id","=",o.id).returningAll().executeTakeFirst()?c:(Pe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return Pe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(a){return Pe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const su=()=>crypto.randomUUID();function au(e){const{id:t,projectId:r,analysisId:s,previousVersionId:a,analysis:o,metadata:i,data:c,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??su(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function ou(e){if(e.length===0)return[];const t=Te(),r=e.map(au);try{return(await t.insertInto("scenarios").values(r).onConflict(Ir(r[0],"id",["created_at"])).returningAll().execute()).map(si)}catch(s){return Pe("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const iu=()=>crypto.randomUUID();function lu(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??iu(),commit_id:r,branch_id:s}}async function eo(e){if(e.length===0)return[];const t=Te(),r=e.map(lu);try{return(await t.insertInto("commit_branches").values(r).onConflict(Ir(r[0],"id",["created_at"])).returningAll().execute()).map(oa)}catch(s){return Pe("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function cu(e,t){const r=Te(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(Ir(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return Pe("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const du=()=>crypto.randomUUID();function uu(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:c,analyzedAt:d,committedAt:h,author:u,metadata:m,files:p,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??du(),project_id:s??String(t),metadata:m?JSON.stringify(m):void 0,files:p?JSON.stringify(p):void 0,branch_id:a,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:c,ai_message:i,analyzed_at:d,committed_at:h}}async function hu({projectId:e,commits:t}){const r=Te();try{const s=t.reduce((i,c)=>{const{author:d}=c;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in s)await cu(i,s[i]);const a=t.map(i=>uu(i,e));return(await r.insertInto("commits").values(a).onConflict(Ir(a[0],"id",["created_at"])).returningAll().execute()).map(Xt)}catch(s){return Pe("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const wr=O.join(Ks.homedir(),".codeyam","secrets.json"),Nr=O.join(process.cwd(),".codeyam","secrets.json");async function Ft(){let e={};try{if(K.existsSync(Nr)){const o=await Ne.readFile(Nr,"utf8");e=JSON.parse(o)}}catch{console.warn(gr.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(wr)){const o=await Ne.readFile(wr,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(gr.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const s=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;s&&(t.ANTHROPIC_API_KEY=s);const a=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return a&&(t.GROQ_API_KEY=a),t}async function mu(e,t=!0){const r=t?wr:Nr,s=O.dirname(r);await Ne.mkdir(s,{recursive:!0}),await Ne.writeFile(r,JSON.stringify(e,null,2)),await Ne.chmod(r,384)}function pu(e=!0){return e?wr:Nr}async function to(){const e=await Ft(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function fu(e){console.log(),console.log(gr.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await Rc({type:"password",name:"key",message:"OpenAI API Key",validate:a=>a&&!a.startsWith("sk-")?"OpenAI API key should start with sk-":!0});s.key&&(t.OPENAI_API_KEY=s.key);break}return t}async function gu(e=!0){const t=await to();if(t.isValid)return t.secrets;const r=await fu(t.missing),a={...await Ft(),...r};await mu(a,e);const o=pu(e);return console.log(gr.green(`✓ Configuration saved to ${o}`)),(await to()).secrets}function yu(e){const t=O.resolve(e),r=O.parse(t).root;return t===r||t===O.resolve(Ks.homedir())}function pi(e=process.cwd()){let t=O.resolve(e);const r=O.parse(t).root;for(;t!==r;){if(yu(t))return null;const s=O.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=O.dirname(t)}return null}let fi=pi();function ge(){return fi}function xu(e){fi=e}function gi(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const bu={"Accordion.Item":e=>`<CYAccordion.Root type="single" collapsible>${e}</CYAccordion.Root>`,"Accordion.Header":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1">${e}</CYAccordion.Item></CYAccordion.Root>`,"Accordion.Trigger":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1"><CYAccordion.Header>${e}</CYAccordion.Header></CYAccordion.Item></CYAccordion.Root>`,"Accordion.Content":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1">${e}</CYAccordion.Item></CYAccordion.Root>`,"AlertDialog.Trigger":e=>`<CYAlertDialog.Root>${e}</CYAlertDialog.Root>`,"AlertDialog.Portal":e=>`<CYAlertDialog.Root>${e}</CYAlertDialog.Root>`,"AlertDialog.Overlay":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal>${e}</CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Content":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal>${e}</CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Title":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Description":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Action":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Cancel":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"Avatar.Image":e=>`<CYAvatar.Root>${e}</CYAvatar.Root>`,"Avatar.Fallback":e=>`<CYAvatar.Root>${e}</CYAvatar.Root>`,"Checkbox.Indicator":e=>`<CYCheckbox.Root>${e}</CYCheckbox.Root>`,"Collapsible.Trigger":e=>`<CYCollapsible.Root>${e}</CYCollapsible.Root>`,"Collapsible.Content":e=>`<CYCollapsible.Root>${e}</CYCollapsible.Root>`,"ContextMenu.Trigger":e=>`<CYContextMenu.Root>${e}</CYContextMenu.Root>`,"ContextMenu.Portal":e=>`<CYContextMenu.Root>${e}</CYContextMenu.Root>`,"ContextMenu.Content":e=>`<CYContextMenu.Root><CYContextMenu.Portal>${e}</CYContextMenu.Portal></CYContextMenu.Root>`,"ContextMenu.Item":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.CheckboxItem":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.RadioGroup":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.RadioItem":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.RadioGroup value="item-1">${e}</CYContextMenu.RadioGroup></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.ItemIndicator":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.CheckboxItem checked>${e}</CYContextMenu.CheckboxItem></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Label":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Separator":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Sub":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.SubTrigger":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.Sub>${e}</CYContextMenu.Sub></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.SubContent":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.Sub>${e}</CYContextMenu.Sub></CYContextMenu.Content></CYContextMenu.Root>`,"Dialog.Trigger":e=>`<CYDialog.Root>${e}</CYDialog.Root>`,"Dialog.Portal":e=>`<CYDialog.Root>${e}</CYDialog.Root>`,"Dialog.Overlay":e=>`<CYDialog.Root><CYDialog.Portal>${e}</CYDialog.Portal></CYDialog.Root>`,"Dialog.Content":e=>`<CYDialog.Root><CYDialog.Portal>${e}</CYDialog.Portal></CYDialog.Root>`,"Dialog.Title":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"Dialog.Description":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"Dialog.Close":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"DropdownMenu.Trigger":e=>`<CYDropdownMenu.Root>${e}</CYDropdownMenu.Root>`,"DropdownMenu.Portal":e=>`<CYDropdownMenu.Root>${e}</CYDropdownMenu.Root>`,"DropdownMenu.Content":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Portal>${e}</CYDropdownMenu.Portal></CYDropdownMenu.Root>`,"DropdownMenu.Item":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.CheckboxItem":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.RadioGroup":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.RadioItem":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.RadioGroup value="item-1">${e}</CYDropdownMenu.RadioGroup></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.ItemIndicator":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.CheckboxItem checked>${e}</CYDropdownMenu.CheckboxItem></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Label":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Separator":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Sub":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.SubTrigger":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.Sub>${e}</CYDropdownMenu.Sub></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.SubContent":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.Sub>${e}</CYDropdownMenu.Sub></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"Form.Field":e=>`<CYForm.Root>${e}</CYForm.Root>`,"Form.Label":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Control":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Message":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.ValidityState":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Submit":e=>`<CYForm.Root>${e}</CYForm.Root>`,"HoverCard.Trigger":e=>`<CYHoverCard.Root>${e}</CYHoverCard.Root>`,"HoverCard.Portal":e=>`<CYHoverCard.Root>${e}</CYHoverCard.Root>`,"HoverCard.Content":e=>`<CYHoverCard.Root><CYHoverCard.Portal>${e}</CYHoverCard.Portal></CYHoverCard.Root>`,"Menubar.Menu":e=>`<CYMenubar.Root>${e}</CYMenubar.Root>`,"Menubar.Trigger":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Portal":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Content":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Item":e=>`<CYMenubar.Root><CYMenubar.Menu><CYMenubar.Content>${e}</CYMenubar.Content></CYMenubar.Menu></CYMenubar.Root>`,"NavigationMenu.List":e=>`<CYNavigationMenu.Root>${e}</CYNavigationMenu.Root>`,"NavigationMenu.Item":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List>${e}</CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Trigger":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item>${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Content":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item><CYNavigationMenu.Trigger />{/* Dummy trigger for context */}${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Link":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item>${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Indicator":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item><CYNavigationMenu.Trigger />{/* Dummy trigger for context */}</CYNavigationMenu.Item>${e}</CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Viewport":e=>`<CYNavigationMenu.Root>${e}</CYNavigationMenu.Root>`,"Popover.Trigger":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Popover.Portal":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Popover.Content":e=>`<CYPopover.Root><CYPopover.Portal>${e}</CYPopover.Portal></CYPopover.Root>`,"Popover.Close":e=>`<CYPopover.Root><CYPopover.Content>${e}</CYPopover.Content></CYPopover.Root>`,"Popover.Anchor":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Progress.Indicator":e=>`<CYProgress.Root value={50}>${e}</CYProgress.Root>`,"RadioGroup.Item":e=>`<CYRadioGroup.Root>${e}</CYRadioGroup.Root>`,"RadioGroup.Indicator":e=>`<CYRadioGroup.Root><CYRadioGroup.Item value="item-1">${e}</CYRadioGroup.Item></CYRadioGroup.Root>`,"ScrollArea.Viewport":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"ScrollArea.Scrollbar":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"ScrollArea.Thumb":e=>`<CYScrollArea.Root><CYScrollArea.Scrollbar orientation="vertical">${e}</CYScrollArea.Scrollbar></CYScrollArea.Root>`,"ScrollArea.Corner":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"Select.Trigger":e=>`<CYSelect.Root>${e}</CYSelect.Root>`,"Select.Value":e=>`<CYSelect.Root><CYSelect.Trigger>${e}</CYSelect.Trigger></CYSelect.Root>`,"Select.Icon":e=>`<CYSelect.Root><CYSelect.Trigger>${e}</CYSelect.Trigger></CYSelect.Root>`,"Select.Portal":e=>`<CYSelect.Root>${e}</CYSelect.Root>`,"Select.Content":e=>`<CYSelect.Root><CYSelect.Portal>${e}</CYSelect.Portal></CYSelect.Root>`,"Select.Viewport":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.Item":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.ItemText":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Item value="item-1">${e}</CYSelect.Item></CYSelect.Content></CYSelect.Root>`,"Select.ItemIndicator":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Item value="item-1">${e}</CYSelect.Item></CYSelect.Content></CYSelect.Root>`,"Select.Group":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.Label":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Group>${e}</CYSelect.Group></CYSelect.Content></CYSelect.Root>`,"Select.Separator":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Slider.Track":e=>`<CYSlider.Root>${e}</CYSlider.Root>`,"Slider.Range":e=>`<CYSlider.Root><CYSlider.Track>${e}</CYSlider.Track></CYSlider.Root>`,"Slider.Thumb":e=>`<CYSlider.Root>${e}</CYSlider.Root>`,"Switch.Thumb":e=>`<CYSwitch.Root>${e}</CYSwitch.Root>`,"Tabs.List":e=>`<CYTabs.Root defaultValue="tab1">${e}</CYTabs.Root>`,"Tabs.Trigger":e=>`<CYTabs.Root defaultValue="tab1"><CYTabs.List>${e}</CYTabs.List></CYTabs.Root>`,"Tabs.Content":e=>`<CYTabs.Root defaultValue="tab1">${e}</CYTabs.Root>`,"Toast.Root":e=>`<CYToast.Provider>${e}</CYToast.Provider>`,"Toast.Title":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Description":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Action":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Close":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Viewport":e=>`<CYToast.Provider>${e}</CYToast.Provider>`,"ToggleGroup.Item":e=>`<CYToggleGroup.Root type="single">${e}</CYToggleGroup.Root>`,"Toolbar.Button":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.Link":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.Separator":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.ToggleGroup":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.ToggleItem":e=>`<CYToolbar.Root><CYToolbar.ToggleGroup type="single">${e}</CYToolbar.ToggleGroup></CYToolbar.Root>`,"Tooltip.Root":e=>`<CYTooltip.Provider>${e}</CYTooltip.Provider>`,"Tooltip.Trigger":e=>`<CYTooltip.Provider><CYTooltip.Root>${e}</CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Portal":e=>`<CYTooltip.Provider><CYTooltip.Root>${e}</CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Content":e=>`<CYTooltip.Provider><CYTooltip.Root><CYTooltip.Portal>${e}</CYTooltip.Portal></CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Arrow":e=>`<CYTooltip.Provider><CYTooltip.Root><CYTooltip.Content>${e}</CYTooltip.Content></CYTooltip.Root></CYTooltip.Provider>`};gi(bu);const vu={"Command.Input":e=>`<CYCommand>${e}</CYCommand>`,"Command.List":e=>`<CYCommand>${e}</CYCommand>`,"Command.Item":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Group":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Separator":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Empty":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Loading":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Shortcut":e=>`<CYCommand><CYCommand.List><CYCommand.Item value="x">${e}</CYCommand.Item></CYCommand.List></CYCommand>`,"Command.Dialog":e=>`<CYCommand.Dialog open>${e}</CYCommand.Dialog>`};gi(vu);function Mn(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const a=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const c=t[i];c&&typeof c=="object"&&!Array.isArray(c)||Array.isArray(c)?o[i]=Mn(a[i],c,r):o[i]=c}return o}const s={...e};for(const a in t)if(t[a]===null)s[a]=null;else if(Array.isArray(t[a])){const o=Array.isArray(e[a])?e[a]:[];s[a]=[];for(let i=0;i<t[a].length;i++){const c=t[a][i];typeof c=="object"&&c!==null?s[a][i]=Mn(o[i],c,r):s[a][i]=c}}else typeof t[a]=="object"&&t[a]!==null?s[a]=Mn(s[a]??{},t[a],r):s[a]=t[a];return s}catch(s){throw console.log("CodeYam: Error merging data",e,t),s}}async function wu({projectId:e,commit:t,branch:r}){var c,d,h,u,m,p,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await Zd({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(c=o.sort((g,x)=>{var v,b,N,w;return(((b=(v=g.branch.metadata)==null?void 0:v.permanent)==null?void 0:b.order)??999)-(((w=(N=x.branch.metadata)==null?void 0:N.permanent)==null?void 0:w.order)??999)})[0])==null?void 0:c.branch,s&&((h=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:h.order)!==void 0&&(((m=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:m.order)<=((f=(p=s.metadata)==null?void 0:p.permanent)==null?void 0:f.order)?s=r:a.active=!1);const y=o.filter(g=>g.active&&g.branch.id!==s.id||!g.active&&g.branch.id===s.id);y.length>0&&await eo(y.map(g=>({...g,active:g.branchId===s.id})))}(o==null?void 0:o.find(y=>y.branchId===a.branchId))||await eo([a])}function zt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=ge();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return Z.join(e,".codeyam","db.sqlite3")}async function Je(){const e=await gu();process.env.SQLITE_PATH=zt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Ie(e){await Je();const t=await ru({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await di({projectId:t.id,names:["_local"]}),s=r==null?void 0:r[0];if(!s)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:s}}async function Nu(e,t,r){await Je();const s=ge(),a=Wd(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let h="";if(s)try{if(h=_e(`git diff HEAD -- "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!h)try{const u=_e(`cat "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const m=u.split(`
30
+ `);h=`@@ -0,0 +1,${m.length} @@
31
+ ${m.map(p=>`+${p}`).join(`
32
+ `)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:h}}),i={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},c=await hu({projectId:e.id,commits:[i]});if(!c||c.length===0)throw new Error("Failed to create fake commit");return await wu({projectId:e.id,commit:c[0],branch:t}),c[0]}async function rn(){await Je();const e=await ut({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const d of e){const h=`${d.name}::${d.filePath}`,u=t.get(h);(!u||d.createdAt&&u.createdAt&&d.createdAt>u.createdAt)&&t.set(h,d)}const r=[...t.values()],s=e.map(d=>d.sha),a=await Dt({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const d of a)o.has(d.entitySha)||o.set(d.entitySha,[]),o.get(d.entitySha).push(d);const i=new Map;for(const d of e){const h=`${d.name}::${d.filePath}`,u=i.get(h)||[];u.push(d.sha),i.set(h,u)}return r.map(d=>{const h=o.get(d.sha)||[];if(h.length>0)return{...d,analyses:h};const u=`${d.name}::${d.filePath}`,m=i.get(u)||[];for(const p of m){if(p===d.sha)continue;const f=o.get(p);if(f&&f.length>0)return{...d,analyses:f}}return{...d,analyses:[]}})}async function Dr(e,t){await Je();const r=await Dt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await ui({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function Lr(e){if(await Je(),e.name&&e.projectId){const r=await Dt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,c=!e.filePath||o.filePath===e.filePath;return i&&c});if(s.length>0)return s.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),s[0];const a=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(a.length>0)return a.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),a[0]}}const t=await Dt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function yi(e){await Je();const t=await Dt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function tn(e){await Je();const t=await $e();if(!t)return null;const{project:r}=await Ie(t);return await ui({projectId:r.id,sha:e})}async function xi(e){var s,a,o,i,c,d,h,u;await Je();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const p of m){if(!p.filePath||!p.name)continue;const f=p.resolvedFilePath??p.filePath,y=p.resolvedName??p.name;let g=await ut({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&p.resolvedIsDefault&&(g=await ut({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],v=await Dt({entityShas:[x.sha],limit:1});let b,N,w;if(v&&v.length>0&&v[0].scenarios){const E=v[0],C=E.scenarios||[],S=C.length,k=C.find(I=>{var j,A;return(A=(j=I.metadata)==null?void 0:j.screenshotPaths)==null?void 0:A[0]});k&&(b=(o=(a=k.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],N=k.name),w={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||E.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:S,timestamp:E.createdAt?new Date(E.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else w={status:"not_analyzed"};t.push({...x,screenshotPath:b,scenarioName:N,analysisStatus:w})}}}if((c=e.metadata)!=null&&c.importedBy){const m=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const y=e.metadata.importedBy[p][f];y.shas&&m.push(...y.shas)}if(m.length>0){const p=await ut({projectId:e.projectId,shas:m});if(p)for(const f of p){const y=await Dt({entityShas:[f.sha],limit:1});let g,x,v;if(y&&y.length>0&&y[0].scenarios){const b=y[0],N=b.scenarios||[],w=N.length,E=N.find(S=>{var k,P;return(P=(k=S.metadata)==null?void 0:k.screenshotPaths)==null?void 0:P[0]});E&&(g=(h=(d=E.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0],x=E.name),v={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:w,timestamp:b.createdAt?new Date(b.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:v})}}}return{importedEntities:t,importingEntities:r}}async function $e(){try{const e=ge();if(!e)return null;const t=Z.join(e,".codeyam","config.json");return JSON.parse(await be.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function yn(){await Je();try{const e=await $e();if(!e)return null;const{project:t,branch:r}=await Ie(e),s=await br({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return s&&s.length>0?s[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function Or(){try{const e=ge();if(!e)return null;const t=Z.join(e,".codeyam","config.json");return JSON.parse(await be.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function bi(e){try{const t=ge();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=Z.join(t,e.filePath);return await be.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function vi(e){try{const t=ge();if(!t||!e.filePath)return!1;const r=Z.join(t,e.filePath),a=(await be.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return a>i+1e3}catch{return!1}}async function wi(e){if(await Je(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await ut({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await Dt({entityShas:r}),a=new Map;if(s)for(const i of s)a.has(i.entitySha)||a.set(i.entitySha,[]),a.get(i.entitySha).push(i);for(const[i,c]of a.entries())c.sort((d,h)=>{const u=new Date(d.createdAt||0).getTime();return new Date(h.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:a.get(i.sha)||[]}));return o.sort((i,c)=>{var u,m;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",h=((m=c.analyses[0])==null?void 0:m.createdAt)||c.createdAt||"";return new Date(h).getTime()-new Date(d).getTime()}),o}async function Ni(e){try{const t=ge();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=Z.join(t,".codeyam","config.json"),s=await be.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await be.writeFile(r,i,"utf8"),a.projectSlug){const c={};e.universalMocks!==void 0&&(c.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(c.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(c.webapps=e.webapps),await mn({projectSlug:a.projectSlug,metadataUpdate:c})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Cu=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:rn,getAnalysesForEntity:Dr,getAnalysisForExactEntitySha:yi,getCurrentCommit:yn,getEntityBySha:tn,getEntityCodeFromFilesystem:bi,getEntityHistory:wi,getLatestAnalysisForEntity:Lr,getProjectConfig:Or,getProjectSlug:$e,getRelatedEntities:xi,hasFileBeenModifiedSinceEntity:vi,requireBranchAndProject:Ie,updateProjectConfig:Ni},Symbol.toStringTag,{value:"Module"})),Ci="secrets.json";function Si(e){return Z.join(e,".codeyam",Ci)}function ki(){return Z.join(Ts.homedir(),".codeyam",Ci)}async function Fr(e){let t={};try{const r=ki(),s=await be.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=Si(e),s=await be.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function Su(e,t,r=!0){const s=r?ki():Si(e),a=Z.dirname(s);await be.mkdir(a,{recursive:!0}),await be.writeFile(s,JSON.stringify(t,null,2)+`
33
+ `,"utf-8")}async function ku(e){const t=await Fr(e);return!!(t.ANTHROPIC_API_KEY&&t.ANTHROPIC_API_KEY.length>0)||!!(t.OPENAI_API_KEY&&t.OPENAI_API_KEY.length>0)||!!(t.GROQ_API_KEY&&t.GROQ_API_KEY.length>0)||!!(t.OPENROUTER_API_KEY&&t.OPENROUTER_API_KEY.length>0)}const Eu=3;let En=0;async function Qn(e){if(!e||e.length===0)return[];if(En>=Eu)return console.warn(`[Loader] Circuit breaker open (${En} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let s=!1;const a=setTimeout(()=>{s||(s=!0,En++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);ut({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),En=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),En++,r([]))})})}function Au({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if($t(t))try{if(Ec(t).length>0)return!1;is(t,{recursive:!0})}catch{return!1}try{_e(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{_e(`rm -rf "${Ga(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=Ga(t,a);$t(o)&&is(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if($t(t))try{is(t,{recursive:!0})}catch{}return!1}}async function Pu({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[]}){const i=Date.now();if(!s&&o.length===0&&Au({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const d=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${d}s]`)}return}return new Promise((c,d)=>{const h=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,m=["-a","--no-specials"];s||m.push("--delete","--force"),m.push(...o);for(const f of r)m.push(`--exclude=${f}`);m.push(h,u);const p=St("rsync",m);p.on("exit",f=>{if(f===0){if(!a){const y=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${y}s]`)}c()}else console.error(`CodeYam Error: rsync failed with code: ${f}`,JSON.stringify({rsyncArgs:m},null,2)),d(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{a||console.log("Error occurred:",f),d(f)})})}const _u=Xs(Zs);async function Mu(e){return new Promise(t=>setTimeout(t,e))}function ju(e){try{return process.kill(e,0),!0}catch{return!1}}async function Ei(e){try{const{stdout:t}=await _u(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
34
+ `).filter(a=>a.trim()).map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a)),s=[...r];for(const a of r){const o=await Ei(a);s.push(...o)}return s}catch{return[]}}function no(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function Tu(e,t,r){const s=await Ei(e);for(const a of s.reverse())await no(a,t,r);await no(e,t,r)}async function In(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let s=0;async function a(o,i){await Tu(e,o,t);for(let c=0;c<i;c++)if(await Mu(1e3),s+=1e3,!await ju(e))return t(`Process tree ${e} successfully killed with ${o} after ${s/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await a("SIGINT",5)||await a("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await a("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${s/1e3} seconds.`),!1}function $u(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Gc(),createdAt:t}}Lc.config({quiet:!0});var Ai=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Ai||{});class Ru extends Oc{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Fc(),{process:s,type:a,name:o,metadata:i,parentId:c}=t,d={id:r,type:a,name:o,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:c,children:[]};if(this.processes.set(r,{info:d,process:s}),c){const m=this.processes.get(c);m&&(m.info.children=m.info.children||[],m.info.children.push(r))}const h=(m,p)=>{this.handleProcessExit(r,m,p)},u=m=>{this.handleProcessError(r,m)};return s.on("exit",h),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",h),s.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:a,process:o}=s;if(a.state==="completed"||a.state==="failed"||a.state==="killed")return;if(r.shutdownChildren&&a.children&&a.children.length>0&&await Promise.all(a.children.map(c=>this.shutdown(c,r))),o.pid)try{await In(o.pid,c=>console.log(`[Process ${t}] ${c}`))}catch(c){console.warn(`Error killing process ${t}:`,c)}await new Promise(c=>setTimeout(c,100)),a.state==="running"&&(a.state="killed",a.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(a=>this.shutdown(a.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(s=>this.shutdown(s.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,s=Date.now();for(const[a,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const c=o.process.__cleanup;c&&c(),this.processes.delete(a)}}}handleProcessExit(t,r,s){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.exitCode=r,o.signal=s,r===0?o.state="completed":s?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:a}=s;a.endedAt=Date.now(),a.state="failed",a.metadata={...a.metadata,error:r.message},this.emit("processExited",a)}}let ps=null;function Iu(){return ps||(ps=new Ru),ps}const Du={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Lu({command:e,args:t,workingDir:r,outputOptions:s=Du,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},c=St(e,t,{cwd:r,env:i});return Iu().register({process:c,type:Ai.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const m=f=>{const y=Z.join(r,"log.txt");K.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},p=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
35
+ `).map(v=>v.trim()?`[${g}]${y} ${v}`:v).join(`
36
+ `)};c.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&m(g+`
37
+ `),s.stdoutCallback&&s.stdoutCallback(y)}),c.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=p(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&m(g+`
38
+ `),s.stderrCallback&&s.stderrCallback(y)}),c.on("exit",function(f){u(f)})}),process:c}}function Ou(e){const t=[];return Object.keys(e).forEach(r=>{const s=e[r];s!==void 0&&(typeof s=="boolean"?s&&t.push(`--${r}`):s!==null&&t.push(`--${r}`,String(s)))}),t}function Fu({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,c])=>`${i}=${c}`).join(`
39
+ `);K.writeFileSync(`${e}/.env`,a);const o=Ou(r);return Lu({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const zu="/tmp/codeyam/local-dev";function Pi(e){return O.join(zu,e)}function _i(e){return O.join(Pi(e),"codeyam")}function ht(e){return O.join(Pi(e),"project")}function zr(e){return O.join(_i(e),"log.txt")}const Bu=[".sync-metadata.json","__codeyamMocks__"];async function Yu(e,t={}){const{port:r,silent:s=!0}=t,a=ht(e);if(r)try{_e(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{_e(`lsof +D "${a}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function Uu(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=ht(e),i=[],c=[];if(!K.existsSync(o))return{removed:i,errors:c};r&&await Yu(e,{port:s,silent:a});for(const d of Bu){const h=O.join(o,d);if(K.existsSync(h))try{(await Ne.stat(h)).isDirectory()?await Ne.rm(h,{recursive:!0,force:!0}):await Ne.unlink(h),i.push(d)}catch(u){c.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:c}}const Wu=O.dirname(Mr(import.meta.url));function Hu(e){let t=e;for(;t!==O.dirname(t);){const r=O.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=O.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Br(){const e=Hu(Wu);return O.join(e,"analyzer-template")}function xn(e){return _i(e)}function Ju(){const e=Br();return K.existsSync(O.join(e,".finalized"))}async function ro(e){const t=Br(),r=xn(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Ne.mkdir(O.dirname(r),{recursive:!0}),await Pu({sourcePath:t,destinationPath:r,silent:!0})}function bn(e,t,r,s){const a=xn(e);if(!K.existsSync(a))throw new Error(`Analyzer not found at ${a}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return Fu({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function Vu(e){const t=Br(),r=xn(e),s=O.join(t,".build-info.json"),a=O.join(r,".build-info.json");if(!K.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(K.readFileSync(s,"utf8")),i=JSON.parse(K.readFileSync(a,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function Yn(e,t){const r=xn(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await ro(e);return}const s=Vu(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await ro(e))}async function ia(e){await Uu(e,{killProcesses:!1})}const qu=O.dirname(Mr(import.meta.url));function Yr(){let e=qu;for(;e!==O.dirname(e);){const t=O.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=O.dirname(e)}return null}function un(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Gu(){const e=Yr();if(e){const t=[O.join(e,"src/webserver/build-info.json"),O.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=un(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function Ku(){const e=Yr();if(e){const t=O.join(e,"package.json");try{const r=JSON.parse(K.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const la=Gu(),fs=Ku();function ca(){if(fs!=="unknown"&&fs!=="0.1.0")return fs;const e=Yr();if(e)for(const t of[O.join(e,"src/webserver/build-info.json"),O.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=un(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function Mi(e){const t=Yr();let r=null;if(t){const d=[O.join(t,"src/webserver/build-info.json"),O.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const h of d)if(r=un(h),r)break}const s=Br(),a=O.join(s,".build-info.json"),o=un(a);let i=null;if(e){const d=xn(e),h=O.join(d,".build-info.json");i=un(h)}let c=!1;return o&&i?c=o.buildTime>i.buildTime:o&&!i&&e&&(c=!0),{cliVersion:la,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:c}}function Ur(e){const t=xn(e),r=O.join(t,".build-info.json"),s=un(r);return(s==null?void 0:s.version)??null}function ji(){const e=ge();return e?O.join(e,".codeyam","server.json"):null}function Ti(){const e=ji();if(!e||!K.existsSync(e))return null;try{const t=K.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function Qu(){const e=ji();if(e)try{K.unlinkSync(e)}catch{}}const Zu="/assets/globals-B17TBSS6.css";function so({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=_(!1);return a?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(de,{to:s,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function Xu({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:l("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),l("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function eh({serverVersion:e}){const[t,r]=_("stale"),[s,a]=_(null),o=async()=>{r("restarting"),a(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let c=0;const d=30,h=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}c++,c<d?setTimeout(()=>void u(),h):(a("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){a(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),l("div",{className:"flex-1",children:[t==="stale"&&l(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),l("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&l(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&l(ue,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&l("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[l("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function vn({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:c=14}){const[d,h]=_(!1),u=ie(()=>{navigator.clipboard.writeText(e).then(()=>{h(!0),setTimeout(()=>h(!1),a)}).catch(m=>{console.error("Failed to copy:",m)})},[e,a]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n(pt,{size:c,className:"text-green-500"}):n(wt,{size:c}):d?r:t})}function th({currentVersion:e,latestVersion:t}){const[r,s]=_(!1);if(r)return null;const a="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),l("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),l("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:a}),n(vn,{content:a,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors"})]})]}),n("button",{type:"button",onClick:()=>s(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let An=null,Zn=0;const nh=3600*1e3;function rh(e,t){const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(r.length,s.length);a++){const o=r[a]??0,i=s[a]??0;if(isNaN(o)||isNaN(i))return!1;if(o>i)return!0;if(o<i)return!1}return!1}async function sh(){const e=ca();if(An&&Date.now()-Zn<nh)return An;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),s=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!s.ok){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return An=c,Zn=Date.now(),c}const o=(await s.json()).version;if(!o){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return An=c,Zn=Date.now(),c}const i={updateAvailable:rh(o,e),latestVersion:o,currentVersion:e};return An=i,Zn=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function Cr(e){return O.join(e,".codeyam","queue.json")}function jn(e){const t=Cr(e);if(!K.existsSync(t))return{paused:!1,jobs:[]};try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function ah(e,t){const r=Cr(e),s=O.dirname(r);K.existsSync(s)||K.mkdirSync(s,{recursive:!0});try{K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const Ar=class Ar extends jr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=Se.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||Ar.IGNORED_DIRS.some(a=>r.includes(a+"/")||r.includes(a+"\\")))return;const s=this.debounceTimers.get(r);s&&clearTimeout(s),this.debounceTimers.set(r,setTimeout(()=>{this.debounceTimers.delete(r),this.syncFile(r)},this.DEBOUNCE_MS))}),console.log(`[InteractiveSyncWatcher] Watching ${this.options.projectRootPath} for changes`)}catch(t){console.error("[InteractiveSyncWatcher] Failed to start:",t)}}syncFile(t){const r=Z.join(this.options.projectRootPath,t),s=Z.join(this.options.tmpProjectPath,t);try{if(!Se.existsSync(r)){Se.existsSync(s)&&(Se.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=Z.dirname(s);Se.existsSync(a)||Se.mkdirSync(a,{recursive:!0}),Se.copyFileSync(r,s);const o=Z.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:o,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(a){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,a);const o={type:"error",fileName:Z.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",o)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null);for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),console.log("[InteractiveSyncWatcher] Stopped")}};Ar.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let Rs=Ar,oh=class extends jr{constructor(){super(),this.setMaxListeners(20)}emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}};const Is="__codeyam_dev_mode_event_emitter__";globalThis[Is]||(globalThis[Is]=new oh);const ao=globalThis[Is],Ds=new Map;async function ih(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await lh(e,t,r);else if(e.type==="baseline")await ch(e,t,r);else if(e.type==="recapture")await dh(e,t,r);else if(e.type==="capture-only")await uh(e,t,r);else if(e.type==="debug-setup")await hh(e,t,r);else if(e.type==="interactive-start")await mh(e,t,r);else if(e.type==="interactive-stop")await ph(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(s){throw console.error(`[Queue] Job ${e.id} failed:`,s),s}}async function lh(e,t,r){var g,x,v,b;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],{project:c}=await Ie(s);await ia(s),await Yn(s,{update:N=>console.log(`[Queue] ${N}`)});const d=Ur(s),h={...await Ft(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:zt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const m=e.onlyDataStructure,p={packageManager:((v=c.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:ht(s),port:0,noServer:!0,framework:u.framework,...m?{}:{orchestrateCapture:"local-sequential"}},f=bn(s,h,p),y=N=>{try{return process.kill(N,0),!0}catch{return!1}};await Rt({commitSha:a,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((b=e.filePaths)==null?void 0:b.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const N=new Promise((w,E)=>setTimeout(()=>E(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,N]),await Rt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await Rt({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(w=>setTimeout(w,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await In(f.process.pid,()=>{})}catch{}}}catch(N){if(console.error(`[Queue] Analysis job ${e.id} failed:`,N),f.process.pid&&y(f.process.pid))try{await In(f.process.pid,()=>{})}catch{}try{await Rt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:N instanceof Error?N.message:String(N)}}),r==null||r.notifyChange("commit")}catch(w){console.error("[Queue] Failed to update commit metadata after job failure:",w)}throw N}}async function ch(e,t,r){var p,f,y;const{projectSlug:s,commitSha:a}=e;if(!a)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${s}`);const{project:o}=await Ie(s);await ia(s),await Yn(s,{update:g=>console.log(`[Queue] ${g}`)});const i=Ur(s),c={...await Ft(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:zt(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=o.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const h={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:ht(s),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=bn(s,c,h),m=g=>{try{return process.kill(g,0),!0}catch{return!1}};await Rt({commitSha:a,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const g=new Promise((x,v)=>setTimeout(()=>v(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,g]),await Rt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${s}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{m(u.process.pid)&&await In(u.process.pid,()=>{})}catch{}}}async function dh(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Recapture job missing analysisId");const c=await At({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:v}=await import("./index-D_kZbNJs.js"),b=v(),N=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",c.entitySha).execute()}await gn(a,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Ie(s);await Yn(s,{update:v=>console.log(`[Queue] ${v}`)});const h=Ur(s),u={...await Ft(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:zt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ht(s),port:void 0,noServer:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??Ke.Next,orchestrateCapture:"local-sequential"},p=bn(s,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function uh(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Capture-only job missing analysisId");const c=await At({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:v}=await import("./index-D_kZbNJs.js"),b=v(),N=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",c.entitySha).execute()}await gn(a,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Ie(s);await Yn(s,{update:v=>console.log(`[Queue] ${v}`)});const h=Ur(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await Ft(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:zt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ht(s),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??Ke.Next,orchestrateCapture:"local-sequential"},p=bn(s,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function hh(e,t,r){var p,f,y,g;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const i=await At({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:c}=await Ie(s);await ia(s),await Yn(s,{update:x=>console.log(`[Queue] ${x}`)});const d={...await Ft(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:zt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((p=c.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:ht(s),port:void 0,noServer:!1,framework:((g=(y=(f=c.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||Ke.Next},m=await bn(s,d,h).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function mh(e,t,r){var x,v,b,N;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await At({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:c}=await Ie(s),d={...await Ft(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:zt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const h=ht(s),u=Z.join(h,".next","dev","lock");if(Se.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const w=_e(`pgrep -f ${JSON.stringify(h)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(w)for(const E of w.split(`
40
+ `).filter(Boolean))try{process.kill(parseInt(E,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${E}`)}catch{}}catch{}try{Se.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const m=Se.existsSync(h)&&Se.existsSync(Z.join(h,"package.json")),p={packageManager:((x=c.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:h,port:void 0,noServer:!1,fast:m,framework:((N=(b=(v=c.metadata)==null?void 0:v.webapps)==null?void 0:b[0])==null?void 0:N.framework)||Ke.Next};await gn(a,w=>{w.readyToBeCaptured=!0});const f=bn(s,d,p);await mi(a,w=>{w.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${f.process.pid}`);const y=ht(s),g=new Rs({projectRootPath:t,tmpProjectPath:y});g.on("sync",w=>{w.type==="file-synced"?ao.emitFileSynced(w.fileName,w.filePath):w.type==="error"&&ao.emitError(w.fileName,w.filePath)}),g.start(),Ds.set(a,g),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function ph(e,t,r){var h;const{projectSlug:s,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await At({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const i=(h=o.metadata)==null?void 0:h.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const c=Ds.get(a);c&&(c.stop(),Ds.delete(a),console.log(`[Queue] File sync watcher stopped for analysis ${a}`));const d=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${d}`);try{try{process.kill(d,0)}catch{console.log(`[Queue] Process ${d} already exited`);return}await In(d,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${d}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${d}:`,u),u}finally{await mi(a,u=>{u.interactiveMode=null})}}class fh{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},r&&(typeof r=="function"?this.notifier={notifyChange:()=>r()}:this.notifier=r)}start(){this.state=jn(this.projectRoot),this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 0,this.save()),this.state.jobs.length>0?(this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||Qs(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const a=new Promise((o,i)=>{this.completionCallbacks.set(r,c=>{c?i(c):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:a}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(a=>a.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const a=this.completionCallbacks.get(t);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return s}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const s=this.completionCallbacks.get(r.id);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const s=this.state.jobs.findIndex(i=>i.id===t);if(s===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const a=r==="up"?s-1:s+1;if(a<0||a>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[a],this.state.jobs[a]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${a})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await ih(t,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"success",completedAt:new Date().toISOString()});const r=this.completionCallbacks.get(t.id);r&&(r(),this.completionCallbacks.delete(t.id)),console.log(`[Queue] Job ${t.id} completed successfully`)}catch(r){console.error(`[Queue] Job ${t.id} failed:`,r),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"error",error:(r==null?void 0:r.message)||"Unknown error",completedAt:new Date().toISOString()});const s=this.completionCallbacks.get(t.id);s&&(s(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){ah(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class gh{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=Cr(this.projectRoot);if(!K.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=Cr(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=K.watch(r,(s,a)=>{a==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(s){console.error("[QueueFileWatcher] Failed to watch directory:",s)}}watchFile(t){try{this.watcher=K.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class yh{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=jn(r)}start(){this.cachedState=jn(this.projectRoot),console.log(`[ProxyQueue] Connected to background server at ${this.serverInfo.url}`),console.log(`[ProxyQueue] Current queue has ${this.cachedState.jobs.length} jobs`),this.fileWatcher=new gh(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const a=new Promise((i,c)=>{r=i,s=c}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),s(i)}),{jobId:o,completion:a}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${s}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${s}`)}this.refreshState()}getState(){return this.cachedState=jn(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=jn(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function xh(e){const t=O.join(e,".codeyam","server.json");if(!K.existsSync(t))return null;try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function bh(e){try{return process.kill(e,0),!0}catch{return!1}}async function vh(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}async function wh(e){const t=xh(e);return!t||!bh(t.pid)||!await vh(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class Nh extends jr{constructor(){super();Gn(this,"watcher",null);Gn(this,"dbPath",null);Gn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=zt();const{default:r}=await import("chokidar"),s=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(s,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",a=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",a=>{console.error("Database watcher error:",a),this.emit("error",a)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const s=Date.now(),a=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${a} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:s})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Nt=new Nh;let Qt=null,Tn=null;async function Ch(){if(!Qt){if(Tn){await Tn;return}Tn=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||pi()||process.cwd();if(xu(e),console.log(`[GlobalQueue] Project root: ${e}`),await Je(),process.env.NODE_ENV==="development")try{const r=Z.join(e,".codeyam","config.json"),a=JSON.parse(await Se.promises.readFile(r,"utf8")).projectSlug;a&&(await mn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),console.log("[GlobalQueue] Labs & Simulations auto-enabled for dev mode"))}catch(r){console.warn("[GlobalQueue] Could not auto-enable labs:",r)}const t=await wh(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new yh(t,e,()=>{Nt.notifyChange("unknown")});await r.start(),Qt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new fh(e,Nt);await r.start(),Qt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Tn}}async function Pt(){return Qt||await Ch(),Qt}function Sh(){return Qt||(Tn&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const kh=()=>[{rel:"stylesheet",href:Zu},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],Eh={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",npmUpdate:null,labs:null,simulationsEnabled:!1,isSimulationsReady:!1,isAdmin:!1,editorMode:!1,displayVersion:ca()};async function Ah({request:e,context:t}){var r,s,a,o,i,c,d,h,u,m,p;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=ge()||process.cwd(),[x,v,b]=await Promise.all([$e(),Fr(g),sh().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:N,branch:w}=await Ie(x);y();const E=await br({projectId:N.id,branchId:w.id,limit:20,skipRelations:!0});y();const C=E.length>0?E[0]:null,S=t.analysisQueue||Sh(),k=S==null?void 0:S.getState();y();const P=await Promise.all(((k==null?void 0:k.jobs)||[]).map(async B=>{var ce;const X=await Qn(B.entityShas||[]);return X.length===0&&((ce=B.entityShas)!=null&&ce.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",B.id),{...B,entities:X}}));let I=null;if(k!=null&&k.currentlyExecuting){const B=k.currentlyExecuting,X=await Qn(B.entityShas||[]);X.length===0&&((r=B.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",B.id),I={...B,entities:X}}const j=I?P.filter(B=>B.id!==I.id):P;let A=((a=(s=C==null?void 0:C.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if(A.length===0){const B=((o=C==null?void 0:C.metadata)==null?void 0:o.historicalRuns)||[];if(B.length>0){const ce=[...B].sort((we,ae)=>{const he=we.archivedAt||we.createdAt||"";return(ae.archivedAt||ae.createdAt||"").localeCompare(he)})[0];if(ce){const we=ce.analysisCompletedAt||ce.createdAt;if(we){const ae=new Date(we).getTime(),ye=Date.now()-1440*60*1e3;ae>ye&&(A=ce.currentEntityShas||[])}}}}const T=await Qn(A),R=[];v.ANTHROPIC_API_KEY&&R.push("ANTHROPIC_API_KEY"),v.GROQ_API_KEY&&R.push("GROQ_API_KEY"),v.OPENAI_API_KEY&&R.push("OPENAI_API_KEY"),v.OPENROUTER_API_KEY&&R.push("OPENROUTER_API_KEY"),y();const $=[];for(const B of E){const X=((i=B.metadata)==null?void 0:i.historicalRuns)||[];for(const ce of X)$.push(ce)}$.sort((B,X)=>{const ce=B.archivedAt||B.analysisCompletedAt||B.createdAt||"";return(X.archivedAt||X.analysisCompletedAt||X.createdAt||"").localeCompare(ce)});const J=new Set(((c=I==null?void 0:I.entities)==null?void 0:c.map(B=>B.sha))||[]),Y=$.filter(B=>!(B.currentEntityShas||[]).some(ce=>J.has(ce))).slice(0,3),U=new Set;for(const B of Y)for(const X of B.currentEntityShas||[])U.add(X);const H=await Qn(Array.from(U)),D=new Map;for(const B of H)D.set(B.sha,B);const M=Y.map(B=>({...B,entities:(B.currentEntityShas||[]).map(X=>D.get(X)).filter(X=>X!=null)})),Q=Ti(),W=(Q==null?void 0:Q.cliVersion)??"unknown",F=W!=="unknown"&&W!==la,te=((h=(d=N.metadata)==null?void 0:d.labs)==null?void 0:h.simulations)??!1,z=te?Ju():!1,L=((u=N.metadata)==null?void 0:u.editorMode)??!1,V={currentRun:(m=C==null?void 0:C.metadata)==null?void 0:m.currentRun,projectSlug:x,currentEntities:T,availableAPIKeys:R,queuedJobCount:j.length,queueJobs:j,currentlyExecuting:I,historicalRuns:M,isServerOutOfDate:F,serverVersion:W,npmUpdate:b!=null&&b.updateAvailable&&b.latestVersion?{latestVersion:b.latestVersion,currentVersion:b.currentVersion}:null,labs:((p=N.metadata)==null?void 0:p.labs)??null,simulationsEnabled:te,isSimulationsReady:z,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:L,displayVersion:ca()};return G(V)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),G(Eh)}}function Ph(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:c,isServerOutOfDate:d,serverVersion:h,npmUpdate:u,labs:m,simulationsEnabled:p,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=qe(),{toasts:v,closeToast:b}=ra(),N=mt(),w=ve(N),E=Pr();ee(()=>{w.current=N},[N]);const C=E.pathname.startsWith("/entity/")&&E.pathname.includes("/edit/")||E.pathname.startsWith("/dev/")||E.pathname.startsWith("/editor"),S=E.pathname.includes("/fullscreen")||E.pathname.startsWith("/editor");return ee(()=>{const k=new EventSource("/api/events");let P=null,I=0;const j=2e3;return k.addEventListener("message",A=>{const T=JSON.parse(A.data);if(T.type==="queue")w.current.revalidate(),I=Date.now();else if(T.type==="db-change"||T.type==="unknown"){const R=Date.now(),$=R-I;$<j?(P&&clearTimeout(P),P=setTimeout(()=>{w.current.revalidate(),I=Date.now(),P=null},j-$)):(w.current.revalidate(),I=R)}}),k.addEventListener("error",A=>{console.error("SSE connection error:",A)}),()=>{P&&clearTimeout(P),k.close()}},[]),l(ue,{children:[l("div",{className:`min-h-screen ${C?"":"grid"} bg-cygray-10`,style:C?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!C&&n(od,{labs:m,isAdmin:y,editorMode:g}),l("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[d&&n(eh,{serverVersion:h}),u&&u.currentVersion&&n(th,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),p&&s.length===0&&n(so,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),p&&!f&&n(so,{text:"Simulations enabled but not yet configured",subtext:"Run /codeyam-setup in Claude Code to install the analyzer and configure your dev server",linkText:"View Labs",linkTo:"/labs"}),n("div",{className:"flex-1",children:n(Yl,{})}),n(Xu,{version:x})]})]}),n(cd,{toasts:v,onClose:b}),!S&&p&&n(dd,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:c})]})}const _h=He(function(){return l("html",{lang:"en",children:[l("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(Ol,{}),n(Fl,{})]}),l("body",{children:[n(id,{children:n(sd,{children:n(Ph,{})})}),n(zl,{}),n(Bl,{})]})]})}),Mh=Object.freeze(Object.defineProperty({__proto__:null,default:_h,links:kh,loader:Ah},Symbol.toStringTag,{value:"Module"}));function Xn(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function sn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const c=Oe(),[d,h]=_(null),[u,m]=_(!1),[p,f]=_(!1),[y,g]=_(!1),x=ve(!1),v=ve(null),b=ve(null),N=ve(null),[w,E]=_(0),[C,S]=_(0),k=ve(null),P=ve(!1),{interactiveUrl:I,resetLogs:j}=kt(a,o),A=ve(t),T=ve(i);ee(()=>{T.current!==i&&(T.current=i,d&&(console.log("[useInteractiveMode] Manual refresh triggered"),f(!0),g(!1),E(0),S($=>$+1),P.current=!1,k.current&&(clearTimeout(k.current),k.current=null)))},[i,d]),ee(()=>{if(A.current!==t&&(A.current=t,v.current&&b.current&&r)){let $=v.current;if(N.current&&s){const Y=Xn(N.current),U=Xn(s);Y!==U&&($=$.replace(Y,U),N.current=s)}const J=Xn(b.current),q=Xn(r);$=$.replace(J,q),b.current=r,h($),f(!0),g(!1),E(0),S(Y=>Y+1),P.current=!1,k.current&&(clearTimeout(k.current),k.current=null);return}},[t,r,s]),ee(()=>{if(I){const $=I+"?width=600px";v.current=$,r&&(b.current=r),s&&(N.current=s),h($),m(!1),f(!0)}},[I]),ee(()=>{const $=J=>{J.data.type==="codeyam-resize"&&(P.current||(P.current=!0,k.current&&(clearTimeout(k.current),k.current=null),E(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{f(!1)})})))};return window.addEventListener("message",$),()=>window.removeEventListener("message",$)},[]);const R=()=>{P.current=!1,k.current&&clearTimeout(k.current);const $=300*Math.pow(2,w);k.current=setTimeout(()=>{P.current||(w<2?(E(J=>J+1),S(J=>J+1),f(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),f(!1)))},$)};return ee(()=>{o&&!x.current&&t&&e&&(x.current=!0,m(!0),g(!1),h(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(J){console.error("[useInteractiveMode] Failed to clear log file:",J)}j(),c.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,j,a]),ee(()=>{const $=e,J=()=>{if(x.current&&$){const Y=new URLSearchParams({action:"stop",analysisId:$});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const U=navigator.sendBeacon("/api/interactive-mode",Y);console.log("[useInteractiveMode] sendBeacon result:",U),U||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,keepalive:!0}).catch(H=>console.error("Failed to stop interactive mode:",H)))}},q=()=>{J()};return window.addEventListener("beforeunload",q),()=>{window.removeEventListener("beforeunload",q),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:x.current,analysisId:$}),J()}},[e]),{interactiveServerUrl:d,isStarting:u,isLoading:p,showIframe:y,iframeKey:C,onIframeLoad:R}}const er=10,jh=1024;function Wr({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[c,d]=_(null),h=ve(null),u=re(()=>[...s].sort((b,N)=>b.width-N.width),[s]),{fittingPresets:m,overflowPresets:p}=re(()=>{const b=[],N=[];for(const w of u)w.width<=jh?b.push(w):N.push(w);return N.sort((w,E)=>E.width-w.width),{fittingPresets:b,overflowPresets:N}},[u]),f=ie(b=>{if(!h.current)return null;const N=h.current.getBoundingClientRect(),w=b-N.left,E=N.width,C=E/2,k=(m.length>0?m[m.length-1].width:0)/2,P=C-k,I=C+k,j=p.length>0?(p.length-1)*er:0;if(p.length>0){if(w<P){if(w<=j){const T=Math.min(Math.floor(w/er),p.length-1);return p[T]}return p[p.length-1]}if(w>I){const T=E-w;if(T<=j){const R=Math.min(Math.floor(T/er),p.length-1);return p[R]}return p[p.length-1]}}const A=Math.abs(w-C);for(let T=m.length-1;T>=0;T--){const R=m[T],$=m[T-1],J=R.width/2,q=$?$.width/2:0;if(A<=J&&A>=q)return R}return m[0]||p[p.length-1]||null},[m,p]),y=ie(b=>{const N=f(b.clientX);d(N),a==null||a(N)},[f,a]),g=ie(()=>{d(null),a==null||a(null)},[a]),x=ie(b=>{const N=f(b.clientX);N&&r(N)},[f,r]),v=c||{name:t,width:e};return l("div",{ref:h,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[c&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${c.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map(b=>{const N=b.width===e,w=(c==null?void 0:c.name)===b.name,E=b.width/2;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${E}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${E}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map((b,N)=>{const w=N*er,E=b.width===e,C=(c==null?void 0:c.name)===b.name;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:l("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${c?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[v.name," - ",v.width,"px"]})})]})}function Hr({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=_(""),[i,c]=_(""),d=()=>{const u=a.trim();if(!u){c("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[l("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),l("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),l("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),l("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:a,onChange:u=>{o(u.target.value),c("")},onKeyDown:u=>{u.key==="Enter"&&a.trim()&&d(),u.key==="Escape"&&s()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),l("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!a.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function Jr(e){const[t,r]=_([]),s=e?`codeyam-custom-sizes-${e}`:null;ee(()=>{if(!s||typeof window>"u"){r([]);return}try{const c=localStorage.getItem(s);if(c){const d=JSON.parse(c);Array.isArray(d)&&r(d)}}catch(c){console.error("[useCustomSizes] Failed to load custom sizes:",c),r([])}},[s]);const a=ie(c=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(c))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[s]),o=ie((c,d,h)=>{r(u=>{const m=u.findIndex(y=>y.name===c),p={name:c,width:d,height:h};let f;return m>=0?(f=[...u],f[m]=p):f=[...u,p],a(f),f})},[a]),i=ie(c=>{r(d=>{const h=d.filter(u=>u.name!==c);return a(h),h})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Lt(){return l("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
41
+ .loader {
42
+ width: 48px;
43
+ height: 48px;
44
+ border: 3px solid rgba(0, 92, 117, 0.2);
45
+ border-radius: 50%;
46
+ display: inline-block;
47
+ position: relative;
48
+ box-sizing: border-box;
49
+ animation: rotation 1s linear infinite;
50
+ }
51
+ .loader::after {
52
+ content: '';
53
+ box-sizing: border-box;
54
+ position: absolute;
55
+ left: 50%;
56
+ top: 50%;
57
+ transform: translate(-50%, -50%);
58
+ width: 56px;
59
+ height: 56px;
60
+ border-radius: 50%;
61
+ border: 3px solid;
62
+ border-color: #005c75 transparent;
63
+ }
64
+
65
+ @keyframes rotation {
66
+ 0% {
67
+ transform: rotate(0deg);
68
+ }
69
+ 100% {
70
+ transform: rotate(360deg);
71
+ }
72
+ }
73
+ `})]})}const oo=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],Th=80;function pn(){const[e,t]=_(0);return ee(()=>{const r=setInterval(()=>{t(s=>(s+1)%oo.length)},Th);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:oo[e]})}async function $h({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw G("Invalid parameters",{status:400});const s=await tn(t);if(!s)throw G("Entity not found",{status:404});const a=await Lr(s),o=((c=a==null?void 0:a.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw G("Scenario not found",{status:404});const i=await $e();return G({entity:s,scenario:o,analysis:a,projectSlug:i})}const gs=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Rh=He(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=qe(),o=Ct(),[i]=fn(),[c,d]=_(null),[h,u]=_(1440),[m,p]=_({name:"Desktop",width:1440,height:900}),[f,y]=_(!1),[g,x]=_(null),{customSizes:v,addCustomSize:b}=Jr(a),N=re(()=>[...gs,...v],[v]),{interactiveServerUrl:w,isStarting:E,isLoading:C,showIframe:S,iframeKey:k,onIframeLoad:P}=sn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0}),{lastLine:I}=kt(a,E||C),j=()=>{o(`/entity/${t.sha}`)},A=(W,F)=>{u(W);const te=N.find(L=>L.width===W&&L.height===F);d(te||null),p({name:(te==null?void 0:te.name)||"Custom",width:W,height:F})},T=W=>{d(W),u(W.width),p({name:W.name,width:W.width,height:W.height})},R=W=>{b(W,m.width,m.height??900),y(!1),p(F=>({...F,name:W}))},$=((s==null?void 0:s.scenarios)||[]).filter(W=>{var F;return!((F=W.metadata)!=null&&F.sameAsDefault)}),J=$.findIndex(W=>W.id===(r==null?void 0:r.id)),q=J+1,Y=$.length,U=J>0,H=J<$.length-1,D=()=>{if(U){const W=$[J-1],F=encodeURIComponent(`/entity/${t.sha}/scenarios/${W.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${W.id}/fullscreen?from=${F}`)}},M=()=>{if(H){const W=$[J+1],F=encodeURIComponent(`/entity/${t.sha}/scenarios/${W.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${W.id}/fullscreen?from=${F}`)}},Q=E||C||!S;return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[l("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:$r,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:D,disabled:!U,className:`${U?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[q,"/",Y]}),n("button",{onClick:M,disabled:!H,className:`${H?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:j,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${gs[gs.length-1].width}px`,width:"100%"},children:n(Wr,{currentViewportWidth:h,currentPresetName:m.name,onDevicePresetClick:T,devicePresets:N,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||m.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:m.name,onChange:W=>{const F=N.find(te=>te.name===W.target.value);F&&T(F)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[N.map(W=>n("option",{value:W.name,children:W.name},W.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:W=>{const F=parseInt(W.target.value,10);!isNaN(F)&&F>0&&A(F,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
74
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
75
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
76
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
77
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
78
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:w?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[Q&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Lt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),I&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),I]})]})]})}),n("iframe",{src:w,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:P,style:{opacity:S?1:0}},k)]}):l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Lt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),I&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),I]})]})]})}),f&&n(Hr,{width:m.width,height:m.height??900,onSave:R,onCancel:()=>y(!1)})]})}),Ih=Object.freeze(Object.defineProperty({__proto__:null,default:Rh,loader:$h},Symbol.toStringTag,{value:"Module"}));function $i({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a}){const[o,i]=_(null),c=ve(null);ee(()=>{if(!r)return;const m=new EventSource("/api/dev-mode-events");return m.onmessage=p=>{try{const f=JSON.parse(p.data);f.type==="file-synced"&&(i(f.fileName),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{i(null)},5e3))}catch{}},()=>{m.close(),c.current&&clearTimeout(c.current)}},[r]);let d;s?d="error":t?d="starting":e?d="running":d="stopped";const h={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},u={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"};return l("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[l("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${h[d]}`}),l("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:u[d]})]}),(d==="stopped"||d==="error")&&a&&n("button",{onClick:a,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),o&&l(ue,{children:[l("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),l("span",{className:"text-green-400",children:["Synced: ",o]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),n("span",{className:"text-gray-500",children:"Claude edits auto-sync to preview via HMR"})]})}const Dh=`
79
+ .xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
80
+ .xterm.focus, .xterm:focus { outline: none; }
81
+ .xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
82
+ .xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; }
83
+ .xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
84
+ .xterm .composition-view.active { display: block; }
85
+ .xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
86
+ .xterm .xterm-screen { position: relative; }
87
+ .xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
88
+ .xterm .xterm-scroll-area { visibility: hidden; }
89
+ .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
90
+ .xterm.enable-mouse-events { cursor: default; }
91
+ .xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
92
+ .xterm.column-select.focus { cursor: crosshair; }
93
+ .xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
94
+ .xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
95
+ .xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
96
+ .xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
97
+ .xterm-dim { opacity: 1 !important; }
98
+ .xterm-underline-1 { text-decoration: underline; }
99
+ .xterm-underline-2 { text-decoration: double underline; }
100
+ .xterm-underline-3 { text-decoration: wavy underline; }
101
+ .xterm-underline-4 { text-decoration: dotted underline; }
102
+ .xterm-underline-5 { text-decoration: dashed underline; }
103
+ .xterm-overline { text-decoration: overline; }
104
+ .xterm-strikethrough { text-decoration: line-through; }
105
+ .xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
106
+ .xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
107
+ .xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
108
+ .xterm-decoration-top { z-index: 2; position: relative; }
109
+ `;function Lh(){if(document.getElementById("xterm-css"))return;const e=document.createElement("style");e.id="xterm-css",e.textContent=Dh,document.head.appendChild(e)}const Ri=Vl(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:c,projectSlug:d,onRefreshPreview:h,onShowResults:u,onHideResults:m,editorMode:p,onIdleChange:f,notificationsEnabled:y},g){const x=ve(null),v=ve(null),b=ve(null),N=ve(null),w=ve(null),E=ve(!1),C=ve(0),S=ve(!1),k=ve(f);k.current=f;const P=ve(y);P.current=y;const I=ie(()=>{var j;(j=b.current)==null||j.focus()},[]);return ql(g,()=>({sendInput(j){const A=N.current;A&&A.readyState===WebSocket.OPEN&&(A.send(JSON.stringify({type:"input",data:j})),setTimeout(()=>{A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var j;(j=b.current)==null||j.focus()},scrollToBottom(){var A;const j=(A=x.current)==null?void 0:A.querySelector(".xterm-viewport");j&&(j.scrollTop=j.scrollHeight)}})),ee(()=>{const j=x.current;if(!j)return;let A=!1;return Lh(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([T,R,$])=>{if(A)return;const J=new T.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},linkHandler:{activate(W,F){try{const te=new URL(F),z=te.searchParams.get("scenario");if(z&&te.pathname==="/editor"){const L=new BroadcastChannel("codeyam-editor");L.postMessage({type:"switch-scenario",scenarioId:z}),L.close();return}}catch{}window.open(F,"_blank")}}}),q=new R.FitAddon;J.loadAddon(q),J.loadAddon(new $.WebLinksAddon),J.open(j),requestAnimationFrame(()=>{try{q.fit()}catch{}}),b.current=J,J.focus(),setTimeout(()=>J.focus(),100),setTimeout(()=>J.focus(),500);const Y=window.location.protocol==="https:"?"wss:":"ws:",U=window.location.host;function H(W){const F=new URLSearchParams;return F.set("entityName",t),r&&F.set("entityType",r),s&&F.set("entitySha",s),a&&F.set("entityFilePath",a),o&&F.set("scenarioName",o),i&&F.set("scenarioDescription",i),c&&F.set("analysisId",c),d&&F.set("projectSlug",d),p&&F.set("editorMode","true"),W&&F.set("reconnectId",W),`${Y}//${U}/ws/terminal?${F.toString()}`}function D(W){const F=H(W),te=new WebSocket(F);N.current=te,te.onopen=()=>{C.current=0,S.current=!1,te.send(JSON.stringify({type:"resize",cols:J.cols,rows:J.rows}))},te.onmessage=z=>{var L,V;try{const B=JSON.parse(z.data);if(B.type==="session-id"){w.current=B.sessionId;return}if(B.type==="refresh-preview"){h==null||h(B.path);return}if(B.type==="show-results"){u==null||u();return}if(B.type==="hide-results"){m==null||m();return}if(B.type==="claude-idle"){if(console.log("[Terminal] Received claude-idle, notifications:",P.current,"permission:",typeof Notification<"u"?Notification.permission:"N/A"),(L=k.current)==null||L.call(k,!0),P.current&&typeof Notification<"u"&&Notification.permission==="granted"){const X=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});X.onclick=()=>{window.focus(),X.close()}}return}B.type==="output"&&(J.write(B.data),(V=k.current)==null||V.call(k,!1))}catch{J.write(z.data)}},te.onclose=()=>{if(E.current){J.write(`\r
110
+ \x1B[90m[Terminal session ended]\x1B[0m\r
111
+ `);return}const z=C.current;if(z<5&&w.current){const L=1e3*Math.pow(2,Math.min(z,3));C.current=z+1,J.write(`\r
112
+ \x1B[33m[Reconnecting...]\x1B[0m\r
113
+ `),setTimeout(()=>{E.current||D(w.current)},L)}else S.current?J.write(`\r
114
+ \x1B[90m[Terminal session ended]\x1B[0m\r
115
+ `):(S.current=!0,J.write(`\r
116
+ \x1B[33m[Starting new session...]\x1B[0m\r
117
+ `),w.current=null,C.current=0,D())},te.onerror=()=>{}}D(),J.onData(W=>{const F=N.current;F&&F.readyState===WebSocket.OPEN&&F.send(JSON.stringify({type:"input",data:W}))});let M=null;const Q=new ResizeObserver(()=>{M&&clearTimeout(M),M=setTimeout(()=>{let W;try{W=q.proposeDimensions()}catch{return}if(!W||W.cols===J.cols&&W.rows===J.rows)return;const F=j.querySelector(".xterm-viewport");let te,z=!0;F&&(te=F.scrollTop,z=F.scrollTop+F.clientHeight>=F.scrollHeight-10),q.fit(),F&&te!==void 0&&(z?F.scrollTop=F.scrollHeight:F.scrollTop=te);const L=N.current;L&&L.readyState===WebSocket.OPEN&&L.send(JSON.stringify({type:"resize",cols:J.cols,rows:J.rows}))},150)});Q.observe(j),v.current=()=>{var W;M&&clearTimeout(M),Q.disconnect(),E.current=!0,(W=N.current)==null||W.close(),N.current=null,J.dispose(),b.current=null}}),()=>{var T;A=!0,(T=v.current)==null||T.call(v),v.current=null}},[]),n("div",{ref:x,onClick:I,className:"w-full h-full",style:{padding:"4px 0 0 8px"}})});function Ge({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=_("loading"),[c,d]=_(!1),h=ve(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,m=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return ee(()=>{i("loading"),d(!1);const f=h.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?l("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n("img",{ref:h,src:u,alt:r,onLoad:m,onError:p,className:s||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&l("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Oh({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const a=Ct();return e.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8",children:n("p",{className:"text-gray-500 text-sm",children:"No scenarios found"})}):n("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map(o=>{var d,h;const i=o.id===t,c=(h=(d=o.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0];return l("button",{onClick:()=>{a(`/entity/${r}/scenarios/${o.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(Ge,{screenshotPath:c,cacheBuster:s,alt:o.name,className:"w-full h-full object-cover object-top"})}),l("div",{className:"p-2.5 min-w-0 flex-1",children:[l("div",{className:"text-white text-sm font-medium truncate",children:[i&&n("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[#005c75] mr-1.5 relative top-[-1px]"}),o.name]}),o.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:o.description})]})]},o.id)})})}async function Fh({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw G("Invalid parameters",{status:400});const s=await tn(t);if(!s)throw G("Entity not found",{status:404});const a=await Lr(s),o=((c=a==null?void 0:a.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw G("Scenario not found",{status:404});const i=await $e();return G({entity:s,scenario:o,analysis:a,projectSlug:i})}const ys=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],zh=He(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=qe(),o=Ct(),i=ve(null),c=ve(null),[d,h]=_(null),[u,m]=_(1440),[p,f]=_({name:"Desktop",width:1440,height:900}),[y,g]=_(!1),[x,v]=_(null),[b,N]=_("chat"),[w,E]=_(0),[C,S]=_(null),k=ie(ae=>{S(ae||null),E(he=>he+1)},[]),{customSizes:P,addCustomSize:I}=Jr(a),j=re(()=>[...ys,...P],[P]),{interactiveServerUrl:A,isStarting:T,isLoading:R,showIframe:$,iframeKey:J,onIframeLoad:q}=sn({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0,refreshTrigger:w}),Y=re(()=>{if(!A)return null;if(!C)return A;try{const ae=new URL(A);return ae.pathname=C,ae.href}catch{return A}},[A,C]),{lastLine:U}=kt(a,T||R),H=()=>{o(`/entity/${t.sha}`)},D=(ae,he)=>{m(ae);const ye=j.find(je=>je.width===ae&&je.height===he);h(ye||null),f({name:(ye==null?void 0:ye.name)||"Custom",width:ae,height:he})},M=ae=>{h(ae),m(ae.width),f({name:ae.name,width:ae.width,height:ae.height})},Q=ae=>{I(ae,p.width,p.height??900),g(!1),f(he=>({...he,name:ae}))},W=()=>{var he;N("chat"),(he=c.current)==null||he.sendInput("Create a new scenario for this entity based on the work we've just done. Create a name and description that reflects what the live preview is showing. Use the scenario data you've changed to create a new scenario in the database. If the data structure was fixed in any way you need to update that in the database as well and backfill all existing scenarios, then save to the database and capture a screenshot. Remember the database is at `.codeyam/db.sqlite3`, the scenarios table has all scenarios and the analyses table contains the scenariosDataStructure is its metadata.")},F=((s==null?void 0:s.scenarios)||[]).filter(ae=>{var he;return!((he=ae.metadata)!=null&&he.sameAsDefault)}),te=F.findIndex(ae=>ae.id===(r==null?void 0:r.id)),z=te+1,L=F.length,V=te>0,B=te<F.length-1,X=()=>{if(V){const ae=F[te-1];o(`/entity/${t.sha}/scenarios/${ae.id}/dev`)}},ce=()=>{if(B){const ae=F[te+1];o(`/entity/${t.sha}/scenarios/${ae.id}/dev`)}},we=T||R||!$;return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[l("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:$r,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:X,disabled:!V,className:`${V?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[z,"/",L]}),n("button",{onClick:ce,disabled:!B,className:`${B?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-2",children:"Dev Mode"})]}),n("button",{onClick:H,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close dev mode",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),l("div",{className:"flex-1 flex min-h-0",children:[l("div",{className:"flex-1 flex flex-col min-w-0",children:[l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${ys[ys.length-1].width}px`,width:"100%"},children:n(Wr,{currentViewportWidth:u,currentPresetName:p.name,onDevicePresetClick:M,devicePresets:j,hideLabel:!0,onHoverChange:v,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||p.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:p.name,onChange:ae=>{const he=j.find(ye=>ye.name===ae.target.value);he&&M(he)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[j.map(ae=>n("option",{value:ae.name,children:ae.name},ae.name)),p.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:p.width,onChange:ae=>{const he=parseInt(ae.target.value,10);!isNaN(he)&&he>0&&D(he,p.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"x"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:p.height??900}),p.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
118
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
119
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
120
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
121
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
122
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:A?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${p.width}px`,maxHeight:`${p.height}px`},children:[we&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Lt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the dev server to be ready"}),U&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),U]})]})]})}),n("iframe",{ref:i,src:Y||A,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:q,style:{opacity:$?1:0}},J)]}):l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Lt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Dev Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment with live preview"}),U&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),U]})]})]})})]}),l("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[l("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-0",children:[l("button",{onClick:()=>N("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",b==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>N("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",b==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),b==="chat"&&n("button",{onClick:W,disabled:!A,className:"px-3 py-1 text-[11px] font-medium rounded bg-[#005c75] text-white hover:bg-[#004a5c] transition-colors disabled:bg-gray-600 disabled:text-gray-400 disabled:cursor-not-allowed cursor-pointer",children:"Save Scenario"})]}),n("div",{style:{display:b==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(Ri,{ref:c,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:a,onRefreshPreview:k})}),b==="scenarios"&&n(Oh,{scenarios:F,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n($i,{serverUrl:A,isStarting:T,projectSlug:a}),y&&n(Hr,{width:p.width,height:p.height??900,onSave:Q,onCancel:()=>g(!1)})]})}),Bh=Object.freeze(Object.defineProperty({__proto__:null,default:zh,loader:Fh},Symbol.toStringTag,{value:"Module"}));async function Yh({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{url:r,filename:s,viewportWidth:a,viewportHeight:o}=t;if(!r||!s)return new Response(JSON.stringify({error:"url and filename are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),c=O.join(i,".codeyam","journal","screenshots");await Ne.mkdir(c,{recursive:!0});const d=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),h=O.join(c,`${d}.png`),u=O.dirname(new URL(import.meta.url).pathname);let m=u;for(let v=0;v<5;v++){const b=O.dirname(m);if(O.basename(b)==="webserver"||O.basename(m)==="webserver"){m=O.basename(m)==="webserver"?m:b;break}m=b}const p=[O.join(m,"scripts","journalCapture.ts"),O.join(m,"app","lib","journalCapture.ts"),O.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),O.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const v of p)try{await Ne.access(v),f=v;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${p.join(", ")}`),f=p[0]);const y=JSON.stringify({url:r,outputPath:h,viewportWidth:a,viewportHeight:o}),g=await new Promise(v=>{const b=St("npx",["tsx",f,y],{cwd:i,env:{...process.env}});let N="",w="";b.stdout.on("data",E=>{N+=E.toString()}),b.stderr.on("data",E=>{w+=E.toString()}),b.on("close",E=>{v(E===0?{success:!0,output:N}:{success:!1,output:N,error:w||`Process exited with code ${E}`})}),b.on("error",E=>{v({success:!1,output:"",error:E.message})})});if(!g.success)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:g.error}),{status:500,headers:{"Content-Type":"application/json"}});const x=`screenshots/${d}.png`;return new Response(JSON.stringify({success:!0,path:x}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-screenshot] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Uh=Object.freeze(Object.defineProperty({__proto__:null,action:Yh},Symbol.toStringTag,{value:"Module"})),Ii=Vs({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),da=()=>{const e=_r(Ii);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Vr=({children:e})=>{const[t,r]=_({height:720,width:1200}),[s,a]=_(1),[o,i]=_(1200),c=ve(null),d=ie(({height:m,width:p})=>{r(f=>({height:m??f.height,width:p??f.width}))},[]),h=ie(m=>{a(m)},[]),u=ie(m=>{i(m)},[]);return n(Ii.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:c,scale:s,updateScale:h,maxWidth:o,updateMaxWidth:u},children:e})},Wh=typeof window<"u";function Hh(){const[e,t]=_(null);return ee(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Jh=1200,Vh=720,io=30,qh=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:c,onDimensionChange:d})=>{const h=Hh(),[u,m]=_(!1),[p,f]=_(!1),[y,g]=_(Jh),[x,v]=_(Vh),[b,N]=_(null),[w,E]=_(null),{dimensions:C,updateDimensions:S,iframeRef:k,updateScale:P,updateMaxWidth:I}=da(),j=re(()=>Math.min(1,y/C.width),[y,C.width]),A=w!==null?w:j;ee(()=>{u||(P(A),c==null||c(A))},[A,P,c,u]),ee(()=>{I(y)},[y,I]);const T=ie(()=>{m(!0),E(j)},[j]),R=ie(()=>{m(!1),E(null)},[]),$=ie((H,D)=>{const M=w!==null?w:1,Q=Math.round(D.size.width/M);S({width:Q}),d==null||d(Q,C.height)},[S,w,d,C.height]),J=ie(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ee(()=>{const H=D=>{if(D.data.type==="codeyam-resize"){if(t&&D.data.name!==t||C.height===D.data.height||D.data.height===0)return;S({height:D.data.height})}};return window.addEventListener("message",H),()=>{window.removeEventListener("message",H)}},[k,t,s,C,S]),ee(()=>{p&&o&&o(k.current)},[p,o,k]),ee(()=>{if(!t)return;const H=setInterval(()=>{var D,M;(M=(D=k==null?void 0:k.current)==null?void 0:D.contentWindow)==null||M.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(H)},[t,k]),ee(()=>{const H=()=>{const D=document.getElementById("scenario-container");if(!D)return;const M=D.getBoundingClientRect(),Q=D.clientWidth-io*2,W=window.innerHeight-M.top-io*2,F=Math.max(W,400),te=window.innerHeight-M.top;g(Q),v(F),N(te)};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[]),ee(()=>{S({width:s,height:a})},[s,a,S]);const q=re(()=>C.width*A,[C.width,A]),Y=re(()=>{const H=C.height,D=H*A;return H&&H!==720&&H!==900&&D<x?D:x},[C.height,x,A]),U=ie(()=>{window.history.back()},[]);return!Wh||!h?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):l("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
123
+ .react-resizable-handle-e {
124
+ display: flex !important;
125
+ align-items: center !important;
126
+ justify-content: center !important;
127
+ width: 6px !important;
128
+ height: 48px !important;
129
+ right: -8px !important;
130
+ top: 50% !important;
131
+ transform: translateY(-50%) !important;
132
+ cursor: ew-resize !important;
133
+ background: #d1d5db !important;
134
+ border-radius: 3px !important;
135
+ opacity: 0 !important;
136
+ transition: all 0.2s ease !important;
137
+ }
138
+ .react-resizable-handle-e:hover {
139
+ opacity: 0.8 !important;
140
+ background: #9ca3af !important;
141
+ }
142
+ .react-resizable:hover .react-resizable-handle-e {
143
+ opacity: 0.4 !important;
144
+ }
145
+ `}),n(h,{width:q,height:Y,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:T,onResizeStop:R,onResize:$,children:n("div",{className:"overflow-auto",style:{width:`${q}px`,height:`${Y}px`},children:n("div",{style:{width:`${C.width}px`,height:`${C.height}px`,transform:`scale(${A})`,transformOrigin:"top left"},children:r?n("iframe",{ref:k,className:"w-full h-full rounded-lg",src:r,onLoad:J,sandbox:"allow-scripts allow-same-origin"}):l("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:U,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Gh({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:c,className:d=""}){const[h,u]=_(!1),[m,p]=_(String(r)),[f,y]=_(String(s)),[g,x]=_(!1),[v,b]=_(!1),N=ve(null);ee(()=>{g||p(String(r))},[r,g]),ee(()=>{v||y(String(s))},[s,v]),ee(()=>{const A=T=>{N.current&&!N.current.contains(T.target)&&u(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[]);const w=re(()=>{const A=e.find(R=>R.width===r&&R.height===s);if(A)return A.name;const T=t.find(R=>R.width===r&&R.height===s);return T?T.name:"Custom"},[e,t,r,s]),E=w==="Custom",C=A=>{o(A.width,A.height),u(!1)},S=A=>{const T=A.target.value;p(T);const R=parseInt(T,10);!isNaN(R)&&R>0&&o(R,s)},k=A=>{const T=A.target.value;y(T);const R=parseInt(T,10);!isNaN(R)&&R>0&&o(r,R)},P=()=>{x(!1);const A=parseInt(m,10);(isNaN(A)||A<=0)&&p(String(r))},I=()=>{b(!1);const A=parseInt(f,10);(isNaN(A)||A<=0)&&y(String(s))},j=A=>{(A.key==="Enter"||A.key==="Escape")&&A.target.blur()};return l("div",{className:`flex items-center gap-3 ${d}`,children:[l("div",{className:"relative",ref:N,children:[l("button",{onClick:()=>u(!h),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:w}),n("svg",{className:`w-4 h-4 transition-transform ${h?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),h&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:l("div",{className:"py-1",children:[e.length>0&&l(ue,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(A=>l("button",{onClick:()=>C(A),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${w===A.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:A.name}),l("span",{className:"text-xs text-gray-500",children:[A.width," x ",A.height]})]},A.name))]}),t.length>0&&l(ue,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((A,T)=>A.width-T.width).map(A=>l("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${w===A.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[l("button",{onClick:()=>C(A),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:A.name}),l("span",{className:"text-xs text-gray-500",children:[A.width," x ",A.height]})]}),c&&n("button",{onClick:T=>{T.stopPropagation(),w===A.name&&e.length>0&&o(e[0].width,e[0].height),c(A.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},A.name))]})]})})]}),l("div",{className:"flex items-center gap-1 text-sm",children:[l("div",{className:"flex items-center",children:[n("input",{type:"text",value:m,onChange:S,onFocus:()=>x(!0),onBlur:P,onKeyDown:j,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),l("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:k,onFocus:()=>b(!0),onBlur:I,onKeyDown:j,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),a!==void 0&&a<1&&l("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(a*100),"%)"]})]}),E&&n("button",{onClick:i,className:"px-3 py-1.5 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors",children:"Save Custom Size"})]})}function xs(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const s of e)if(s.name===t||s.title===t||s.id===t)return s}return e[t]}function Ls(e){return e&&(typeof e=="object"||Array.isArray(e))}function Kh(e){return Array.isArray(e)?e.length:void 0}function Qh(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((s,a)=>a.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((a,o)=>{const i=Ls(t[a]),c=Ls(t[o]);return i&&!c?1:!i&&c?-1:a.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((a,o)=>a.localeCompare(o))}}function Zh({scenarioFormData:e,handleInputChange:t}){return l("div",{className:"p-3 flex flex-col gap-3",children:[l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),l("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Xh({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=ie(()=>{a&&a(e)},[a,e]);return l("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),l("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Di=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Di||{});const em=({name:e,value:t,options:r,onChange:s})=>{const a=ie(o=>{s({target:{name:e,value:o.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:a,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},tm=({name:e,value:t,onChange:r})=>{const s=ie(a=>{const o=a.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
146
+ bg-gray-300 checked:bg-blue-600
147
+ after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
148
+ after:bg-white after:rounded-full after:transition-transform
149
+ checked:after:translate-x-4`})})};function nm({dataType:e,path:t,value:r,onChange:s}){const a=re(()=>t[t.length-1],[t]),o=re(()=>t.join("-"),[t]),i=ie(d=>{s(t,d.target.value)},[s,t]),c=ie(d=>{s(t,d.target.value)},[s,t]);return l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:a==="~~codeyam-code~~"?"Dynamic Field":a}),e.includes("|")?n(em,{name:o,value:r,options:e.split("|"),onChange:i}):e===Di.BOOLEAN?n(tm,{name:o,value:r??!1,onChange:c}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function rm({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=_(!1),[c,d]=_(""),h=ie(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const m=e.scenarios.find(x=>x.name===t);if(!m)throw new Error("Scenario not found");const p=e.scenarios.find(x=>x.name===Rr),f=await a(c,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,v)=>{const b=Object.assign({},x);return g(x)&&g(v)&&Object.keys(v).forEach(N=>{g(v[N])?N in x?b[N]=y(x[N],v[N]):Object.assign(b,{[N]:v[N]}):Object.assign(b,{[N]:v[N]})}),b},g=x=>x&&typeof x=="object"&&!Array.isArray(x);m.metadata.data=y(y((p==null?void 0:p.metadata.data)||{},m.metadata.data),f.data||{}),s(m),i(!1),d("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,c,r,t,s,a]),u=ie(m=>{d(m.target.value)},[]);return l("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:c}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${c.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void h(),children:o?l(ue,{children:[l("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function sm({namedPath:e,path:t,last:r,onClick:s}){const a=ie(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:a,children:e[e.length-1]})}function am({dataItem:e,onClick:t}){const r=ie(()=>t([]),[t]),s=re(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return l("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&l("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(s).map((a,o)=>l("div",{className:"flex items-center gap-1",children:[n(sm,{namedPath:e.namedPath.slice(0,o+s+1),path:e.path.slice(0,o+s+1),last:o+s===e.namedPath.length-1,onClick:t}),o+s<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${a}-${o+s}`))]})}function lo({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:c}){const d=re(()=>r.data,[r]),h=re(()=>Qh(r),[r]);return l("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(am,{dataItem:r,onClick:s}),l("div",{className:"flex flex-col gap-3",children:[n(rm,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),h==null?void 0:h.map((u,m)=>{var f;if(Ls(d[u])){let y=u;isNaN(Number(u))||(y=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...r.path,u],x=[...r.namedPath,y];return n(Xh,{path:g,namedPath:x,isArray:Array.isArray(d),count:Kh(d[u]),onClick:s},`data-${u}-${m}`)}if(u==="id")return null;const p=[...r.path,u];return n(nm,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:p,value:d[u],onChange:a},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),l("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:c==null?void 0:c.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:c!=null&&c.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:c==null?void 0:c.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(c==null?void 0:c.message)&&!(c!=null&&c.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${c.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:c.message})]})}function co({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=_(r),c=[];return s&&c.push("border-t"),a&&c.push("border-b"),l("div",{className:`${c.join(" ")} border-gray-300`,children:[l("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const om=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:c,onGenerateData:d,saveFeedback:h})=>{const u=ie((S,k)=>{const P=Object.assign({},S),I=j=>j&&typeof j=="object"&&!Array.isArray(j);return I(S)&&I(k)&&Object.keys(k).forEach(j=>{I(k[j])?j in S?P[j]=u(S[j],k[j]):Object.assign(P,{[j]:k[j]}):Object.assign(P,{[j]:k[j]})}),P},[]),[m,p]=_({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,y]=_(null),g=re(()=>({...m.data}),[m]),x=re(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),v=re(()=>{const S={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(S).reduce((k,P)=>{if(P.includes(".")){const[I,j]=P.split(".");k[I]||(k[I]={}),k[I][j]=S[P]}else k[P]=S[P];return k},{})},[r]),b=ie(async S=>{S.preventDefault();const k=S.target.querySelector('input[name="recapture"]'),P=(k==null?void 0:k.value)==="true",I={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:P,dataToSave:I,rawFormData:m.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(I,null,2).substring(0,1e3));const j=s==null?void 0:s.scenarios.map(A=>!a&&A.name===e.name?{...A,name:m.name,description:m.description,metadata:{...A.metadata,data:I}}:A);a&&j.push({name:m.name,description:m.description,metadata:{data:I,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",j),o&&await o(j,{recapture:P}),i&&i(m.name)},[s,e.name,m,g,a,o,i]),N=ie(S=>{p(k=>({...k,[S.target.name]:S.target.value}))},[]),w=ie(S=>{y(k=>{if(!k)return null;for(const P of[{arguments:S.metadata.data.argumentsData},S.metadata.data.mockData]){let I=P;for(const j of k.path)if(I=xs(I,j),!I)break;I&&(k.data=I)}return{...k}}),p({name:S.name,description:S.description,data:S.metadata.data})},[]),E=ie((S,k)=>{p(P=>{for(const I of[{"Function Arguments":P.data.argumentsData},{"Retrieved Data":P.data.mockData}]){let j=I;for(const A of S.slice(0,-1))if(j=xs(j,A),!j)break;if(j){const A=j[S[S.length-1]];y(T=>T?(T.namedPath[T.namedPath.length-1]===A&&(T.namedPath[T.namedPath.length-1]=k.toString()),T.data[S[S.length-1]]=k,{...T}):null),j[S[S.length-1]]=k}}return{...P}})},[]),C=ie(S=>{var j,A,T;if(S.length===0){y(null);return}let k=x;const P=[];let I=v;for(const R of S){if(P.push(isNaN(parseInt(R))?R:((j=k[R])==null?void 0:j.name)??((A=k[R])==null?void 0:A.title)??((T=k[R])==null?void 0:T.id)??R),k=xs(k,R),!k){console.log("Data not found",k,R),y(null);return}Array.isArray(I)?I=I[0]:I=I[R]}y({path:S,namedPath:P,data:k,structure:I})},[x,v]);return ee(()=>{const S=k=>{var P;k.data.type==="codeyam-log"&&((P=k.data.data)!=null&&P.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",k.data.data)};return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[]),ee(()=>{var S;if((S=c==null?void 0:c.current)!=null&&S.contentWindow){const k={arguments:g.argumentsData??[],...g.mockData??{}},P={type:"codeyam-override-data",name:e.name,data:JSON.stringify(k)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:P.type,name:P.name,dataPreview:JSON.stringify(k).substring(0,200)+"...",fullData:k}),c.current.contentWindow.postMessage(P,"*")}},[g,e,c]),n("form",{method:"post",onSubmit:S=>void b(S),children:f?n(lo,{analysis:s,scenarioName:m.name,dataItem:f,onClick:C,onChange:E,onAIResult:w,onGenerateData:d,saveFeedback:h}):l(ue,{children:[n(co,{title:"Edit Name and Description",borderT:!0,children:n(Zh,{scenarioFormData:m,handleInputChange:N})}),e.metadata.data&&n(co,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(lo,{analysis:s,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:x,structure:v},onClick:C,onChange:E,onAIResult:w,onGenerateData:d,saveFeedback:h})})]})})};function qr({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:c,onScaleChange:d,onDimensionChange:h,projectSlug:u,defaultWidth:m=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:y}=kt(u??null,s||a);return r?l("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(qh,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:m,defaultHeight:p,onIframeLoad:c,onScaleChange:d,onDimensionChange:h},i)}),!o&&(s||a)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Lt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),y]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Lt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(pn,{}),y]})]})]})})}const im=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function lm({params:e}){var d,h;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const s=await Dr(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(d=a.scenarios)==null?void 0:d.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(h=a.scenarios)==null?void 0:h.find(u=>u.name===Rr),c=await $e();return G({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:c})}function cm(){var R,$,J;const e=qe(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=Ct(),{iframeRef:c}=da(),[d,h]=_(!1),[u,m]=_(null),[p,f]=_(null),[y,g]=_(!1),[x,v]=_(!1),[b,N]=_(null),{interactiveServerUrl:w,isStarting:E,isLoading:C,showIframe:S,iframeKey:k,onIframeLoad:P}=sn({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),I=ie(async(q,Y)=>{h(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",Y),console.log("[EditScenario] Scenarios to save:",q);try{const U={analysis:t,scenarios:q};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:q.length,scenarioNames:q.map(M=>M.name)});const H=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(U)}),D=await H.json();if(console.log("[EditScenario] API response:",D),!H.ok||!D.success)throw new Error(D.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),Y!=null&&Y.recapture&&r.id&&w){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:w}),m("Changes saved. Capturing screenshot...");const M={serverUrl:w,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",M);const Q=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});console.log("[EditScenario] Capture response status:",Q.status);const W=await Q.json();if(console.log("[EditScenario] Capture response body:",W),!Q.ok||!W.success)throw console.error("[EditScenario] Capture failed:",W),new Error(W.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",W),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),m("Recapture successful")}else if(Y!=null&&Y.recapture&&!w){console.log("[EditScenario] No running server, using queued recapture");const M=new FormData;M.append("analysisId",t.id||""),M.append("scenarioId",r.id||"");const Q=await fetch("/api/recapture-scenario",{method:"POST",body:M}),W=await Q.json();if(!Q.ok||!W.success)throw new Error(W.error||"Failed to trigger recapture");console.log("Recapture queued:",W),f(W.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(U){console.error("Error saving scenarios:",U),m(`Error: ${U instanceof Error?U.message:String(U)}`)}finally{h(!1)}},[t,r.id,w]),j=ie(q=>{},[]),A=ie(async(q,Y)=>{var D;const U=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:q,existingScenarios:t.scenarios,scenariosDataStructure:(D=t.metadata)==null?void 0:D.scenariosDataStructure,editingMockName:r.name,editingMockData:Y==null?void 0:Y.data})}),H=await U.json();if(!U.ok||!H.success)throw new Error(H.error||"Failed to generate scenario data");return H.data},[t,r.name]),T=ie(async()=>{var q;if(!r.id){N("Cannot delete scenario without ID");return}g(!0),N(null);try{const Y=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((q=r.metadata)==null?void 0:q.screenshotPaths)||[]})}),U=await Y.json();if(!Y.ok||!U.success)throw new Error(U.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(Y){console.error("[EditScenario] Error deleting scenario:",Y),N(Y instanceof Error?Y.message:"Failed to delete scenario"),v(!1)}finally{g(!1)}},[r.id,(R=r.metadata)==null?void 0:R.screenshotPaths,a,i]);return l("div",{className:"h-screen bg-gray-50 flex flex-col",children:[l("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:l(de,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",($=t.entity)==null?void 0:$.name]})}),l("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[l("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(om,{currentScenario:r,defaultScenario:s,dataStructure:((J=t.metadata)==null?void 0:J.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:I,onNavigate:j,iframeRef:c,onGenerateData:A,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(de,{to:`/entity/${a}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),l("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?l("div",{className:"space-y-3",children:[l("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void T(),disabled:y,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:y?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>v(!1),disabled:y,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>v(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),b&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(qr,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:w,isStarting:E,isLoading:C,showIframe:S,iframeKey:k,onIframeLoad:P,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const dm=He(function(){return n(Vr,{children:n(cm,{})})}),um=Object.freeze(Object.defineProperty({__proto__:null,default:dm,loader:lm,meta:im},Symbol.toStringTag,{value:"Module"}));function hm(e){return zn.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function mm(e){const t=e.match(/^(GET|POST|PUT|DELETE|PATCH)\s+(\/\S+)$/);return t?{method:t[1],pathPattern:t[2]}:{method:null,pathPattern:e}}function pm(e){const t=[],r=e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,a)=>(t.push(a),"([^/]+)"));return{regex:new RegExp(`^${r}$`),paramNames:t}}function fm(e,t){if(t.includes(e))return e;const r=e.lastIndexOf("/");if(r>0){const s=e.substring(0,r);if(t.includes(s))return s}return null}function gm(){let e=[],t={},r=null,s=null,a=!1,o=null;function i(h){const u=[],m=h.routes;if(m&&typeof m=="object")for(const[p,f]of Object.entries(m)){const{method:y,pathPattern:g}=mm(p),{regex:x,paramNames:v}=pm(g),b=typeof f=="object"&&f!==null?f:{body:f};u.push({method:y,pathPattern:g,pathRegex:x,paramNames:v,response:{body:b.body,status:typeof b.status=="number"?b.status:200}})}return u}function c(h){const u=h.state;if(u&&typeof u=="object"){a=!0,t={};for(const[m,p]of Object.entries(u))t[m]=Array.isArray(p)?JSON.parse(JSON.stringify(p)):[];r=JSON.stringify(u)}else a=!1,t={},r=null}return{loadScenario(h){const u=hm(h);s&&u===s||(s=u,o=h,e=i(h),c(h))},matchRequest(h,u,m){if(!o&&e.length===0&&!a)return null;const p=Object.keys(t);if(a){const y=fm(u,p);if(y&&h==="GET"&&y===u)return{body:t[y],status:200};if(y){const g=d(h,u);if(h==="POST"&&y===u&&g){const x=t[y],v=typeof m=="object"&&m!==null?{...m}:{};if(!("id"in v)){const b=x.reduce((N,w)=>{const E=typeof w.id=="number"?w.id:0;return Math.max(N,E)},0);v.id=b+1}return x.push(v),{body:v,status:g.response.status}}if(h==="DELETE"&&g&&g.params){const x=g.params.id,v=t[y],b=v.findIndex(N=>String(N.id)===String(x));return b===-1?{body:{error:"Not found"},status:404}:(v.splice(b,1),{body:null,status:g.response.status})}if(h==="PUT"&&g&&g.params){const x=g.params.id,v=t[y],b=v.findIndex(w=>String(w.id)===String(x));if(b===-1)return{body:{error:"Not found"},status:404};const N=typeof m=="object"&&m!==null?{...m}:v[b];return v[b]=N,{body:N,status:g.response.status}}}}const f=d(h,u);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(o&&h==="GET"){const y=u.match(/^\/api\/(.+)$/);if(y){const g=y[1];if(g in o&&g!=="routes"&&g!=="state")return{body:o[g],status:200}}}return null},resetState(){if(r){const h=JSON.parse(r);t={};for(const[u,m]of Object.entries(h))t[u]=Array.isArray(m)?JSON.parse(JSON.stringify(m)):[]}},getState(){return{...t}}};function d(h,u){for(const m of e)if(m.method!==null&&m.method===h&&m.paramNames.length===0&&m.pathRegex.exec(u))return{response:m.response};if(h==="GET"){for(const m of e)if(m.method===null&&m.paramNames.length===0&&m.pathRegex.exec(u))return{response:m.response}}for(const m of e)if(m.paramNames.length>0){if((m.method??"GET")!==h)continue;const f=m.pathRegex.exec(u);if(f){const y={};for(let g=0;g<m.paramNames.length;g++)y[m.paramNames[g]]=f[g+1];return{response:m.response,params:y}}}return null}}const Li="__codeyam_editor_proxy__",ym=500;let vt={data:null,timestamp:0};const uo=10*1024*1024;function Oi(){return globalThis[Li]??null}function Fi(e){globalThis[Li]=e}function zi(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=gm()),globalThis[e]}function Bi(){const e=Oi();return e?`http://localhost:${e.port}`:null}function xm(){const e=Date.now();if(vt.data!==null&&e-vt.timestamp<ym)return vt.data;const t=ge()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=Z.join(t,".codeyam","active-scenario.json");try{if(!Se.existsSync(r))return vt={data:null,timestamp:e},null;const a=JSON.parse(Se.readFileSync(r,"utf-8")).scenarioId;if(!a)return vt={data:null,timestamp:e},null;const o=Z.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!Se.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),vt={data:null,timestamp:e},null;const i=JSON.parse(Se.readFileSync(o,"utf-8"));return vt={data:i,timestamp:e},zi().loadScenario(i),i}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),vt={data:null,timestamp:e},null}}function bm(e){return new Promise(t=>{const r=[];let s=0;e.on("data",a=>{s+=a.length,s>uo?(t(null),e.resume()):r.push(a)}),e.on("end",()=>{s>uo||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function ho(e,t,r,s){const a=new URL(r),o={...e.headers,host:`${a.hostname}:${a.port}`};s&&(o["content-length"]=String(s.length));const i={hostname:a.hostname,port:a.port,path:e.url,method:e.method,headers:o},c=ea.request(i,d=>{t.writeHead(d.statusCode||200,d.headers),d.pipe(t,{end:!0})});c.on("error",d=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${d.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),s&&s.length>0?c.end(s):c.end()}function vm(e,t,r){const s=new URL(r),a={hostname:s.hostname,port:s.port,path:e.url,method:e.method,headers:{...e.headers,host:`${s.hostname}:${s.port}`}},o=ea.request(a,i=>{t.writeHead(i.statusCode||200,i.headers),i.pipe(t,{end:!0})});o.on("error",i=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${i.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(o,{end:!0})}function wm(e,t,r,s){const a=new URL(s),o=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${a.hostname}:${o}`);const i=zc.connect(o,a.hostname,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
150
+ `,d=Object.entries(e.headers).filter(([,h])=>h!=null).map(([h,u])=>`${h}: ${Array.isArray(u)?u.join(", "):u}`).join(`\r
151
+ `);i.write(c+d+`\r
152
+ \r
153
+ `),r.length>0&&i.write(r),i.pipe(t,{end:!0}),t.pipe(i,{end:!0})});i.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{i.destroy()})}function Nm(e,t){const r=ge()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=Z.join(r,".codeyam","proxy-config.json");try{Se.mkdirSync(Z.dirname(s),{recursive:!0}),Se.writeFileSync(s,JSON.stringify({proxyUrl:`http://localhost:${e}`,devServerUrl:t}),"utf-8"),console.log(`[editorProxy] Wrote proxy config to ${s}`)}catch(a){console.warn("[editorProxy] Failed to write proxy-config.json:",a)}}function Cm(){const e=ge()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=Z.join(e,".codeyam","proxy-config.json");try{Se.existsSync(t)&&Se.unlinkSync(t)}catch{}}async function Yi(e){await Ui();const{targetUrl:t}=e;let r=e.port;console.log(`[editorProxy] Starting proxy (requested port ${r}, target ${t})`);const s=zi(),a=ea.createServer((i,c)=>{(async()=>{const h=new URL(i.url||"/",`http://localhost:${r}`).pathname,u=i.method||"GET";if(u==="OPTIONS"){c.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}),c.end();return}if(xm(),u==="POST"||u==="PUT"||u==="DELETE"||u==="PATCH"){const f=await bm(i);if(f===null){ho(i,c,t,null);return}let y;if(f.length>0)try{y=JSON.parse(f.toString("utf-8"))}catch{}const g=s.matchRequest(u,h,y);if(g){console.log(`[editorProxy] Intercepted ${u} ${h} → mock response (status ${g.status})`),c.writeHead(g.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),c.end(g.body!=null?JSON.stringify(g.body):"");return}ho(i,c,t,f);return}const p=s.matchRequest(u,h);if(p){console.log(`[editorProxy] Intercepted ${u} ${h} → mock response (status ${p.status})`),c.writeHead(p.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data"}),c.end(p.body!=null?JSON.stringify(p.body):"");return}vm(i,c,t)})()});a.on("upgrade",(i,c,d)=>{wm(i,c,d,t)});const o=10;for(let i=0;i<o;i++){const c=r+i;try{return await new Promise((h,u)=>{a.once("error",u),a.listen(c,"0.0.0.0",()=>{a.removeListener("error",u),h()})}),r=c,Fi({server:a,port:r,targetUrl:t}),Nm(r,t),console.log(`[editorProxy] Proxy started on port ${r}, forwarding to ${t}`),{port:r}}catch(d){if((d==null?void 0:d.code)==="EADDRINUSE"&&i<o-1){console.log(`[editorProxy] Port ${c} in use, trying ${c+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",d),null}}return null}async function Ui(){const e=Oi();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),Cm(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Fi(null),setTimeout(t,2e3)})}function Wi(){vt={data:null,timestamp:0}}async function Hi(){const e=Bi();if(e)return console.log(`[editorProxy] Proxy already running at ${e}`),e;const t=globalThis.__codeyam_editor_dev_server__;if(!t||t.status!=="running"||!t.url)return console.log("[editorProxy] Cannot start proxy — dev server not running"),null;const r=parseInt(process.env.CODEYAM_PORT||"3111",10);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${r+1}, target ${t.url})`);const s=await Yi({port:r+1,targetUrl:t.url});if(s){const a=`http://localhost:${s.port}`;return console.log(`[editorProxy] On-demand proxy started at ${a}`),a}return console.error("[editorProxy] Failed to start on-demand proxy"),null}function Ji(e){const t=[];for(const r of e.split(`
154
+ `))r.includes("[JournalCapture] Page console.error:")?t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,"")):r.includes("[JournalCapture] Network failed:")&&t.push(r.replace(/.*\[JournalCapture\] /,""));return t}async function Vi(e,t,r,s){const a=O.join(e,".codeyam","editor-scenarios","client-errors.json");let o={};try{const i=await Ne.readFile(a,"utf8");o=JSON.parse(i)}catch{}o[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await Ne.mkdir(O.dirname(a),{recursive:!0}),await Ne.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function Sm(e){const t=O.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await Ne.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function ua(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function Gt(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function Os(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function qi(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}async function km(e,t,r){const s=O.join(e,".codeyam","journal"),a=O.join(s,"index.json");O.join(s,"screenshots");let o;try{const c=await Ne.readFile(a,"utf8");o=JSON.parse(c)}catch{return}let i=!1;for(const c of o.entries)if(!c.commitSha&&c.scenarioScreenshots)for(let d=0;d<c.scenarioScreenshots.length;d++){const h=c.scenarioScreenshots[d];if(h.name!==t)continue;const u=O.join(s,h.path);try{await Ne.copyFile(r,u),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${c.title}"`)}catch(m){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${m instanceof Error?m.message:m}`)}}i&&Nt.notifyChange("journal")}function Em(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function Am(e){const t=O.dirname(new URL(import.meta.url).pathname);let r=t;for(let a=0;a<5;a++){const o=O.dirname(r);if(O.basename(o)==="webserver"||O.basename(r)==="webserver"){r=O.basename(r)==="webserver"?r:o;break}r=o}const s=[O.join(r,"scripts","journalCapture.ts"),O.join(r,"app","lib","journalCapture.ts"),O.join(e,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),O.resolve(t,"..","lib","journalCapture.ts")];for(const a of s)try{return await Ne.access(a),a}catch{}return console.warn(`[editor-register-scenario] journalCapture.ts not found in any of: ${s.join(", ")}`),s[0]}function Pm(e,t,r){return new Promise(s=>{const a=St("npx",["tsx",e,t],{cwd:r,env:{...process.env}});let o="",i="";a.stdout.on("data",c=>{o+=c.toString()}),a.stderr.on("data",c=>{i+=c.toString()}),a.on("close",c=>{s(c===0?{success:!0,output:o}:{success:!1,output:o,error:i||`Process exited with code ${c}`})}),a.on("error",c=>{s({success:!1,output:"",error:c.message})})})}async function _m({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{name:r,description:s,componentName:a,componentPath:o}=t;if(!r)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await $e();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:c}=await Ie(i),d=Te(),h=Qs();try{await d.schema.alterTable("editor_scenarios").addColumn("url","varchar").execute()}catch{}await d.insertInto("editor_scenarios").values({id:h,project_id:c.id,name:r,description:s||null,component_name:a||null,component_path:o||null,url:t.url||null}).execute();const u=process.env.CODEYAM_ROOT_PATH||process.cwd();if(t.mockData){const b=O.join(u,".codeyam","editor-scenarios");await Ne.mkdir(b,{recursive:!0}),await Ne.writeFile(O.join(b,`${h}.json`),JSON.stringify(t.mockData,null,2))}Nt.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${r}" (id: ${h})`);const m=t.url&&t.url.startsWith("/"),p=!t.url||m?await Hi():null,f=Em(),y=qi(t.url||null,p,f);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${t.url||"none"}, isPath=${m}, proxy=${p||"none"}, devServer=${f||"none"} → using ${y||"none"}`);let g=null,x=null,v=[];if(y){const b=Gt(r),N=O.join(u,".codeyam","active-scenario.json");await Ne.writeFile(N,JSON.stringify({scenarioId:h,scenarioSlug:b,timestamp:new Date().toISOString()})),Wi(),console.log(`[editor-register-scenario] Active scenario set to "${b}" (${h}), cache invalidated`),await new Promise(j=>setTimeout(j,500));const w=O.join(u,".codeyam","editor-scenarios","screenshots");await Ne.mkdir(w,{recursive:!0});const E=O.join(w,`${h}.png`),C=await Am(u);console.log(`[editor-register-scenario] Capture script: ${C}`);const S=JSON.stringify({url:y,outputPath:E,viewportWidth:1280,viewportHeight:720,...a?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Running Playwright capture: url=${y}, output=${E}`);const k=Date.now(),P=await Pm(C,S,u),I=Date.now()-k;if(console.log(`[editor-register-scenario] Capture ${P.success?"succeeded":"FAILED"} in ${I}ms`),P.success||(console.warn(`[editor-register-scenario] Capture stdout: ${P.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(P.error||"").slice(0,500)}`)),v=Ji(P.output),await Vi(u,h,r,v),v.length>0&&console.warn(`[editor-register-scenario] ${v.length} client-side error(s) detected:`,v),P.success){g=`screenshots/${h}.png`;try{await d.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await d.updateTable("editor_scenarios").set({screenshot_path:g}).where("id","=",h).execute(),Nt.notifyChange("scenario"),await km(u,r,E)}else x=P.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${x}`)}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");return console.log(`[editor-register-scenario] Done: scenario="${r}", screenshot=${g?"captured":"skipped"}`),new Response(JSON.stringify({success:!0,scenario:{id:h,name:r,description:s,componentName:a||null,componentPath:o||null,screenshotPath:g,url:t.url||null},screenshotCaptured:g!==null,captureError:x,clientErrors:v}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-register-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Mm=Object.freeze(Object.defineProperty({__proto__:null,action:_m},Symbol.toStringTag,{value:"Module"}));function jm({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=ie(i=>t.some(c=>c.flowId===i),[t]),o=ie(i=>{a(i.id)?r(t.filter(c=>c.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,a]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const c=a(i.id),d=i.usedInScenarios.length>0;return l("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[l("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:c,onChange:()=>o(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),c&&i.requiredValues.length>0&&l("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((h,u)=>l("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:h.attributePath})," ",n("span",{className:"text-gray-400",children:h.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:h.value})]},u))})]})]},i.id)})})}function ha(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),s=new Map;r.forEach(d=>{s.set(d.id,d)});const a=[];t.forEach(d=>{var u;const h=((u=d.metadata)==null?void 0:u.coveredFlows)||[];h.forEach(m=>{const p=s.get(m);p&&p.usedInScenarios.push({id:d.id||"",name:d.name})}),a.push({scenario:d,coveredFlowIds:h})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,c=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:c,scenariosWithFlows:a}}function Tm(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const $m=({data:e})=>[{title:e!=null&&e.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function Rm({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Dr(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const a=(i=s.scenarios)==null?void 0:i.find(c=>c.name===Rr);if(!a)throw new Response("Default scenario not found",{status:404});const o=await $e();return G({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function Im(){var U;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=qe(),o=Ct(),{iframeRef:i}=da(),[c,d]=_(""),[h,u]=_(400),[m,p]=_(!1),[f,y]=_(!1),[g,x]=_(!1),[v,b]=_(null),[N,w]=_(null),[E,C]=_([]),S=re(()=>{var D;return!((D=e==null?void 0:e.metadata)!=null&&D.executionFlows)||!(e!=null&&e.scenarios)?[]:ha(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:k,isStarting:P,isLoading:I,showIframe:j,iframeKey:A,onIframeLoad:T}=sn({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:a,enabled:!0}),R=ie(async()=>{var H,D,M,Q;if(!c.trim()&&E.length===0){b("Please describe how you want to change the scenario or select execution flows");return}y(!0),b(null),w("Generating scenario with AI...");try{const W=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:c,existingScenarios:e.scenarios,scenariosDataStructure:(H=e.metadata)==null?void 0:H.scenariosDataStructure,flowSelections:E.length>0?E:void 0})}),F=await W.json();if(!W.ok||!F.success)throw new Error(F.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",F.data);const te=F.data;if(!te.name||!te.data)throw new Error("AI response missing required fields (name or data)");w("Saving new scenario..."),x(!0);const z={name:te.name,description:te.description||c,metadata:{data:te.data,interactiveExamplePath:(D=t.metadata)==null?void 0:D.interactiveExamplePath}},L=[...e.scenarios||[],z],V=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:L})}),B=await V.json();if(!V.ok||!B.success)throw new Error(B.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",B);const X=(Q=(M=B.analysis)==null?void 0:M.scenarios)==null?void 0:Q.find(ce=>ce.name===te.name);if(!(X!=null&&X.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),w("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(k){w("Capturing screenshot...");const ce=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:k,scenarioId:X.id,projectId:e.projectId,viewportWidth:1440})}),we=await ce.json();!ce.ok||!we.success?(console.error("[CreateScenario] Capture failed:",we),w("Scenario created! (Screenshot capture failed)")):w("Scenario created and captured!")}else w("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${X.id}`)},1e3)}catch(W){console.error("[CreateScenario] Error:",W),b(W instanceof Error?W.message:String(W)),w(null)}finally{y(!1),x(!1)}},[c,E,e,t,s,k,o]),$=f||g,J=ie(()=>{p(!0)},[]),q=ie(H=>{if(!m)return;const D=H.clientX;D>=250&&D<=600&&u(D)},[m]),Y=ie(()=>{p(!1)},[]);return ee(()=>(m?(document.addEventListener("mousemove",q),document.addEventListener("mouseup",Y)):(document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",Y)),()=>{document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",Y)}),[m,q,Y]),l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void o(`/entity/${s}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),l("div",{className:"flex items-end gap-8 shrink-0",children:[n(de,{to:`/entity/${s}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:l("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((U=e==null?void 0:e.scenarios)==null?void 0:U.length)||0})]})}),n(de,{to:`/entity/${s}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(de,{to:`/entity/${s}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(de,{to:`/entity/${s}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(de,{to:`/entity/${s}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[l("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${h}px`},children:[l("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),S.length>0&&l("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[l("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",E.length>0&&l("span",{className:"text-blue-600",children:["(",E.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(jm,{executionFlows:S,selections:E,onChange:C,disabled:$})})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:c,onChange:H=>d(H.target.value),placeholder:"e.g., Show an empty state with no items...",className:"w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:$})]}),l("div",{className:"space-y-2",children:[n("button",{onClick:()=>void R(),disabled:$||!c.trim()&&E.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:$?"Creating...":"Create Scenario"}),N&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:N}),v&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:v})]})]}),l("div",{onMouseDown:J,style:{width:"20px",position:"absolute",top:0,left:`${h-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:m?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
155
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
156
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
157
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
158
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
159
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(qr,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:k,isStarting:P,isLoading:I,showIframe:j,iframeKey:A,onIframeLoad:T,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const Dm=He(function(){return n(Vr,{children:n(Im,{})})}),Lm=Object.freeze(Object.defineProperty({__proto__:null,default:Dm,loader:Rm,meta:$m},Symbol.toStringTag,{value:"Module"}));function Om(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function Fm({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,url:s,viewportWidth:a,viewportHeight:o}=t;if(!r)return new Response(JSON.stringify({error:"scenarioId is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await $e();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:c}=await Ie(i),d=Te(),h=await d.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",c.id).executeTakeFirst();if(!h)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const u=s??h.url??null,m=u&&u.startsWith("/"),p=!u||m?await Hi():null,f=Om(),y=qi(u,p,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${h.url||"none"}, proxy=${p||"none"}, devServer=${f||"none"} → captureUrl=${y||"none"}`),!y)return new Response(JSON.stringify({error:"Cannot determine capture URL — no proxy or dev server running"}),{status:400,headers:{"Content-Type":"application/json"}});console.log(`[editor-capture-scenario] Starting capture for scenario "${h.name}" (id: ${r}), url: ${y}`);const g=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=Gt(h.name),v=O.join(g,".codeyam","active-scenario.json");await Ne.writeFile(v,JSON.stringify({scenarioId:r,scenarioSlug:x,timestamp:new Date().toISOString()})),Wi(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise(R=>setTimeout(R,500));const b=O.join(g,".codeyam","editor-scenarios","screenshots");await Ne.mkdir(b,{recursive:!0});const N=O.join(b,`${r}.png`),w=O.dirname(new URL(import.meta.url).pathname);let E=w;for(let R=0;R<5;R++){const $=O.dirname(E);if(O.basename($)==="webserver"||O.basename(E)==="webserver"){E=O.basename(E)==="webserver"?E:$;break}E=$}const C=[O.join(E,"scripts","journalCapture.ts"),O.join(E,"app","lib","journalCapture.ts"),O.join(g,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),O.resolve(w,"..","lib","journalCapture.ts")];let S="";for(const R of C)try{await Ne.access(R),S=R;break}catch{}S||(console.warn(`[editor-capture-scenario] journalCapture.ts not found in any of: ${C.join(", ")}`),S=C[0]),console.log(`[editor-capture-scenario] Capture script: ${S}`);const k=JSON.stringify({url:y,outputPath:N,viewportWidth:a||1280,viewportHeight:o||720,...h.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Running Playwright capture: url=${y}, output=${N}`);const P=Date.now(),I=await new Promise(R=>{const $=St("npx",["tsx",S,k],{cwd:g,env:{...process.env}});let J="",q="";$.stdout.on("data",Y=>{J+=Y.toString()}),$.stderr.on("data",Y=>{q+=Y.toString()}),$.on("close",Y=>{R(Y===0?{success:!0,output:J}:{success:!1,output:J,error:q||`Process exited with code ${Y}`})}),$.on("error",Y=>{R({success:!1,output:"",error:Y.message})})}),j=Date.now()-P;if(console.log(`[editor-capture-scenario] Capture ${I.success?"succeeded":"FAILED"} in ${j}ms`),!I.success)return console.warn(`[editor-capture-scenario] Capture stdout: ${I.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(I.error||"").slice(0,500)}`),new Response(JSON.stringify({error:"Failed to capture screenshot",details:I.error}),{status:500,headers:{"Content-Type":"application/json"}});const A=`screenshots/${r}.png`;try{await d.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}await d.updateTable("editor_scenarios").set({screenshot_path:A}).where("id","=",r).execute();const T=Ji(I.output);return await Vi(g,r,h.name,T),T.length>0&&console.warn(`[editor-capture-scenario] ${T.length} client-side error(s) detected:`,T),Nt.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:A,clientErrors:T}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-capture-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const zm=Object.freeze(Object.defineProperty({__proto__:null,action:Fm},Symbol.toStringTag,{value:"Module"}));async function Bm({params:e}){const t=e["*"];if(!t)return new Response("Image path is required",{status:400});const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=Z.join(r,".codeyam","editor-scenarios","screenshots",t),a=Z.resolve(s),o=Z.resolve(Z.join(r,".codeyam","editor-scenarios","screenshots"));if(!a.startsWith(o))return new Response("Invalid path",{status:403});try{await be.access(s);const i=await be.readFile(s),c=Z.extname(s).toLowerCase(),d=c===".png"?"image/png":c===".jpg"||c===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Image not found",{status:404})}}const Ym=Object.freeze(Object.defineProperty({__proto__:null,loader:Bm},Symbol.toStringTag,{value:"Module"}));async function Um({params:e,request:t}){const r=e["*"];if(!r)return new Response("Image path is required",{status:400});const s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=Z.join(s,".codeyam","journal","screenshots",r),o=Z.resolve(a),i=Z.resolve(Z.join(s,".codeyam","journal","screenshots"));if(!o.startsWith(i))return new Response("Invalid path",{status:403});try{const c=await be.stat(a),d=`"${c.mtimeMs.toString(36)}-${c.size.toString(36)}"`;if(t.headers.get("if-none-match")===d)return new Response(null,{status:304,headers:{ETag:d}});const u=await be.readFile(a),m=Z.extname(a).toLowerCase(),p=m===".png"?"image/png":m===".jpg"||m===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":p,"Cache-Control":"public, max-age=0, must-revalidate",ETag:d}})}catch{return new Response("Image not found",{status:404})}}const Wm=Object.freeze(Object.defineProperty({__proto__:null,loader:Um},Symbol.toStringTag,{value:"Module"})),Gi=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function Ki(e){const t=JSON.stringify({type:"refresh-preview",...e});let r=0;for(const s of Gi)try{s.ws.readyState===Xo.OPEN&&(s.ws.send(t),r++)}catch{}return r}function Hm(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of Gi)try{r.ws.readyState===Xo.OPEN&&(r.ws.send(e),t++)}catch{}return t}const Jm=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:Hm,broadcastPreviewRefresh:Ki},Symbol.toStringTag,{value:"Module"}));async function Vm({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const a=ge()||process.cwd(),o=Z.join(a,".codeyam"),i=Z.join(o,"active-scenario.json");Se.mkdirSync(o,{recursive:!0}),Se.writeFileSync(i,JSON.stringify({scenarioSlug:r,scenarioId:s||null,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));const c=Ki();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:c}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const qm=Object.freeze(Object.defineProperty({__proto__:null,action:Vm},Symbol.toStringTag,{value:"Module"}));var me;(e=>{(t=>{t.OPENAI_GPT5_1="openai/gpt-5.1",t.OPENAI_GPT5="openai/gpt-5",t.OPENAI_GPT5_MINI="openai/gpt-5-mini",t.OPENAI_GPT5_NANO="openai/gpt-5-nano",t.OPENAI_GPT4_1="openai/gpt-4.1",t.OPENAI_GPT4_1_MINI="openai/gpt-4.1-mini",t.OPENAI_GPT4_O="openai/gpt-4o",t.OPENAI_GPT4_O_MINI="openai/gpt-4o-mini",t.OPENAI_GPT_OSS_120B_GROQ="openai/gpt-oss-120b-groq",t.OPENAI_GPT_OSS_120B_DEEPINFRA="openai/gpt-oss-120b-deepinfra",t.QWEN3_235B_INSTRUCT_DEEPINFRA="qwen/qwen3-235b-instruct-deepinfra",t.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA="qwen/qwen3-coder-480b-instruct-deepinfra",t.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA="google/gemini-2.5-pro-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA="google/gemini-2.5-flash-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER="google/gemini-2.5-flash-lite-openrouter",t.META_LLAMA_4_MAVERICK_OPENROUTER="meta-llama/llama-4-maverick-openrouter",t.DEEPSEEK_V3_1_TERMINUS_OPENROUTER="deepseek/v3.1-terminus-openrouter",t.ANTHROPIC_CLAUDE_4_5_HAIKU="anthropic/claude-4.5-haiku",t.ANTHROPIC_CLAUDE_4_5_SONNET="anthropic/claude-4.5-sonnet",t.ANTHROPIC_CLAUDE_4_5_OPUS="anthropic/claude-4.5-opus",t.PHIND_CODELLAMA="phind/codellama",t.GOOGLE_GEMINI_PRO="google/gemini-pro",t.GOOGLE_PALM_2_CODE_CHAT_32K="google/palm-2-code-chat-32k",t.META_CODELLAMA_34B_INSTRUCT="meta-llama/codellama-34b-instruct",t.OPENAI_GPT4_PREVIEW="openai/gpt-4-preview"})(e.Model||(e.Model={}))})(me||(me={}));function Qi(e,t){return e?Object.values(me.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Zi=Qi(process.env.DEFAULT_SMALLER_MODEL,me.Model.OPENAI_GPT4_1_MINI),Gm=Qi(process.env.DEFAULT_LARGER_MODEL,me.Model.OPENAI_GPT4_1),ct={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},bs={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Km={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},vs={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},Mt={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Qm={[me.Model.OPENAI_GPT5_1]:{id:me.Model.OPENAI_GPT5_1,provider:ct,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[me.Model.OPENAI_GPT5]:{id:me.Model.OPENAI_GPT5,provider:ct,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[me.Model.OPENAI_GPT5_MINI]:{id:me.Model.OPENAI_GPT5_MINI,provider:ct,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[me.Model.OPENAI_GPT5_NANO]:{id:me.Model.OPENAI_GPT5_NANO,provider:ct,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[me.Model.OPENAI_GPT4_1]:{id:me.Model.OPENAI_GPT4_1,provider:ct,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[me.Model.OPENAI_GPT4_1_MINI]:{id:me.Model.OPENAI_GPT4_1_MINI,provider:ct,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[me.Model.OPENAI_GPT4_O]:{id:me.Model.OPENAI_GPT4_O,provider:ct,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[me.Model.OPENAI_GPT4_O_MINI]:{id:me.Model.OPENAI_GPT4_O_MINI,provider:ct,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[me.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:me.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:bs,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[me.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:me.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:bs,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[me.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:me.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:bs,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[me.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:me.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Km,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[me.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:me.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:Mt,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[me.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:me.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:Mt,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[me.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:me.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:Mt,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[me.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:me.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:Mt,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[me.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:me.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:Mt,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[me.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:me.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:vs,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[me.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:me.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:vs,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[me.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:me.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:vs,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[me.Model.PHIND_CODELLAMA]:{id:me.Model.PHIND_CODELLAMA,provider:ct,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[me.Model.GOOGLE_GEMINI_PRO]:{id:me.Model.GOOGLE_GEMINI_PRO,provider:Mt,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[me.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:me.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:Mt,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[me.Model.META_CODELLAMA_34B_INSTRUCT]:{id:me.Model.META_CODELLAMA_34B_INSTRUCT,provider:Mt,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[me.Model.OPENAI_GPT4_PREVIEW]:{id:me.Model.OPENAI_GPT4_PREVIEW,provider:ct,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Gr(e){const t=Qm[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Zm(e){return Gr(e).maxCompletionTokens}function Xm(e){return Gr(e).pricing}const mo=1e6;function ep({model:e,usage:t}){const r=Xm(e);return r?t.prompt_tokens*(r.input/mo)+t.completion_tokens*(r.output/mo):null}function tp({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const s=t.usage||{prompt_tokens:0,completion_tokens:0},a=ep({model:r,usage:s});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,cost:a?Math.round(a*1e5)/1e5:void 0}}function np({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??Zi,i=Gr(o);Zm(o);const c=[];return e&&c.push({role:"system",content:e}),c.push({role:"user",content:[{type:"text",text:t}]}),{messages:c,model:i.apiModelName,response_format:s==="json_schema"&&a?{type:"json_schema",json_schema:{name:a.name,schema:a.schema,strict:a.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const Fs="/tmp/codeyam-e2e-tracking";let ws,Ns;function rp(){return ws===void 0&&(ws=process.env.CODEYAM_E2E_TRACK_DATA==="true"),ws}function sp(){return Ns===void 0&&(Ns=!process.env.CODEYAM_LLM_FIXTURES_DIR),Ns}function ap(){K.existsSync(Fs)||K.mkdirSync(Fs,{recursive:!0})}function op(e){const t=JSON.stringify(e,null,0);return Ic.createHash("md5").update(t).digest("hex")}function ip(e,t,r){return[e].join("_")+".json"}function Xi(e,t,r,s){if(!rp())return;ap();const a=ip(e),o=O.join(Fs,a),i=op(t);if(sp()){const c={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};K.writeFileSync(o,JSON.stringify(c,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(o)){const c=JSON.parse(K.readFileSync(o,"utf-8")),d={matches:i===c.dataHash,firstRunHash:c.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=zs(c.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${c.dataHash}`),console.log(` Second run hash: ${i}`);const h=o.replace(".json","_DIFF.json");K.writeFileSync(h,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:c.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${h}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function zs(e,t,r=""){const s=[];if(typeof e!=typeof t)return s.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),s;if(e===null||t===null)return e!==t&&s.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),s;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&s.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const a=Math.max(e.length,t.length);for(let o=0;o<a;o++)s.push(...zs(e[o],t[o],`${r}[${o}]`));return s}if(typeof e=="object"&&typeof t=="object"){const a=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...a,...o]));for(const c of i){const d=e[c],h=t[c];c in e?c in t?s.push(...zs(d,h,`${r?r+".":""}${c}`)):s.push(`${r?r+".":""}${c}: missing in second run`):s.push(`${r?r+".":""}${c}: missing in first run`)}return s}if(e!==t){const a=JSON.stringify(e),o=JSON.stringify(t);a.length<100&&o.length<100?s.push(`${r||"root"}: ${a} vs ${o}`):s.push(`${r||"root"}: values differ (${a.length} chars vs ${o.length} chars)`)}return s}Xs(Zs);const tr=new Yc({concurrency:100,timeout:1200*1e3,autoStart:!0}),po={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},jt={};async function Bs({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=Zi,attempts:i=0}){var S,k,P,I,j,A,T;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await lp(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${tr.size}, running=${tr.pending}]`);const c=Date.now();let d,h=0;const u=Gr(o),m=process.env[u.provider.apiKeyEnvVar];if(!m)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new Bc({apiKey:m,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:a?"json_schema":s?"json_object":"text",jsonSchema:a},y=np(f),g=await tr.add(()=>(d=Date.now(),Ka(async()=>{const R=Date.now(),$=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],J=setInterval(()=>{const q=Math.floor((Date.now()-R)/1e3),Y=Math.floor(q/10)%$.length;Za(1,`${$[Y]} [type=${e}, model=${o}, elapsed=${q}s]`)},1e4);try{return await p.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(J)}},{...po,onFailedAttempt:R=>{h++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:R,prompt:r,systemMessage:t,attempts:i,retryCount:h})}})));if(!g)throw new Error("Completion call returned no result");const x=g,v=Date.now(),b=tp({chatRequest:f,chatCompletion:x,model:o});if(!b)throw new Error("Failed to get LLM call stats");b.retries=h,b.wait_ms=d-c,b.duration_ms=v-c;const N=(S=x.choices)==null?void 0:S[0];let w=null;if(N){if(!N.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:x,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");w=(k=N.message)==null?void 0:k.content}let E=w;w&&(E=w.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const C=s?E&&(((P=E.match(/\{[\s\S]*\}/))==null?void 0:P[0])??E):E;if(!C){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:C,rawCompletion:w,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Bs({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(C.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:w,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(C)}catch(R){if(console.log("CodeYam Error: Invalid JSON in completion",{error:R.message,model:o,completion:C.substring(0,500),rawCompletion:w==null?void 0:w.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:R.message});const $=`Your previous response contained invalid JSON with the following error:
160
+
161
+ ${R.message}
162
+
163
+ Here was your previous response:
164
+ \`\`\`
165
+ ${C}
166
+ \`\`\`
167
+
168
+ Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,J=await tr.add(()=>Ka(async()=>{const D=Date.now(),M=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],Q=setInterval(()=>{const W=Math.floor((Date.now()-D)/1e3),F=Math.floor(W/10)%M.length;Za(1,`${M[F]} [type=${e}, model=${o}, elapsed=${W}s]`)},1e4);try{return await p.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:C},{role:"user",content:$}]},{timeout:300*1e3})}finally{clearInterval(Q)}},{...po,onFailedAttempt:D=>{console.log("CodeYam Error: Correction call failed",{error:D,attempts:i})}}));if(!J)throw new Error("Correction call returned no result");const q=J,Y=(A=(j=(I=q.choices)==null?void 0:I[0])==null?void 0:j.message)==null?void 0:A.content;let U=Y;Y&&(U=Y.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const H=U&&(((T=U.match(/\{[\s\S]*\}/))==null?void 0:T[0])??U);if(!H)throw new Error("Correction attempt returned empty completion");try{JSON.parse(H),console.log("CodeYam: JSON correction successful");const D=Date.now();return b.duration_ms=D-c,{finishReason:q.choices[0].finish_reason,completion:H,stats:b}}catch(D){return console.log("CodeYam Error: Corrected JSON still invalid",{error:D.message,correctedCompletion:H.substring(0,500)}),await Bs({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${R.message}`)}return Xi(`completionCall_${e}`,{completion:C,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:C,stats:b}}async function lp(e,t,r){var o,i,c,d,h;const s=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!s.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=s.readdirSync(t).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const m={};for(const b of u)try{const N=s.readFileSync(a.join(t,b),"utf-8"),w=JSON.parse(N);m[w.prompt_type]||(m[w.prompt_type]=[]),m[w.prompt_type].push(w)}catch(N){console.warn(`Failed to parse LLM fixture file ${b}:`,N)}for(const b of Object.keys(m))m[b].sort((N,w)=>{const E=N.created_at??0,C=w.created_at??0;return E-C});const p=m[e];if(!p||p.length===0){const b=Object.keys(m).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${b}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const b=r.match(/Scenario name must match exactly: "([^"]+)"/),N=b==null?void 0:b[1];if(N){const w={};for(const C of p)try{const k=((o=JSON.parse(C.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";w[k]||(w[k]=[]),w[k].push(C)}catch{}const E=w[N];if(E&&E.length>0){const C=`${t}::${e}::${N}`;jt[C]===void 0&&(jt[C]=0);const S=jt[C];jt[C]=(S+1)%E.length,f=E[S],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${N}' [${S+1}/${E.length}]`)}else{const C=Object.keys(w).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${N}'. Available: [${C}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${t}::${e}`;jt[b]===void 0&&(jt[b]=0);const N=jt[b];jt[b]=(N+1)%p.length,f=p[N],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${N+1}/${p.length}]`)}let g;try{g=((d=(c=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:c.message)==null?void 0:d.content)||f.response}catch{g=f.response}let x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const v=x&&(((h=x.match(/\{[\s\S]*\}/))==null?void 0:h[0])??x);return Xi(`completionCall_${e}`,{completion:v||"",finishReason:"stop"}),{finishReason:"stop",completion:v||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function fo(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function cp(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=Qs(),o=Date.now(),i={...r,id:a,created_at:o,props:s};let c;const d=`${i.object_id}_${a}.json`;if(process.env.DYNAMODB_PATH?c=O.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(c=O.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),c)try{const u=O.dirname(c);return await Ne.mkdir(u,{recursive:!0}),await Ne.writeFile(c,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${c}`),{id:a}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const h=fo();if(!h)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,m]of Object.entries(i))typeof m>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${u} with explicit value 'undefined'`);try{return await new Tr().send(new Uc({TableName:fo(),Item:Hc(i,{removeUndefinedValues:!0})})),{id:a}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${h}`,u),{id:"-1"}}}new Tr({});new Tr({});new Tr({});const dp=3,up=2,ma=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+dp*String(t).length*(1+up)});new ta(ma());new ta(ma());new ta(ma());class hp{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,s){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),s&&(this.byClassAndMethod.has(s)||this.byClassAndMethod.set(s,new Map),this.byClassAndMethod.get(s).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var s;return(s=this.byClassAndMethod.get(t))==null?void 0:s.get(r)}}class mp{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class pp{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class fp{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class gp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class yp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];if(s.addType(o,"function"),s.addEquivalence(o.withParameter(1),r.withElement("*")),a.args.length>1){const i=a.args[1];s.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class xp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.getLastFunctionCallSegment();a&&a.args.forEach(o=>{s.addEquivalence(t,o)}),s.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class bp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class vp{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>2)for(let o=2;o<a.args.length;o++){const i=a.args[o];s.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class wp{getReturnType(){return"number"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0)for(let o=0;o<a.args.length;o++)s.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class Np{getReturnType(){return"string"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class Cp{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Sp{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class kp{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Ep{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Ap{getReturnType(){return"object"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"array")}}isComplete(){return!0}}class Pp{getReturnType(){return"string[]"}addEquivalences(t,r,s){s.addType(r,"string"),s.addType(t,"string[]"),s.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class _p{getReturnType(){return"unknown"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r),s.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class Mp{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class jp{getReturnType(){return"array"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}function Tp(){const e=new hp;return e.register("filter",new mp,"Array"),e.register("map",new Cp,"Array"),e.register("flatMap",new Sp,"Array"),e.register("join",new Np,"Array"),e.register("find",new gp,"Array"),e.register("findLast",new Ep,"Array"),e.register("at",new kp,"Array"),e.register("reduce",new yp,"Array"),e.register("concat",new xp,"Array"),e.register("slice",new bp,"Array"),e.register("splice",new vp,"Array"),e.register("push",new wp,"Array"),e.register("some",new pp,"Array"),e.register("every",new fp,"Array"),e.register("fromEntries",new Ap,"Object"),e.register("split",new Pp,"String"),e.register("then",new _p,"Promise"),e.register("useState",new jp,"React"),e.register("useMemo",new Mp,"React"),e}Tp();new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));const $p=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Rp=new Set(["find","findLast","at","pop","shift"]),Ip=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Dp=new Set([...$p,...Rp,...Ip]),Lp=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Op=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Fp=new Set([...Lp,...Op]);[...Dp,...Fp];class zp{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,s)=>{const a=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";s?console.info(`${o}${a}${r}`,JSON.stringify(s)):console.info(`${o}${a}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new zp({enabled:!1});function Jt(e,t){const r={added:{},removed:{},changed:{}},s=new Set(Object.keys(e??{})),a=new Set(Object.keys(t??{}));for(const o of a)s.has(o)||(r.added[o]=t[o]);for(const o of s)a.has(o)||(r.removed[o]=e[o]);for(const o of s)a.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function Bp(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function nr(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let Yp=0;class pa{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++Yp,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,s){var d,h,u,m;if(!this.isEnabled())return;const a=this.traces.get(t);if(!a)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:o},c=a.stages[a.stages.length-1];if(c&&(i.diffFromPrevious={signatureSchema:Jt(c.data.signatureSchema,o.signatureSchema),returnValueSchema:Jt(c.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||c.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const p=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(c.data.dependencySchemas??{})]);for(const f of p){const y=(d=c.data.dependencySchemas)==null?void 0:d[f],g=(h=o.dependencySchemas)==null?void 0:h[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const v=`${f}::${x}`,b=(u=y==null?void 0:y[x])==null?void 0:u.returnValueSchema,N=(m=g==null?void 0:g[x])==null?void 0:m.returnValueSchema,w=Jt(b,N);Bp(w)&&(i.diffFromPrevious.dependencySchemas[v]=w)}}}a.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var a;const t={},r=new Map;for(const[o,i]of this.traces){let c=0;for(const d of i.stages){if(!d.diffFromPrevious)continue;const u=`${((a=i.stages[i.stages.indexOf(d)-1])==null?void 0:a.stage)??"start"}→${d.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),d.diffFromPrevious.signatureSchema){const m=d.diffFromPrevious.signatureSchema;t[u].added+=Object.keys(m.added).length,t[u].removed+=Object.keys(m.removed).length,t[u].changed+=Object.keys(m.changed).length,c+=nr(m)}if(d.diffFromPrevious.returnValueSchema){const m=d.diffFromPrevious.returnValueSchema;t[u].added+=Object.keys(m.added).length,t[u].removed+=Object.keys(m.removed).length,t[u].changed+=Object.keys(m.changed).length,c+=nr(m)}}r.set(o,c)}const s=[...r.entries()].sort((o,i)=>i[1]-o[1]).slice(0,10).map(([o])=>o);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(h=>`${h}(${this.traces.get(h).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:a}=this.computeFlushSummary(),o={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:a},c=O.dirname(this.outputPath);K.existsSync(c)||K.mkdirSync(c,{recursive:!0});const d=K.openSync(this.outputPath,"w");try{K.writeSync(d,`{
169
+ "meta": `),K.writeSync(d,JSON.stringify(o,null,2)),K.writeSync(d,`,
170
+ "summary": `),K.writeSync(d,JSON.stringify(i,null,2)),K.writeSync(d,`,
171
+ "entities": {`);let h=!0;for(const[u,m]of this.traces)h||K.writeSync(d,","),K.writeSync(d,`
172
+ ${JSON.stringify(u)}: `),K.writeSync(d,JSON.stringify(m,null,2)),h=!1;K.writeSync(d,`
173
+ }
174
+ }
175
+ `),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{K.closeSync(d)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=K.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new pa({enabled:!1});a.projectSlug=s.meta.projectSlug;for(const[o,i]of Object.entries(s.entities))a.traces.set(o,i);return a}getSummary(){var a,o,i;const t={},r=new Map;for(const[c,d]of this.traces){let h=0;for(let u=1;u<d.stages.length;u++){const m=d.stages[u],f=`${((a=d.stages[u-1])==null?void 0:a.stage)??"start"}→${m.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=m.diffFromPrevious)!=null&&o.signatureSchema){const y=m.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,h+=nr(y)}if((i=m.diffFromPrevious)!=null&&i.returnValueSchema){const y=m.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,h+=nr(y)}}r.set(c,h)}const s=[...r.entries()].sort((c,d)=>d[1]-c[1]).slice(0,10).map(([c,d])=>({name:c,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(a=>a.path&&r.test(a.path)):s.operations:[]}tracePath(t,r){var o,i;const s=this.traces.get(t),a=[];if(!s)return{entityName:t,path:r,history:a};for(const c of s.stages){const d=(o=c.data.signatureSchema)==null?void 0:o[r],h=(i=c.data.returnValueSchema)==null?void 0:i[r],u=d??h;u!==void 0&&a.push({stage:c.stage,value:u})}for(const c of s.operations)c.path===r&&a.push({operation:c.operation,stage:c.stage,value:c.after??c.before,context:c.context});return{entityName:t,path:r,history:a}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const a=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[c,d]of Object.entries(i.data.signatureSchema??{}))o.test(c)&&a.push({stage:i.stage,path:c,type:d,schemaType:"signature"});for(const[c,d]of Object.entries(i.data.returnValueSchema??{}))o.test(c)&&a.push({stage:i.stage,path:c,type:d,schemaType:"returnValue"});for(const[c,d]of Object.entries(i.data.dependencySchemas??{}))for(const[h,u]of Object.entries(d))for(const[m,p]of Object.entries(u.returnValueSchema??{}))o.test(m)&&a.push({stage:i.stage,path:`${c}/${h}::${m}`,type:p,schemaType:"dependency"})}return a}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){s=r.stages[d];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,h)=>{const u=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const m=u[1],p=u[2]==="[]";if(a.has(m))return;const f=m+(p?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:h})};for(const[,d]of Object.entries(s.data.dependencySchemas??{}))for(const[,h]of Object.entries(d))for(const[u,m]of Object.entries(h.returnValueSchema??{}))i(u,m);const c=[];for(const[d,h]of o)new Set(h.map(m=>m.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&c.push({propertyName:d,paths:h.map(m=>({...m,stage:s.stage}))});return c.sort((d,h)=>{const u=new Set(d.paths.map(p=>p.type)).size;return new Set(h.paths.map(p=>p.type)).size-u}),c}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(p=>p.stage===r),i=a.stages.find(p=>p.stage===s);if(!o||!i)return null;const c={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},h=i.data.returnValueSchema??{},u=new Set(Object.keys(d)),m=new Set(Object.keys(h));for(const p of m)u.has(p)?d[p]!==h[p]&&c.typeChanged.push({path:p,from:d[p],to:h[p]}):c.added.push(`${p}: ${h[p]}`);for(const p of u)m.has(p)||c.removed.push(`${p}: ${d[p]}`);return c}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const c=Jt(i,s);for(const[d,h]of Object.entries(c.added))this.operation(t,{operation:r,path:d,before:void 0,after:h,context:{...o,changeType:"added"}});for(const[d,h]of Object.entries(c.removed))this.operation(t,{operation:r,path:d,before:h,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:h,to:u}]of Object.entries(c.changed))this.operation(t,{operation:r,path:d,before:h,after:u,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=Jt(s,a);for(const[c,d]of Object.entries(i.added))this.operation(t,{operation:r,path:c,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[c,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:c,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:d,to:h}]of Object.entries(i.changed))this.operation(t,{operation:r,path:c,before:d,after:h,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,a,o="both"){if(!this.enabled){for(const i in s)for(const c in s[i]){const d=s[i][c];(o==="signature"||o==="both")&&d.signatureSchema&&a(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&a(d.returnValueSchema)}return}for(const i in s)for(const c in s[i]){const d=s[i][c],h={filePath:i,dependencyName:c};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,a,{...h,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,a,{...h,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,a){var i;if(!this.enabled){a();return}const o={};for(const c in s){o[c]={};for(const d in s[c]){const h=s[c][d];o[c][d]={sig:{...h.signatureSchema||{}},rv:{...h.returnValueSchema||{}}}}}a();for(const c in s)for(const d in s[c]){const h=s[c][d],u=(i=o[c])==null?void 0:i[d],m={filePath:c,dependencyName:d};if(h.signatureSchema){const p=(u==null?void 0:u.sig)||{},f=Jt(p,h.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...m,schemaType:"signature",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...m,schemaType:"signature",changeType:"changed"}})}if(h.returnValueSchema){const p=(u==null?void 0:u.rv)||{},f=Jt(p,h.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...m,schemaType:"returnValue",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...m,schemaType:"returnValue",changeType:"changed"}})}}}}function Up(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const go=new pa({enabled:Up(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{go.isEnabled()&&go.flush()});function el(e){if(e==null)return null;const t=e.match(/```json\s*([\s\S]*?)\s*```/);t&&(e=t[1]),e=e.replace(/"[^"]+"\s*:\s*undefined\s*,?\s*/g,""),e=e.replace(/,(\s*[}\]])/g,"$1");try{return Wc.parse(e)}catch(r){const a=r.message.match(/invalid character .* at (\d+):(\d+)/);if(a){const o=parseInt(a[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),el(e)}return null}}function Wp({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
176
+ User-selected Execution Flow Values:
177
+ The user has specifically requested these values be used in the scenario:
178
+ ${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
179
+ `)}
180
+
181
+ IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
182
+ `),`Mock Scenario Data Structure:
183
+ \`\`\`
184
+ ${JSON.stringify(r,null,2)}
185
+ \`\`\`
186
+ Existing Mock Scenario Data:
187
+ \`\`\`
188
+ ${JSON.stringify(t,null,2)}
189
+ \`\`\`
190
+ ${a}
191
+ New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
192
+ `}function Hp({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===Rr);return`Mock Scenario Data Structure:
193
+ \`\`\`
194
+ ${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
195
+ \`\`\`
196
+
197
+ Existing Mock Scenario Data:
198
+ \`\`\`
199
+ ${JSON.stringify(s.map(i=>({name:i.name,data:Mn(o.metadata.data,i.metadata.data)})),null,2)}
200
+ \`\`\`
201
+
202
+ Mock Scenario that should be edited: "${t}"
203
+ ${r?`The portion of the data that should be edited:
204
+ \`\`\`
205
+ ${JSON.stringify(r,null,2)}
206
+ \`\`\``:""}
207
+
208
+ How this data should be changed: "${e}"
209
+ `}async function Jp({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const c=t?Hp({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):Wp({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),d=await Bs({type:"guessScenarioDataFromDescription",systemMessage:t?qp(r):Vp,prompt:c,model:i??Gm});await cp({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...d.stats});const{completion:h}=d;return h?el(h):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Vp=`
210
+ You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
211
+
212
+ Your goal is to add one scenario to the list of existing scenarios by generating an english name, proper description, and a JSON data structure that describes the data that would be used in a scenario for the code.
213
+
214
+ The data for the scenario will be merged with the "Default Scenario" data, so you don't need to replicate any data in the default scenario but must overwrite any data that should be different.
215
+
216
+ You must respond with valid JSON following this format of this TS type definition:
217
+ \`\`\`
218
+ export type ScenarioData = {
219
+ name: string;
220
+ description: string;
221
+ data: {
222
+ mockData: { [key: string]: unknown };
223
+ argumentsData: { [key: string]: unknown };
224
+ };
225
+ };
226
+
227
+ \`\`\`
228
+ `,qp=e=>`
229
+ You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
230
+
231
+ Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
232
+ ${e?`
233
+ We only want to edit a specific portion of the data, which is provided in the "The portion of the data that should be edited" section. You should only change the data that is provided in this section.`:""}
234
+
235
+ Always return the complete data structure for the scenario, with both mockData and argumentsData, even if you only changed a small portion of the data.
236
+
237
+ You must respond with valid JSON following this type definition:
238
+ \`\`\`
239
+ {
240
+ data: {
241
+ mockData: { [key: string]: unknown };
242
+ argumentsData: { [key: string]: unknown };
243
+ }
244
+ }
245
+ \`\`\`
246
+ `;async function Gp({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:c}=t;if(!r&&(!c||c.length===0))return G({error:"Missing required field: description or flowSelections"},{status:400});const d=await Jp({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:c}),h=(d==null?void 0:d.data)||d;return G({success:!0,data:h})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),G({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Kp=Object.freeze(Object.defineProperty({__proto__:null,action:Gp},Symbol.toStringTag,{value:"Module"}));function Qp(e){const t=new Map;for(const r of[...e].reverse()){const s=t.get(r.date)||[];s.push(r),t.set(r.date,s)}return t}function Zp(e){const t=new Map;for(const r of e){const s=r.name.indexOf(" - "),a=s!==-1?r.name.slice(0,s):"App",o=t.get(a)||[];o.push(r),t.set(a,o)}return[...t.entries()].sort(([r],[s])=>r==="App"?-1:s==="App"?1:r.localeCompare(s))}function Xp(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function ef(e){const{title:t,timeStr:r,type:s,description:a,allScenarioNames:o,screenshot:i,scenarioScreenshots:c,commitSha:d,commitMessage:h}=e,u=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(o.length>0&&u.push(`**Scenarios:** ${o.join(", ")}`),u.push(""),u.push(a),i&&(u.push(""),u.push(`![${t}](${i})`)),c.length>0){u.push(""),u.push("**Scenario Screenshots:**");for(const m of c)u.push(""),u.push(`![${m.name}](${m.path})`)}return d&&h&&(u.push(""),u.push(`**Commit:** \`${d}\` — ${h}`)),u.push(""),u.join(`
247
+ `)}function tf(e,t){return e.findIndex(r=>r.time===t)}function nf(e,t){return t.commitSha!==void 0&&(e.commitSha=t.commitSha),t.commitMessage!==void 0&&(e.commitMessage=t.commitMessage),t.description!==void 0&&(e.description=t.description),t.scenarios!==void 0&&(e.scenarios=t.scenarios),t.scenarioScreenshots!==void 0&&(e.scenarioScreenshots=t.scenarioScreenshots),e}function rf(e,t,r,s){const a=`
248
+ **Commit:** \`${r}\` — ${s||"no message"}
249
+ `,o=`### ${t}`,i=e.lastIndexOf(o);if(i===-1)return null;const c=e.indexOf(`
250
+ ---
251
+ `,i+1),d=c!==-1?c:e.length;return e.slice(0,d)+a+e.slice(d)}async function sf(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await $e();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await Ie(t),a=await Te().selectFrom("editor_scenarios").select(["name","screenshot_path","id"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${a.length} matching scenarios:`,a.map(d=>({name:d.name,screenshot_path:d.screenshot_path,id:d.id})));const i=ua(a,d=>d.name).filter(d=>d.screenshot_path).map(d=>({name:d.name,screenshotPath:d.screenshot_path,scenarioId:d.id})),c=a.filter(d=>!d.screenshot_path);return c.length>0&&console.warn(`[editorScenarioLookup] ${c.length} scenarios have no screenshot_path:`,c.map(d=>d.name)),console.log(`[editorScenarioLookup] Found ${i.length} scenarios with screenshots`),i}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function tl(){console.log("[editorScenarioLookup] Looking up new scenario screenshots since last journal entry");try{const e=await $e();if(!e)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:t}=await Ie(e),r=Te(),s=ge()||process.cwd();let a=null;const o=O.join(s,".codeyam","journal","index.json");try{const u=K.readFileSync(o,"utf8"),m=JSON.parse(u);m.entries&&m.entries.length>0&&(a=m.entries[m.entries.length-1].time)}catch{}if(!a){const u=O.join(s,".codeyam","editor-step.json");try{const m=K.readFileSync(u,"utf8");a=JSON.parse(m).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}}if(!a)return console.warn("[editorScenarioLookup] No cutoff timestamp found (no journal entries, no featureStartedAt)"),[];const i=Os(a),c=await r.selectFrom("editor_scenarios").select(["name","screenshot_path","id"]).where("project_id","=",t.id).where("created_at",">=",i).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${c.length} scenarios since ${a}`);const h=ua(c,u=>u.name).filter(u=>u.screenshot_path).map(u=>({name:u.name,screenshotPath:u.screenshot_path,scenarioId:u.id}));return console.log(`[editorScenarioLookup] Found ${h.length} new scenarios with screenshots`),h}catch(e){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",e),[]}}async function nl(e,t,r){const s=O.join(t,".codeyam","journal","screenshots");await Ne.mkdir(s,{recursive:!0});const a=[];for(const o of e){const i=O.join(t,".codeyam","editor-scenarios",o.screenshotPath),c=Xp(o.name,r),d=O.join(s,c);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${o.name}" from ${i} → ${d}`);try{await Ne.access(i),await Ne.copyFile(i,d),a.push({name:o.name,path:`screenshots/${c}`}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${o.name}"`)}catch(h){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,h instanceof Error?h.message:h)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${a.length} scenarios have screenshots embedded`),a}async function af({request:e}){if(e.method!=="PATCH")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{time:r,commitSha:s,commitMessage:a,description:o,includeSessionScenarios:i}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const c=process.env.CODEYAM_ROOT_PATH||process.cwd(),d=O.join(c,".codeyam","journal"),h=O.join(d,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let u={entries:[]};try{const g=await Ne.readFile(h,"utf8");u=JSON.parse(g)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const m=tf(u.entries,r);if(m===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const p=u.entries[m];let f,y;if(i){const g=await tl();g.length>0&&(f=g.map(x=>x.name),y=await nl(g,c,new Date))}if(nf(p,{commitSha:s,commitMessage:a,description:o,scenarios:f,scenarioScreenshots:y}),u.entries[m]=p,await Ne.writeFile(h,JSON.stringify(u,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const g=p.date,x=O.join(d,`${g}.md`);let v="";try{v=await Ne.readFile(x,"utf8")}catch{}if(v){const b=rf(v,p.title,s,a||null);b&&(await Ne.writeFile(x,b,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(g){console.warn("[editor-journal-update] Failed to update markdown:",g)}return Nt.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${p.title}"`),new Response(JSON.stringify({success:!0,entry:p}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-update] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const of=Object.freeze(Object.defineProperty({__proto__:null,action:af},Symbol.toStringTag,{value:"Module"}));async function lf({request:e}){try{const t=process.env.CODEYAM_ROOT_PATH||process.cwd(),r=await Sm(t);let s=0;const a={};for(const[o,i]of Object.entries(r))i.errors.length>0&&(a[o]=i,s+=i.errors.length);return new Response(JSON.stringify({hasErrors:s>0,totalErrors:s,scenarios:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-client-errors] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const cf=Object.freeze(Object.defineProperty({__proto__:null,loader:lf},Symbol.toStringTag,{value:"Module"}));async function df({request:e}){try{const r=(await rn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const c=i.analyses[0],d=c.scenarios||[],h=!((y=c.status)!=null&&y.finishedAt),u=i.entityType||"visual",p=u==="library"||u==="functionCall"?d.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):d.some(g=>{var x,v,b,N;return((v=(x=g.metadata)==null?void 0:x.screenshotPaths)==null?void 0:v[0])&&!((b=g.metadata)!=null&&b.noScreenshotSaved)&&!((N=g.metadata)!=null&&N.sameAsDefault)}),f=d.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:p,isAnalyzing:h,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),a=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),o=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:a,analyzing:o}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-entity-status] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const uf=Object.freeze(Object.defineProperty({__proto__:null,loader:df},Symbol.toStringTag,{value:"Module"}));async function hf({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:a,scenarios:o,includeSessionScenarios:i,screenshot:c,commitSha:d,commitMessage:h}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(o||[])}, includeSessionScenarios=${!!i}, screenshot=${c||"none"}`),!r||!s||!a)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!a}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=O.join(u,".codeyam","journal");await Ne.mkdir(m,{recursive:!0});const p=new Date,f=p.toISOString().split("T")[0],y=p.toISOString();let g=o||[];const x=i?await tl():o&&o.length>0?await sf(o):[];i&&x.length>0&&(g=x.map(k=>k.name));const v=await nl(x,u,p),b=O.join(m,`${f}.md`);let N="";try{N=await Ne.readFile(b,"utf8")}catch{N=`# Development Journal — ${f}
252
+ `}const w=ef({title:r,timeStr:y,type:s,description:a,allScenarioNames:g,screenshot:c||null,scenarioScreenshots:v,commitSha:d||null,commitMessage:h||null});await Ne.writeFile(b,N+w,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${b}`);const E=O.join(m,"index.json");let C={entries:[]};try{const k=await Ne.readFile(E,"utf8");C=JSON.parse(k)}catch{}const S={date:f,time:y,title:r,type:s,description:a,scenarios:g,screenshot:c||null,scenarioScreenshots:v,commitSha:d||null,commitMessage:h||null};return C.entries.push(S),await Ne.writeFile(E,JSON.stringify(C,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${C.entries.length} entries)`),Nt.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${v.length}`),new Response(JSON.stringify({success:!0,entry:S,scenarioScreenshotsFound:v.length}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-entry] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const mf=Object.freeze(Object.defineProperty({__proto__:null,action:hf},Symbol.toStringTag,{value:"Module"}));function pf({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=ge()||process.cwd();let o=new URL(e.url).searchParams.get("scenarioId");if(!o){const d=O.join(r,".codeyam","active-scenario.json");if(!K.existsSync(d))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(K.readFileSync(d,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=O.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!K.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const c=K.readFileSync(i,"utf-8");return new Response(c,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const ff=Object.freeze(Object.defineProperty({__proto__:null,loader:pf},Symbol.toStringTag,{value:"Module"}));async function gf(e,t){const r=ge();if(!r)return{entityCalls:[],analysisCalls:[]};const s=O.join(r,".codeyam","llm-calls");try{await Ne.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const a=[],o=[];try{const c=(await Ne.readdir(s)).filter(v=>v.endsWith(".json")),d=`${e}_`,h=t?`${t}_`:null,u=[],m=[];for(const v of c)v.startsWith(d)||h&&v.startsWith(h)?u.push(v):m.push(v);const p=u.map(async v=>{try{const b=O.join(s,v),N=await Ne.readFile(b,"utf-8");return JSON.parse(N)}catch{return null}}),f=m.map(async v=>{try{const b=O.join(s,v),N=await Ne.readFile(b,"utf-8"),w=JSON.parse(N);return w.object_id===e||t&&w.object_id===t?w:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(p),Promise.all(f)]),x=[...y,...g].filter(v=>v!==null);for(const v of x)v.object_id===e?a.push(v):t&&v.object_id===t&&o.push(v);a.sort((v,b)=>b.created_at-v.created_at),o.sort((v,b)=>b.created_at-v.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function yf({params:e,request:t}){const{entitySha:r}=e;if(!r)return G({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await gf(r,a);return G(o)}const xf=Object.freeze(Object.defineProperty({__proto__:null,loader:yf},Symbol.toStringTag,{value:"Module"}));function bf(e){try{const t=O.join(e,"package.json"),r=JSON.parse(K.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function vf(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const c of s)for(const d of c.assertionResults||[]){const h=d.ancestorTitles||[],u=d.title||d.fullName||"unknown",m=h.length>0?`${h.join(" > ")} > ${u}`:u;a.push({title:u,fullName:m,status:d.status==="passed"?"passed":d.status==="failed"?"failed":"skipped",duration:d.duration,failureMessages:(i=d.failureMessages)!=null&&i.length?d.failureMessages:void 0})}const o=a.some(c=>c.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}async function wf(e,t){const r=bf(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=O.isAbsolute(t)?t:O.join(e,t);if(!K.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=O.join(Ks.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var m;let i,c;r==="vitest"?(c="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",a,t]):(c="./node_modules/.bin/jest",i=["--json","--outputFile",a,"--testPathPatterns",t]);const d=St(c,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let h="";(m=d.stderr)==null||m.on("data",p=>{h+=p.toString()});const u=setTimeout(()=>{d.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);d.on("close",()=>{clearTimeout(u);try{const p=K.readFileSync(a,"utf8");K.unlinkSync(a),o(vf(t,p))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:h.trim().slice(0,500)||"Test runner failed to produce output"})}}),d.on("error",p=>{clearTimeout(u),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${p.message}`})})})}async function Nf({request:e}){const r=new URL(e.url).searchParams.get("testFile");if(!r)return new Response(JSON.stringify({status:"error",errorMessage:"Missing testFile parameter",testCases:[],testFilePath:""}),{headers:{"Content-Type":"application/json"}});const s=ge()||process.cwd();try{const a=await wf(s,r);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}catch(a){const o=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const Cf=Object.freeze(Object.defineProperty({__proto__:null,loader:Nf},Symbol.toStringTag,{value:"Module"}));function Sf(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=_e("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return kf(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function kf(e){const t=e.trim().split(`
253
+ `).filter(s=>s.length>0),r=[];for(const s of t){const a=s[0],o=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),c,d=!1,h;if(a==="A"||o==="A")c="added",d=a==="A";else if(a==="M"||o==="M")c="modified",d=a==="M";else if(a==="D"||o==="D")c="deleted",d=a==="D";else if(a==="R"||o==="R"){c="renamed",d=a==="R";const u=i.indexOf(" -> ");u!==-1&&(h=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(c="untracked",d=!1):(c="modified",d=a!==" "&&a!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=Z.join(u,i);try{const p=(y,g)=>{const x=Se.readdirSync(y,{withFileTypes:!0}),v=[];for(const b of x){const N=Z.join(y,b.name),w=Z.relative(u,N);b.isDirectory()?v.push(...p(N,g)):b.isFile()&&v.push(w)}return v},f=p(m,u);for(const y of f)r.push({path:y,status:c,staged:d,...h&&{oldPath:h}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:c,staged:d,...h&&{oldPath:h}})}return r}function Ef(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return _e("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function Af(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=_e('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(s)return s[1];try{return _e("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return _e("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function Pf(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return _e('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
254
+ `).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function rl(){const e=ge();return e?Sf(e):[]}function _f(){const e=ge();return e?Ef(e):null}function Mf(){const e=ge();return e?Af(e):"main"}function jf(){const e=ge();return e?Pf(e):[]}function sl(e,t){const r=ge();return r?Tf(e,t,r):[]}function Tf(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return _e(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
255
+ `).filter(i=>i.length>0).map(i=>{const c=i.split(" "),d=c[0];let h=c[1],u,m;return d==="A"?m="added":d==="M"?m="modified":d==="D"?m="deleted":d.startsWith("R")?(m="renamed",u=c[1],h=c[2]):m="modified",{path:h,status:m,...u&&{oldPath:u}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function $f(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=_e(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=Se.readFileSync(Z.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),a=""}return{oldContent:s,newContent:a,fileName:e}}catch(s){return console.error(`Failed to get diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Rf(e){const t=ge();return t?$f(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function If(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=_e(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=_e(`git show ${r}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function lr(e,t,r){const s=ge();return s?If(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function yo(e,t){var r,s;try{return((s=(r=_e(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:s.trim())??null}catch(a){return console.error(`Failed to get commit SHA for ${e}:`,a),""}}function Df(e,t,r,s){const a=zn.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function al(){const e=ge();if(!e)throw new Error("No project root found");const t=Z.join(e,".codeyam","cache","branch-entity-diff");return Se.existsSync(t)||Se.mkdirSync(t,{recursive:!0}),t}function Lf(e){try{const t=al(),r=Z.join(t,`${e}.json`);if(!Se.existsSync(r))return null;const s=Se.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function Of(e,t){try{const r=al(),s=Z.join(r,`${e}.json`);Se.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function Ff(e,t,r){const s=xr(t,e),a=xr(r,e),o=new Map(s.map(u=>[u.name,u])),i=new Map(a.map(u=>[u.name,u])),c=[],d=[],h=[];for(const[u,m]of i){const p=o.get(u);p?p.sha!==m.sha&&d.push({name:u,baseSha:p.sha,compareSha:m.sha,entityType:m.entityType}):c.push(m)}for(const[u,m]of o)i.has(u)||h.push(m);return{filePath:e,newEntities:c,modifiedEntities:d,deletedEntities:h}}function zf(e,t){const r=ge();if(!r)throw new Error("No project root found");const s=yo(e,r),a=yo(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Df(e,t,s,a),i=Lf(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const c=sl(e,t),d=[];for(const u of c)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const m=lr(u.path,e,t),p=xr(m.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const m=lr(u.path,e,t),p=xr(m.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const m=lr(u.path,e,t),p=Ff(u.path,m.oldContent,m.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const h={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return Of(o,h),h}function Bf({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return G({error:"Missing required parameters: base and compare"},{status:400});const a=zf(r,s);return G(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),G({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const Yf=Object.freeze(Object.defineProperty({__proto__:null,loader:Bf},Symbol.toStringTag,{value:"Module"}));async function Uf({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:a,viewportWidth:o=1440}=t;if(!r||!s||!a)return G({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${s}`);const i=ge();if(!i)return G({error:"Project root not found"},{status:500});const c=O.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),h=await new Promise(p=>{const f=O.join(i,".codeyam","db.sqlite3"),y=St("npx",["tsx",c,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",v=>{const b=v.toString();g+=b;const N=b.trim().split(`
256
+ `);for(const w of N)w.includes("[Capture]")&&console.log(w)}),y.stderr.on("data",v=>{const b=v.toString();x+=b,console.error("[Capture:Error]",b.trim())}),y.on("close",v=>{p(v===0?{success:!0,output:g}:{success:!1,output:g,error:x||`Process exited with code ${v}`})}),y.on("error",v=>{console.error("[Capture] Failed to spawn child process:",v),p({success:!1,output:"",error:v.message})})});if(!h.success)return G({error:"Failed to capture screenshot",details:h.error},{status:500});const u=h.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return G({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(u[1]);return G(m)}catch(t){return console.error("[Capture] Error:",t),G({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Wf=Object.freeze(Object.defineProperty({__proto__:null,action:Uf},Symbol.toStringTag,{value:"Module"}));function Hf(e){const t=e||process.cwd();try{return _e("git rev-parse HEAD",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch(r){throw new Error(`Failed to get HEAD SHA: ${r}`)}}function Jf(e){const t=e||process.cwd();try{return _e("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function Vf(e){if(Jf(e))return!1;_e("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{_e('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),_e('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function qf(e){_e("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function Gf(e,t){return _e(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Hf(e)}function Kf(e){return/^[0-9a-f]{7,40}$/i.test(e)}function Qf(e,t){try{return _e(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function Zf(e,t){try{return{stashed:!_e(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function Xf(e,t){_e(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function eg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{commitSha:r}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({success:!1,error:"commitSha is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(!Kf(r))return new Response(JSON.stringify({success:!1,error:"Invalid commit SHA format"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();if(console.log(`[editor-load-commit] Loading commit ${r} in ${s}`),!Qf(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:a}=Zf(s,"codeyam: auto-stash before time travel");a&&console.log("[editor-load-commit] Stashed uncommitted changes");try{Xf(s,r),console.log(`[editor-load-commit] Checked out ${r}`)}catch(o){const i=o instanceof Error?o.message:String(o);return console.error("[editor-load-commit] Checkout failed:",i),new Response(JSON.stringify({success:!1,error:`Checkout failed: ${i}`}),{status:500,headers:{"Content-Type":"application/json"}})}try{const i=await(await fetch(`http://localhost:${process.env.CODEYAM_PORT||"3111"}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})})).json();console.log("[editor-load-commit] Dev server restart:",i)}catch(o){console.warn("[editor-load-commit] Dev server restart warning:",o)}return new Response(JSON.stringify({success:!0,stashed:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-load-commit] Error:",t),new Response(JSON.stringify({success:!1,error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const tg=Object.freeze(Object.defineProperty({__proto__:null,action:eg},Symbol.toStringTag,{value:"Module"}));async function ng(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Je();const s=await At({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const a=Te(),o=s.entitySha,i=await a.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let c={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?c=JSON.parse(i.metadata):c=i.metadata),c.defaultWidth=t,await a.updateTable("entities").set({metadata:JSON.stringify(c)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!s.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=s.scenarios)==null?void 0:f.length)||0} scenarios`),await gn(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=ge();if(!d)throw new Error("Project root not found");const h=O.join(d,".codeyam","config.json"),u=JSON.parse(K.readFileSync(h,"utf8")),{projectSlug:m}=u;if(!m)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:m,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function rg(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Je();const s=await At({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=(u=s.scenarios)==null?void 0:u.find(m=>m.id===t);if(!a)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${a.name}`),await gn(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const p=m.scenarios.find(f=>f.name===a.name);p&&(delete p.finishedAt,delete p.startedAt,delete p.error,delete p.errorStack,delete p.screenshotStartedAt,delete p.screenshotFinishedAt,delete p.interactiveStartedAt,delete p.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${a.name} for recapture`);const o=ge();if(!o)throw new Error("Project root not found");const i=O.join(o,".codeyam","config.json"),c=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:d}=c;if(!d)throw new Error("Project slug not found in config");const{jobId:h}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${h}`),{jobId:h}}async function sg({request:e,context:t}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return G({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return G({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await rg(a,o,r);return console.log("[API] Scenario recapture queued",i),G({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),G({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const ag=Object.freeze(Object.defineProperty({__proto__:null,action:sg},Symbol.toStringTag,{value:"Module"}));async function Ys(e){try{return await be.stat(e),!0}catch{return!1}}async function ol(){try{const e=ge();if(!e)return null;const t=Z.join(e,".codeyam","config.json");return JSON.parse(await be.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function og(){return`/private/tmp/claude-501/-${(ge()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const cr="/tmp/claude-rule-markers",ig=/<system-reminder>[\s\S]*?<\/system-reminder>/g,xo=2e3;function lg(e,t){if(e==="Read"||e==="Write"||e==="Edit")return String(t.file_path||"");if(e==="Glob")return String(t.pattern||"");if(e==="Grep"){const r=String(t.pattern||""),s=String(t.path||"");return s?`"${r}" in ${s}`:`"${r}"`}if(e==="Bash"){const r=String(t.command||"");return r.length>100?r.slice(0,100)+"...":r}if(e==="Task")return String(t.description||String(t.prompt||"").slice(0,80));for(const r of Object.values(t))if(typeof r=="string"&&r)return r.slice(0,80);return""}const cg=["no,","no ","that's not","thats not","that is not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","dont do","shouldn't","should not","try again","let me clarify","to clarify","that broke","that failed","error","bug"];function dg(e){const t=[],r=new Set;for(const s of e)if(!(s.type!=="tool_call"||!s.name||!s.input)){if(s.name==="Write"||s.name==="Edit"){const a=String(s.input.file_path||"");if(a.includes(".claude/rules/")){const o=a.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${s.name}:${o}`;r.has(i)||(r.add(i),s.name==="Write"?t.push({action:"created",filePath:o,content:String(s.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(s.input.old_string||""),newString:String(s.input.new_string||"")}))}}else if(s.name==="Bash"){const a=String(s.input.command||"");if(a.includes("codeyam memory touch")){const o=`touch:${a}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:a}))}}}return t}function ug(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let s=e.slice(r+t.length).trim();const a=s.indexOf(`
257
+ ###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function hg(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of cg)if(r.includes(s))return!0}return!1}function mg(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type==="assistant"){const a=(s.message||{}).model;if(typeof a=="string"&&a)return a}}catch{continue}}}function pg(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type!=="result")continue;const a={subtype:String(s.subtype||"unknown"),is_error:!!s.is_error};if(typeof s.duration_ms=="number"&&(a.duration_ms=s.duration_ms),typeof s.duration_api_ms=="number"&&(a.duration_api_ms=s.duration_api_ms),typeof s.num_turns=="number"&&(a.num_turns=s.num_turns),typeof s.total_cost_usd=="number"&&(a.total_cost_usd=s.total_cost_usd),s.usage&&typeof s.usage=="object"){a.usage={};for(const o of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof s.usage[o]=="number"&&(a.usage[o]=s.usage[o])}return Array.isArray(s.errors)&&s.errors.length>0&&(a.errors=s.errors.map(String)),a}catch{continue}}}function fg(e){const t=[],r={};for(const s of e){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,h=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:h,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const u of d)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const m=u,p=String(m.tool_use_id||"");let f=m.content;const y=!!m.is_error;typeof f=="string"&&(f=f.replace(ig,"").trim()),t.push({type:"tool_result",tool_use_id:p,tool_name:r[p]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:h})}}}else if(i==="assistant"&&Array.isArray(d))for(const u of d){if(typeof u!="object"||u===null)continue;const m=u;if(m.type==="text"){const p=String(m.text||"").trim();p&&t.push({type:"assistant_text",text:p,timestamp:h})}else if(m.type==="tool_use"){const p=String(m.id||""),f=String(m.name||"unknown"),y=m.input||{};r[p]=f,t.push({type:"tool_call",tool_use_id:p,name:f,input:y,timestamp:h})}}}return t}function gg(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}const ln=20;async function bo(e){const r=(await be.readFile(e.filePath,"utf-8")).split(`
258
+ `),s=fg(r);if(s.length===0)return null;const a=s.find(N=>N.type==="user_prompt"),o=e.stem,i=mg(r);let c=(a==null?void 0:a.slug)||"",d=(a==null?void 0:a.timestamp)||"";d||(d=new Date(e.mtime).toISOString());let h;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?c=c||"rule-reflection/stale":e.stem.endsWith("-conversation")?c=c||"rule-reflection/conversation":e.stem.endsWith("-interruption")?c=c||"rule-reflection/interruption":c=c||"rule-reflection";const N=e.filePath.replace(/\.log$/,".context");if(await Ys(N))try{h=await be.readFile(N,"utf-8")}catch{}}const u=s.filter(N=>N.type==="tool_call").length,m=s.filter(N=>N.type==="assistant_text").length,p=s.filter(N=>N.type==="tool_result"&&N.is_error&&N.content!=="Sibling tool call errored"),f=p.length,y=p.map(N=>{const w=N.content||"Unknown error";return w.length>150?w.slice(0,150)+"...":w});for(const N of s)N.type==="tool_call"&&N.name&&N.input&&(N.summary=lg(N.name,N.input));for(const N of s)N.type==="tool_result"&&N.content&&N.content.length>xo&&(N.truncated=!0,N.fullLength=N.content.length,N.content=N.content.slice(0,xo));const g=dg(s),x=hg(s),v=ug(h),b=pg(r);return{id:o,slug:c,timestamp:d,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:m,errors:f,errorMessages:y},entries:s,context:h,conversationSnippet:v,ruleChanges:g,hasConfusion:x,sessionResult:b}}async function yg(){const e=og(),t=cr,r=[];if(await Ys(e)){const i=await be.readdir(e);for(const c of i)if(c.endsWith(".output")){const d=Z.join(e,c),h=await be.stat(d);r.push({filePath:d,stem:c.replace(".output",""),mtime:h.mtimeMs})}}const s=new Set,a=await ol(),o=[];a&&o.push(Z.join(t,a)),o.push(t);for(const i of o){if(!await Ys(i))continue;const c=await be.readdir(i);for(const d of c){if(!d.endsWith(".log")||s.has(d))continue;s.add(d);const h=Z.join(i,d),u=await be.stat(h);r.push({filePath:h,stem:d.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,c)=>c.mtime-i.mtime),r}async function xg({request:e}){var t;try{const r=new URL(e.url),s=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",a=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),o=await yg();if(!s){const u=o.length,m=(a-1)*ln,p=o.slice(m,m+ln),f=[];for(const y of p){const g=await bo(y);g&&f.push(g)}return Response.json({agents:f,total:u,page:a,pageSize:ln})}const i=[];for(const u of o){const m=await bo(u);if(!m)continue;(m.id.toLowerCase().includes(s)||m.slug.toLowerCase().includes(s)||m.entries.some(f=>gg(f,s)))&&i.push(m)}const c=i.length,d=(a-1)*ln,h=i.slice(d,d+ln);return Response.json({agents:h,total:c,page:a,pageSize:ln})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const bg=Object.freeze(Object.defineProperty({__proto__:null,loader:xg},Symbol.toStringTag,{value:"Module"}));function vg(e){var a,o;const t=Z.join(e,"package.json");if(!Se.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(Se.readFileSync(t,"utf8"));if(Se.existsSync(Z.join(e,"pnpm-lock.yaml"))?r="pnpm":Se.existsSync(Z.join(e,"yarn.lock"))?r="yarn":Se.existsSync(Z.join(e,"bun.lockb"))&&(r="bun"),!((a=i.scripts)!=null&&a.dev))if((o=i.scripts)!=null&&o.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}const wg=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/];function Ng(e){for(const t of wg){const r=e.match(t);if(r){const s=r[1]||r[0];return Cg(s).trim()}}return null}function Cg(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function Sg(e){const{exitCode:t,uptime:r,retryCount:s}=e,a=r<1e4;return t!==0&&t!==null&&a&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:{action:"stopped"}}const il="__codeyam_editor_dev_server__",vo=30;function fa(){return globalThis[il]??null}function ll(e){globalThis[il]=e}function Cs(e,t){const r=[Z.join(e,".next","dev","lock"),Z.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{Se.existsSync(s)&&(Se.unlinkSync(s),console.log(`[editor-dev-server] Removed stale lock file: ${s}`))}catch(a){console.warn(`[editor-dev-server] Failed to remove lock file ${s}:`,a)}if(t)try{const s=_e(`lsof -ti:${t}`,{encoding:"utf8"}).trim();s&&(_e(`lsof -ti:${t} | xargs kill`),console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${s}`))}catch{}}function kg({request:e}){const t=fa();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:Bi(),pid:t.pid,errorMessage:t.status==="error"?t.errorMessage:null}),{headers:{"Content-Type":"application/json"}}):new Response(JSON.stringify({status:"stopped",url:null,proxyUrl:null}),{headers:{"Content-Type":"application/json"}})}async function Eg({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{action:r}=t;return r==="start"?Us():r==="stop"?wo():r==="restart"?(wo(),await new Promise(s=>setTimeout(s,1e3)),Us()):new Response(JSON.stringify({error:'Invalid action. Use "start", "stop", or "restart".'}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}function Ag(){let t=Z.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const a=Z.dirname(t);if(Z.basename(a)==="webserver"||Z.basename(t)==="webserver"){t=Z.basename(t)==="webserver"?t:a;break}t=a}const r=[Z.join(t,"scripts","codeyam-preload.mjs"),Z.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(Se.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function Us(e=!1){var g,x;const t=fa();if(t&&t.status!=="stopped"&&t.status!=="error")return new Response(JSON.stringify({status:t.status,url:t.url,message:"Dev server is already running"}),{headers:{"Content-Type":"application/json"}});const r=ge()||process.cwd(),s=vg(r);if("error"in s)return new Response(JSON.stringify({error:s.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:a,args:o}=s;Cs(r,3e3),Cs(r,3001),Cs(r,5173),console.log(`[editor-dev-server] Starting: ${a} ${o.join(" ")} in ${r}`);const c=parseInt(process.env.CODEYAM_PORT||"3111",10)+1,d=Ag(),h=process.env.NODE_OPTIONS||"",u=d?`${h} --import ${d}`.trim():h,m=St(a,o,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1",...u?{NODE_OPTIONS:u}:{},CODEYAM_PROXY_URL:`http://localhost:${c}`},detached:!0});m.unref();const p=e?((t==null?void 0:t.retryCount)??0)+1:0,f={process:m,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:m.pid||0,startedAt:Date.now(),retryCount:p};ll(f);const y=(v,b)=>{const N=v.toString();if(b){const w=N.split(`
259
+ `).filter(E=>E.trim());f.stderrBuffer.push(...w),f.stderrBuffer.length>vo&&(f.stderrBuffer=f.stderrBuffer.slice(-vo))}if(f.status==="starting"){const w=Ng(N);if(w){f.url=w,f.status="running",console.log(`[editor-dev-server] URL detected: ${f.url}`);const E=parseInt(process.env.CODEYAM_PORT||"3111",10);Yi({port:E+1,targetUrl:f.url})}}};return(g=m.stdout)==null||g.on("data",v=>y(v,!1)),(x=m.stderr)==null||x.on("data",v=>y(v,!0)),m.on("exit",v=>{console.log(`[editor-dev-server] Process exited with code ${v}`);const b=Date.now()-f.startedAt,N=Sg({exitCode:v??null,uptime:b,retryCount:f.retryCount});N.action==="retry"?(console.log(`[editor-dev-server] Quick failure (${b}ms), auto-retrying...`),f.status="stopped",Us(!0)):N.action==="error"?(f.status="error",f.errorMessage=f.stderrBuffer.length>0?f.stderrBuffer.join(`
260
+ `):`Dev server exited with code ${v}`,console.error(`[editor-dev-server] Server failed: ${f.errorMessage}`)):f.status="stopped"}),m.on("error",v=>{console.error("[editor-dev-server] Process error:",v),f.status="error",f.errorMessage=v.message}),new Response(JSON.stringify({status:"starting",pid:m.pid,message:`Starting ${a} ${o.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function wo(){const e=fa();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});Ui();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",ll(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const Pg=Object.freeze(Object.defineProperty({__proto__:null,action:Eg,loader:kg},Symbol.toStringTag,{value:"Module"}));async function _g({params:e,request:t}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});if(t.method!=="DELETE")return new Response("Method not allowed",{status:405});const s=zr(r);try{return await _n(s,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error clearing log file:",a);const o=a instanceof Error?a.message:String(a);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function Mg({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=zr(t);try{if(!$t(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const s=await js(r,"utf-8");return!s||s.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(s,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error reading log file:",s);const a=s instanceof Error?s.message:String(s);return new Response(`Error reading log file: ${a}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const jg=Object.freeze(Object.defineProperty({__proto__:null,action:_g,loader:Mg},Symbol.toStringTag,{value:"Module"}));async function Tg(){const e=await $e();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await Ie(e),r=Te(),s=process.env.CODEYAM_PORT||"3111",a=ge()||process.cwd(),o=O.join(a,".codeyam","editor-step.json");let i=null;try{const u=K.readFileSync(o,"utf8");i=JSON.parse(u).featureStartedAt||null}catch{}let c=r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path"]).where("project_id","=",t.id);if(i){const u=i.replace("T"," ").replace(/\.\d{3}Z$/,"");c=c.where("created_at",">=",u)}const h=(await c.orderBy("created_at","asc").execute()).map(u=>({id:u.id,name:u.name,componentName:u.component_name||null,link:`http://localhost:${s}/editor?scenario=${u.id}&ref=link`}));return Response.json({scenarios:h})}const $g=Object.freeze(Object.defineProperty({__proto__:null,loader:Tg},Symbol.toStringTag,{value:"Module"}));async function Rg(e,t){var o,i,c,d,h,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Je();const r=await At({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(o=r.scenarios)==null?void 0:o.find(m=>m.id===t);if(!s)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${s.name}`);const a={returnValue:{status:"success",data:((d=(c=(i=s.metadata)==null?void 0:i.data)==null?void 0:c.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(h=s.metadata)==null?void 0:h.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),a}async function Ig({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return G({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await Rg(r,s);return console.log("[API] Function execution completed successfully"),G({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),G({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Dg=Object.freeze(Object.defineProperty({__proto__:null,action:Ig},Symbol.toStringTag,{value:"Module"}));function Lg({request:e}){return G({status:"ok"})}async function Og({request:e,context:t}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return console.error("[Interactive Mode API] Queue not initialized"),G({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("action"),o=s.get("analysisId"),i=s.get("scenarioId");if(!a||!o)return G({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return G({error:'Invalid action. Must be "start" or "stop"'},{status:400});const c=await $e();if(console.log("[Interactive Mode API] projectSlug:",c),!c)return G({error:"Project not initialized"},{status:500});if(a==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:c});return G({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:c});return G({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(s){console.error("[Interactive Mode API] Error:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),G({error:"Failed to control interactive mode",details:a},{status:500})}}const Fg=Object.freeze(Object.defineProperty({__proto__:null,action:Og,loader:Lg},Symbol.toStringTag,{value:"Module"}));async function zg({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:s}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),s&&s.length>0){const a=ge();if(a)for(const o of s){const i=Z.join(a,".codeyam","captures","screenshots",o);try{await be.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(c){console.log(`[API] Could not delete screenshot ${i}:`,c instanceof Error?c.message:c)}}}return await Ud({ids:[r]}),console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const Bg=Object.freeze(Object.defineProperty({__proto__:null,action:zg},Symbol.toStringTag,{value:"Module"}));class Yg extends jr{emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}emitRefreshPreview(){this.emit("event",{type:"refresh-preview",timestamp:Date.now()})}}const Ws="__codeyam_dev_mode_event_emitter__";if(!globalThis[Ws]){const e=new Yg;e.setMaxListeners(20),globalThis[Ws]=e}const No=globalThis[Ws];function Ug({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
261
+
262
+ `));let a=!1;const o=()=>{if(!a){a=!0,No.off("event",i),clearInterval(c);try{r.close()}catch{}}},i=d=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(d)}
263
+
264
+ `))}catch{o()}};No.on("event",i);const c=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
265
+
266
+ `))}catch{o()}},3e4);e.signal.addEventListener("abort",o)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const Wg=Object.freeze(Object.defineProperty({__proto__:null,loader:Ug},Symbol.toStringTag,{value:"Module"})),Dn="/tmp/codeyam",Hs=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",cl=500,Hg=cl*1024*1024;function Kt(e,t){try{return _e(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function dr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function dl(e){return Kt("config user.email",e)}function Jg(e){const t=O.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function Vg(e,t=20){const r=O.join(Dn,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
267
+ `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function qg(e){try{const t=await fetch(`${Hs}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!t.ok)return!1;const{hasBase:r}=await t.json();return r}catch{return!1}}function Gg(e,t){try{_e(`git archive HEAD | gzip > "${t}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(r){throw new Error(`Failed to create base archive: ${r.message}`)}}function Kg(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,c=i||(()=>{}),d=Date.now(),h=O.join(Dn,`delta-staging-${d}`),u=O.join(h,"delta");K.mkdirSync(u,{recursive:!0});try{const m=Kt("diff --binary HEAD",t)||"";K.writeFileSync(O.join(u,"tracked.patch"),m?m+`
268
+ `:"");const p=Kt("ls-files --others --exclude-standard",t);if(p){const x=O.join(u,"untracked");K.mkdirSync(x,{recursive:!0});for(const v of p.split(`
269
+ `).filter(Boolean)){const b=O.join(t,v),N=O.join(x,v);if(K.existsSync(b)){const w=O.dirname(N);K.mkdirSync(w,{recursive:!0}),K.statSync(b).isFile()&&K.copyFileSync(b,N)}}}const f=O.join(t,".codeyam");if(K.existsSync(f)){const x=O.join(u,"codeyam");K.cpSync(f,x,{recursive:!0})}K.writeFileSync(O.join(u,"meta.json"),JSON.stringify(a,null,2));const y=O.join(Dn,"local-dev",r,"codeyam","log.txt");K.existsSync(y)?K.copyFileSync(y,O.join(u,"codeyam-log.txt")):K.writeFileSync(O.join(u,"codeyam-log.txt"),`# Log file not found
270
+ `);const g=O.join(t,".codeyam","debug-report.md");K.existsSync(g)&&(K.copyFileSync(g,O.join(u,"debug-report.md")),c("Debug report included")),o&&o.length>0&&(K.writeFileSync(O.join(u,"screenshot.jpg"),o),c(`Screenshot included (${dr(o.length)})`));try{_e(`tar -czf "${s}" -C "${h}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{K.rmSync(h,{recursive:!0,force:!0})}}async function Qg(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const c=Kt("rev-parse HEAD",t);if(!c)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=Kt("rev-parse --abbrev-ref HEAD",t)||"unknown",h=Kt("status --porcelain",t),u=Kt("remote get-url origin",t),m=h!==null&&h.length>0,p=Mi(r),f=Jg(t);let y=s;f&&(y={...s||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:c,branch:d,isDirty:m,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),v=O.join(Dn,`base-${c}-${x}.tar.gz`),b=O.join(Dn,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const N=await qg(c);let w=null;N?i("Server already has base, skipping..."):(i("Generating base archive..."),Gg(t,v),w=K.statSync(v).size,i(`Base archive: ${dr(w)}`)),i("Generating delta archive..."),Kg({projectRoot:t,projectSlug:r,outputPath:b,metadata:g,screenshot:a,onProgress:o});const C=K.statSync(b).size;i(`Delta archive: ${dr(C)}`);const S=(w||0)+C;if(S>Hg)throw K.existsSync(v)&&K.unlinkSync(v),K.unlinkSync(b),new Error(`Bundle too large: ${dr(S)} (max: ${cl} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:N?null:v,deltaPath:b,metadata:g,baseSha:c,baseSize:w,deltaSize:C}}async function Zg(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:c}=e,d=c||(()=>{}),h=K.statSync(r),u=t?K.statSync(t):null,m=h.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${Hs}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:m,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!p.ok){const N=await p.json();throw new Error(N.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await p.json(),x=[];if(t&&g){d("Uploading base...");const N=K.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:N}).then(w=>{if(!w.ok)throw new Error(`Base upload failed: ${w.status}`)}))}d("Uploading delta...");const v=K.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(N=>{if(!N.ok)throw new Error(`Delta upload failed: ${N.status}`)})),await Promise.all(x),d("Confirming upload...");const b=await fetch(`${Hs}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!b.ok){const N=await b.json();throw new Error(N.error||`Confirm failed: ${b.status}`)}return t&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function Xg({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),a=t.get("email"),o=t.get("source"),i=t.get("entitySha"),c=t.get("scenarioId"),d=t.get("analysisId"),h=t.get("currentUrl"),u=t.get("entityName"),m=t.get("entityType"),p=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&u&&(p?g=`Issue on ${u} scenario "${p}"`:g=`Issue on ${u}`);let x;if(y&&y.size>0){const S=await y.arrayBuffer();x=Buffer.from(S),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const v=ge();if(!v)return G({error:"Project root not found"},{status:500});const b=await $e();if(!b)return G({error:"Project slug not found"},{status:500});const N={issueType:r||"other",description:g,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:c||void 0,analysisId:d||void 0,currentUrl:h||void 0,recentActivity:Vg(b,20),entityName:u||void 0,entityType:m||void 0,scenarioName:p||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${N.source}, issue: ${N.issueType}`);const w=await Qg({projectRoot:v,projectSlug:b,feedback:N,screenshot:x,onProgress:S=>{console.log(`[Bundle] ${S}`)}}),E=(w.baseSize||0)+w.deltaSize;console.log(`[Bundle] Archives created: delta=${w.deltaSize} bytes${w.basePath?`, base=${w.baseSize} bytes`:" (base reused)"}`);const C=await Zg({basePath:w.basePath,deltaPath:w.deltaPath,projectSlug:b,metadata:w.metadata,baseSha:w.baseSha,deltaSize:w.deltaSize,onProgress:S=>{console.log(`[Bundle] ${S}`)}});return console.log(`[Bundle] Upload complete: ${C.bundleId}`),G({success:!0,reportId:C.bundleId,size:E})}catch(t){return console.error("[Bundle] Error:",t),G({error:t.message||"Failed to generate bundle"},{status:500})}}function e0(){const e=ge(),t=e?dl(e):null;return G({defaultEmail:t})}const t0=Object.freeze(Object.defineProperty({__proto__:null,action:Xg,loader:e0},Symbol.toStringTag,{value:"Module"}));async function n0({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=O.join(s,".codeyam","journal","index.json");let o={entries:[]};try{const c=await Ne.readFile(a,"utf8");o=JSON.parse(c)}catch{}let i=o.entries;return r&&(i=i.filter(c=>c.date===r)),new Response(JSON.stringify({entries:i}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const r0=Object.freeze(Object.defineProperty({__proto__:null,loader:n0},Symbol.toStringTag,{value:"Module"}));function ul(e){if(!K.existsSync(e))return Ke.Unknown;try{const t=JSON.parse(K.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?Ke.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?Ke.Remix:r["react-scripts"]?Ke.CRA:Ke.Unknown}catch{return Ke.Unknown}}function s0(e,t){let r=e;const s=O.resolve(t);for(;;){const a=O.resolve(r);if(K.existsSync(O.join(a,"pnpm-lock.yaml")))return"pnpm";if(K.existsSync(O.join(a,"yarn.lock")))return"yarn";if(K.existsSync(O.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=O.dirname(a);if(o===a)break;r=o}throw new Error(`Could not detect package manager in ${e} or any parent directory up to ${t}`)}function a0(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function o0(e){const t=O.join(e,"package.json");if(!K.existsSync(t))return{isWebApp:!1};if(ul(t)===Ke.Unknown)return{isWebApp:!1};try{const a=JSON.parse(K.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel"],c=Object.keys(a).filter(d=>["dev","start","serve","build"].some(h=>d.includes(h))).filter(d=>o.some(h=>a[d].includes(h)));if(c.length===0)return{isWebApp:!1};for(const d of c){const h=a[d],u=a0(h);if(u){const m=O.join(e,u);if(K.existsSync(m)&&K.statSync(m).isDirectory())return{isWebApp:!0,actualPath:m}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function hl(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=o0(t);if(o.isWebApp){const c=o.actualPath||t,d=O.relative(e,c);return a.push(d||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const c=K.readdirSync(t,{withFileTypes:!0});for(const d of c)if(d.isDirectory()&&!i.includes(d.name)){const h=O.join(t,d.name);a.push(...hl(e,h,r+1,s))}}catch{}return a}function i0(e){const t=hl(e);return t.length===0?[]:t.map(s=>{const a=O.join(e,s),o=O.join(a,"package.json"),i=ul(o),c=s0(a,e);let d;if(i===Ke.Remix||i===Ke.Next){const m=O.join(a,"app");K.existsSync(m)&&K.statSync(m).isDirectory()&&(d="app")}const h=l0(s,e),u=h?{command:"sh",args:["-c",`${c} run ${h} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:c,appDirectory:d,startCommand:u}})}function l0(e,t){const r=O.join(t,e),s=O.join(r,"package.json");if(!K.existsSync(s))return null;try{const o=JSON.parse(K.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const c of i)if(o[c])return c;return null}catch{return null}}async function c0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=ge()||process.cwd(),r=Z.join(t,".codeyam","config.json");let s=[];try{s=i0(t)}catch{}if(Se.existsSync(r)){const i=JSON.parse(Se.readFileSync(r,"utf8"));i.webapps=s,Se.writeFileSync(r,JSON.stringify(i,null,2))}const a=await $e();if(a)try{await mn({projectSlug:a,metadataUpdate:{webapps:s}})}catch{}let o=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",d=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(d.status==="stopped"||d.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),o=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:o,message:`Detected ${s.length} webapp(s)`}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const d0=Object.freeze(Object.defineProperty({__proto__:null,action:c0},Symbol.toStringTag,{value:"Module"}));function Zt(){const e=process.memoryUsage(),t=Jc.getHeapStatistics();return{process:{rss:Math.round(e.rss/1024/1024),heapTotal:Math.round(e.heapTotal/1024/1024),heapUsed:Math.round(e.heapUsed/1024/1024),external:Math.round(e.external/1024/1024),arrayBuffers:Math.round(e.arrayBuffers/1024/1024)},heap:{totalHeapSize:Math.round(t.total_heap_size/1024/1024),totalHeapSizeExecutable:Math.round(t.total_heap_size_executable/1024/1024),totalPhysicalSize:Math.round(t.total_physical_size/1024/1024),totalAvailableSize:Math.round(t.total_available_size/1024/1024),usedHeapSize:Math.round(t.used_heap_size/1024/1024),heapSizeLimit:Math.round(t.heap_size_limit/1024/1024),mallocedMemory:Math.round(t.malloced_memory/1024/1024),peakMallocedMemory:Math.round(t.peak_malloced_memory/1024/1024)},system:{totalMemory:Math.round(Ts.totalmem()/1024/1024),freeMemory:Math.round(Ts.freemem()/1024/1024)}}}function u0(){const e=Zt();console.log(`
271
+ [Memory Profiler] Detailed Statistics:`),console.log(" Process Memory:"),console.log(` RSS: ${e.process.rss} MB (total memory used by process)`),console.log(` Heap Used: ${e.process.heapUsed} MB / ${e.process.heapTotal} MB`),console.log(` External: ${e.process.external} MB (C++ objects)`),console.log(` ArrayBuffers: ${e.process.arrayBuffers} MB`),console.log(" V8 Heap:"),console.log(` Used: ${e.heap.usedHeapSize} MB / ${e.heap.totalHeapSize} MB`),console.log(` Physical: ${e.heap.totalPhysicalSize} MB`),console.log(` Limit: ${e.heap.heapSizeLimit} MB`),console.log(` Malloced: ${e.heap.mallocedMemory} MB (peak: ${e.heap.peakMallocedMemory} MB)`),console.log(" System:"),console.log(` Total: ${e.system.totalMemory} MB`),console.log(` Free: ${e.system.freeMemory} MB`);const t=(e.heap.usedHeapSize/e.heap.heapSizeLimit*100).toFixed(1);return console.log(` Heap Usage: ${t}% of limit`),e}function h0(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Zt();global.gc();const t=Zt(),r=e.process.heapUsed-t.process.heapUsed;return console.log(`[Memory Profiler] GC freed ${r} MB`),console.log(`[Memory Profiler] Heap: ${t.process.heapUsed} MB (was ${e.process.heapUsed} MB)`),!0}else return console.log("[Memory Profiler] GC not available. Start Node with --expose-gc to enable."),!1}function m0(){const e=Zt(),t=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,r={highHeapUsage:t>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},s=[];return r.highHeapUsage&&s.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&s.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&s.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&s.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:s,hasIssues:s.length>0}}function p0({request:e}){const r=new URL(e.url).searchParams.get("action");try{switch(r){case"snapshot":return Response.json({success:!1,error:"Heap snapshots are disabled because they block the server for several minutes. Use action=leaks instead."},{status:400});case"gc":{const s=h0(),a=Zt();return Response.json({success:s,message:s?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:a})}case"detailed":{const s=u0();return Response.json({success:!0,stats:s})}case"leaks":{const s=m0(),a=Zt();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=Zt();return Response.json({success:!0,stats:s,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(s){return console.error("[Memory API] Error:",s),Response.json({success:!1,error:s.message},{status:500})}}const f0=Object.freeze(Object.defineProperty({__proto__:null,loader:p0},Symbol.toStringTag,{value:"Module"})),rr=Xs(Zs);async function g0({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const s=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(s.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const a=await Promise.all(s.map(async o=>{const i=y0(o),c=i?await x0(o):null;return{pid:o,isRunning:i,processName:c}}));return Response.json({processes:a})}function y0(e){try{return process.kill(e,0),!0}catch{return!1}}async function x0(e){if(process.platform==="win32")try{const{stdout:r}=await rr(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),s=r.match(/"([^"]+)"/);if(!s)return null;const a=s[1];if(a.toLowerCase()==="node.exe")try{const{stdout:o}=await rr(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return a}catch{return null}try{const{stdout:r}=await rr(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await rr(`ps -p ${e} -o args=`),a=s.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const b0=Object.freeze(Object.defineProperty({__proto__:null,loader:g0},Symbol.toStringTag,{value:"Module"})),v0=Mr(import.meta.url),w0=O.dirname(v0);function N0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ti(),r=ge()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const s=(t==null?void 0:t.port)||3111,a=O.join(w0,"..","..","..","..","webserver","bootstrap.js"),o=O.join(r,".codeyam","logs");K.existsSync(o)||K.mkdirSync(o,{recursive:!0});const i=K.openSync(O.join(o,"background-server.log"),"a"),c=K.openSync(O.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();K.appendFileSync(O.join(o,"background-server.log"),`
272
+ [${d}] Server restart requested via dashboard
273
+ `),Qu();const h=St("node",[a],{detached:!0,stdio:["ignore",i,c],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});h.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${h.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const C0=Object.freeze(Object.defineProperty({__proto__:null,action:N0},Symbol.toStringTag,{value:"Module"}));async function S0({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${s.length} scenarios to save`),s.forEach((c,d)=>{var m,p,f,y,g;const h=(p=(m=c.metadata)==null?void 0:m.data)==null?void 0:p.argumentsData,u=Array.isArray(h)&&h.length>0?JSON.stringify(h[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${c.name}`,{id:c.id,projectId:c.projectId,analysisId:c.analysisId,hasMetadata:!!c.metadata,hasData:!!((f=c.metadata)!=null&&f.data),mockDataKeys:(g=(y=c.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(c.metadata.data.mockData):[],argumentsDataLength:Array.isArray(h)?h.length:"not-array",argumentsDataPreview:u})});const a=s.map(c=>({...c,projectId:c.projectId||r.projectId,analysisId:c.analysisId||r.id})),o=await ou(a);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((c,d)=>{var u,m;const h=(m=(u=c.metadata)==null?void 0:u.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${d}: ${c.name}`,{id:c.id,argumentsDataLength:Array.isArray(h)?h.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const k0=Object.freeze(Object.defineProperty({__proto__:null,action:S0},Symbol.toStringTag,{value:"Module"})),E0=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function A0({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",a=new URLSearchParams;r&&a.set("search",r),s!=="1"&&a.set("page",s);const o=a.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),d=await(await fetch(i.toString())).json();if(d.error)return G({agents:[],error:d.error,search:r,page:1,totalPages:1});const h=d.total??(d.agents||[]).length,u=d.pageSize??20;return G({agents:d.agents||[],error:null,search:r,page:d.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(h/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),G({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function P0(e){if(!e)return"";try{return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return e}}function _0(e){if(!e)return"";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}catch{return e}}function M0(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function ur({type:e,toolName:t}){const r={user_prompt:"bg-[#00b4d8] text-black",assistant_text:"bg-[#a8dadc] text-black",tool_call:"bg-[#f4a261] text-black",tool_result:"bg-[#2a9d8f] text-black",context:"bg-[#7c3aed] text-white"},s={user_prompt:"USER",assistant_text:"ASSISTANT",tool_call:t||"TOOL",tool_result:"RESULT",context:"CONTEXT"};return n("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide ${r[e]||"bg-gray-300 text-black"}`,children:s[e]||e})}function j0({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let s=typeof r=="string"?r:JSON.stringify(r);return s.length>500&&(s=s.slice(0,500)+"..."),l("div",{children:[l("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function T0({content:e,truncated:t,fullLength:r}){const[s,a]=_(!1);return l("div",{children:[l("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>a(!s),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:s?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function $0({entry:e,pairedResult:t}){const[r,s]=_(!1),a=P0(e.timestamp||"");return e.type==="user_prompt"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(ur,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(ur,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?l("div",{className:"my-2",children:[l("button",{onClick:()=>s(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(ot,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(Ot,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(ur,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:a})]}),r&&l("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(j0,{input:e.input||{}}),t&&l("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[l("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(T0,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function R0({context:e}){const[t,r]=_(!1);return l("div",{className:"my-2",children:[l("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(ot,{className:"w-3 h-3 text-gray-400"}):n(Ot,{className:"w-3 h-3 text-gray-400"}),n(ur,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Full prompt context"})]}),t&&n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e})]})}function I0({snippet:e}){const[t,r]=_(!1),s=e.split(`
274
+ `).filter(c=>c.trim()),a=s.slice(0,4),o=s.length>4,i=t?s:a;return l("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n(uc,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),l("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((c,d)=>{const h=c.match(/^\[(\w+)\]:\s*(.*)/);if(!h)return null;const[,u,m]=h,p=u==="user";return l("div",{className:"text-xs",children:[l("span",{className:`font-bold ${p?"text-blue-700":"text-gray-500"}`,children:[p?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:m.length>200?m.slice(0,200)+"...":m})]},d)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function D0({change:e}){const[t,r]=_(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return l("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:l("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(ot,{className:"w-3 h-3 inline flex-shrink-0"}):n(Ot,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&l("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&l("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&l("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function L0({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),a=r.some(i=>i.action==="modified");return l("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":a?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),l("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,c)=>n(D0,{change:i},c)),t.length>0&&l("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function O0({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",a=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=d=>d>=6e4?`${(d/6e4).toFixed(1)}m`:`${(d/1e3).toFixed(1)}s`,c=d=>d>=1e3?`${(d/1e3).toFixed(1)}k`:String(d);return l("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[l("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),l("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[l("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&l("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&l("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&l("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&l("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&l("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&l("span",{children:["Input: ",c(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&l("span",{children:["Output: ",c(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&l("span",{children:["Cache read: ",c(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&l("span",{children:["Cache write:"," ",c(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((d,h)=>n("div",{className:"text-red-700 break-words",children:d},h))})]})]})}function F0({agent:e,defaultOpen:t,isAdmin:r}){var E,C,S;const[s,a]=_(t),[o,i]=_(!1),[c,d]=_(null),[h,u]=_(!1),m=re(()=>{const k={};for(const P of e.entries)P.type==="tool_result"&&P.tool_use_id&&(k[P.tool_use_id]=P);return k},[e.entries]),p=re(()=>{const k=new Set;for(const P of e.entries)P.type==="tool_call"&&P.tool_use_id&&m[P.tool_use_id]&&k.add(P.tool_use_id);return k},[e.entries,m]),f=k=>{k.stopPropagation(),i(!0),d(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(P=>P.json()).then(P=>{P.success?d(`Saved to ${P.fixturePath}`):d(`Error: ${P.error}`)}).catch(P=>{d(`Error: ${P instanceof Error?P.message:String(P)}`)}).finally(()=>{i(!1)})},y=(e.ruleChanges||[]).filter(k=>k.action!=="touched"),g=y.filter(k=>k.action==="created"),x=y.filter(k=>k.action==="modified"),v=(e.ruleChanges||[]).filter(k=>k.action==="touched"),b=y.length>0,N=v.length>0,w=b||N;return l("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":g.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[l("button",{onClick:()=>a(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(ot,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(Ot,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm font-bold text-[#005C75] font-mono",children:e.id.slice(0,8)}),e.slug&&n("span",{className:"text-xs text-gray-500",children:e.slug}),e.model&&n("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-purple-100 text-purple-700",title:e.model,children:M0(e.model)}),g.length>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(mr,{className:"w-3 h-3"}),g.length," rule",g.length!==1?"s":""," ","created"]}),x.length>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(mr,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!b&&N&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[v.length," timestamp",v.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(hr,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),l("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((E=e.sessionResult)==null?void 0:E.duration_ms)!=null&&l(ue,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((C=e.sessionResult)==null?void 0:C.total_cost_usd)!=null&&l(ue,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),l("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[_0(e.timestamp),r&&b&&l("button",{onClick:f,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(dc,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),c&&n("div",{className:`px-4 py-2 text-xs font-mono ${c.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:c}),s&&l("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&l("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:k=>{k.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),u(!0),setTimeout(()=>u(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors flex-shrink-0",title:"Copy file path",children:h?n(pt,{className:"w-3.5 h-3.5 text-green-500"}):n(wt,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(O0,{result:e.sessionResult}),e.stats.errors>0&&((S=e.stats.errorMessages)==null?void 0:S.length)>0&&l("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[l("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((k,P)=>n("li",{className:"break-words",children:k},P))})]}),e.conversationSnippet&&n(I0,{snippet:e.conversationSnippet}),w&&n(L0,{changes:e.ruleChanges}),e.context&&n(R0,{context:e.context}),e.entries.map((k,P)=>{if(k.type==="tool_result"&&k.tool_use_id&&p.has(k.tool_use_id))return null;const I=k.type==="tool_call"&&k.tool_use_id?m[k.tool_use_id]:void 0;return n($0,{entry:k,pairedResult:I},`${e.id}-${P}`)})]})]})}function Ss(e,t){const r=new URLSearchParams;t&&r.set("search",t),e>1&&r.set("page",String(e));const s=r.toString();return`/agent-transcripts${s?`?${s}`:""}`}const z0=He(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=qe(),i=Ct(),c=Ul("root"),d=(c==null?void 0:c.isAdmin)??!1,[h,u]=_(s),[m,p]=_(!1),[f,y]=_(0);ft({source:"agent-transcripts-page"});const g=v=>{v.preventDefault(),window.location.href=Ss(1,h)},x=()=>{p(!m),y(v=>v+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[l("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(lc,{className:"w-5 h-5"})}),n(pr,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),l("div",{className:"flex items-center gap-4 mb-6",children:[l("form",{onSubmit:g,className:"relative flex-1 max-w-md",children:[n(On,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:h,onChange:v=>u(v.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:m?"Collapse All":"Expand All"})]}),l("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&l("span",{children:[" ","matching “",s,"”",n(de,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(pr,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(v=>n(F0,{agent:v,defaultOpen:m,isAdmin:d},v.id))},f),o>1&&l("div",{className:"flex items-center justify-center gap-3 mt-8",children:[l("a",{href:a>1?Ss(a-1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a>1?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:[n(cc,{className:"w-4 h-4"}),"Prev"]}),l("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),l("a",{href:a<o?Ss(a+1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a<o?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:["Next",n(Ot,{className:"w-4 h-4"})]})]})]})})}),B0=Object.freeze(Object.defineProperty({__proto__:null,default:z0,loader:A0,meta:E0},Symbol.toStringTag,{value:"Module"}));async function Y0({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{message:r}=t;if(!r)return new Response(JSON.stringify({error:"message is required"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();console.log(`[editor-commit] Committing with message: "${r}" in ${s}`);const a=Vf(s);a&&console.log("[editor-commit] Initialized new git repository"),qf(s),console.log("[editor-commit] Staged all changes");const o=Gf(s,r);console.log(`[editor-commit] Created commit: ${o}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>Jm);i()}catch{}return new Response(JSON.stringify({success:!0,commitSha:o,initialized:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-commit] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const U0=Object.freeze(Object.defineProperty({__proto__:null,action:Y0},Symbol.toStringTag,{value:"Module"})),W0=["JSX","React","Element","ReactNode"];function H0(e){return e.returnType?W0.some(t=>e.returnType.includes(t)):!1}function J0(e){const t=[],r=[];for(const s of e)H0(s)?t.push(s):r.push(s);return{components:t,functions:r}}function V0({components:e,functions:t,scenarioCounts:r,testFileExistence:s}){const a=e.map(u=>{const m=r[u.name]||0;return{name:u.name,filePath:u.filePath,scenarioCount:m,status:m>0?"ok":"missing"}}),o=t.map(u=>{const m=u.testFile?s[u.testFile]??!1:!1;return{name:u.name,filePath:u.filePath,testFile:u.testFile,testFileExists:m,status:m?"ok":"missing"}}),i=a.filter(u=>u.status==="ok").length,c=a.length-i,d=o.filter(u=>u.status==="ok").length,h=o.length-d;return{components:a,functions:o,summary:{totalComponents:a.length,componentsOk:i,componentsMissing:c,totalFunctions:o.length,functionsOk:d,functionsMissing:h,allPassing:c===0&&h===0}}}async function q0(){const e=ge()||process.cwd(),t=O.join(e,".codeyam","glossary.json");let r;try{const m=K.readFileSync(t,"utf8");r=JSON.parse(m),Array.isArray(r)||(r=[])}catch{return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,totalFunctions:0,functionsOk:0,functionsMissing:0,allPassing:!0}})}if(r.length===0)return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,totalFunctions:0,functionsOk:0,functionsMissing:0,allPassing:!0}});const s=O.join(e,".codeyam","editor-step.json");let a=null;try{const m=K.readFileSync(s,"utf8");a=JSON.parse(m).featureStartedAt||null}catch{}const{components:o,functions:i}=J0(r),c={},d=await $e();if(d)try{const{project:m}=await Ie(d),p=Te();let f=p.selectFrom("editor_scenarios").select(["component_name"]).select(p.fn.count("id").as("count")).where("project_id","=",m.id).where("component_name","is not",null).groupBy("component_name");if(a){const g=a.replace("T"," ").replace(/\.\d{3}Z$/,"");f=f.where("created_at",">=",g)}const y=await f.execute();for(const g of y)g.component_name&&(c[g.component_name]=Number(g.count))}catch{}const h={};for(const m of i)m.testFile&&(h[m.testFile]=K.existsSync(O.join(e,m.testFile)));const u=V0({components:o,functions:i,scenarioCounts:c,testFileExistence:h});return Response.json(u)}const G0=Object.freeze(Object.defineProperty({__proto__:null,loader:q0},Symbol.toStringTag,{value:"Module"}));async function K0({request:e}){try{const t=await e.json(),{pid:r,signal:s="SIGTERM",commitSha:a}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Co(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,c=500,d=Date.now();let h=!0;for(;h&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,c)),h=Co(r);if(h){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(a)try{await Rt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function Co(e){try{return process.kill(e,0),!0}catch{return!1}}const Q0=Object.freeze(Object.defineProperty({__proto__:null,action:K0},Symbol.toStringTag,{value:"Module"})),Z0=Mr(import.meta.url),X0=Z.dirname(Z0),ey=Z.resolve(X0,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function ty(e){const t=[],r=new Set;for(const s of e.split(`
275
+ `)){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const c of i.content){if(typeof c!="object"||c===null)continue;const d=c;if(d.type!=="tool_use")continue;const h=String(d.name||""),u=d.input||{};if(h==="Write"||h==="Edit"){const m=String(u.file_path||"");if(m.includes(".claude/rules/")){const p=m.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${h}:${p}`;r.has(f)||(r.add(f),t.push({action:h==="Write"?"created":"modified",filePath:p}))}}else if(h==="Bash"){const m=String(u.command||"");if(m.includes("codeyam memory touch")){const p=`touch:${m}`;r.has(p)||(r.add(p),t.push({action:"touched",filePath:m}))}}}}return t}async function ny({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{sessionId:r}=t;if(!r)return Response.json({error:"Missing required field: sessionId"},{status:400});const s=await ol(),a=s?Z.join(cr,s):null;let o=a?Z.join(a,`${r}.log`):"";if((!o||!$t(o))&&(o=Z.join(cr,`${r}.log`)),!$t(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await js(o,"utf-8");let c=a?Z.join(a,`${r}.context`):"";(!c||!$t(c))&&(c=Z.join(cr,`${r}.context`));let d=null;if($t(c))try{d=await js(c,"utf-8")}catch{}const h=ty(i),m=d?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>d.toLowerCase().includes(x)):!1,p=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+p,y=Z.join(ey,f);await $c(y,{recursive:!0}),await _n(Z.join(y,"agent-log.jsonl"),i),d&&await _n(Z.join(y,"context.md"),d),await _n(Z.join(y,"rule-changes.json"),JSON.stringify(h,null,2)),await _n(Z.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:m,ruleChangeCount:h.length},null,2));const g=Z.relative(process.cwd(),y);return console.log(`[api.save-fixture] Saved fixture to ${g}`),Response.json({success:!0,fixturePath:g})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const ry=Object.freeze(Object.defineProperty({__proto__:null,action:ny},Symbol.toStringTag,{value:"Module"}));async function sy({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=ge();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=Z.join(r,".codeyam","captures","screenshots",t);try{await be.access(s);const a=await be.readFile(s),o=Z.extname(s).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(a,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const ay=Object.freeze(Object.defineProperty({__proto__:null,loader:sy},Symbol.toStringTag,{value:"Module"})),So={visual:{label:"VISUAL",bgColor:"#f9f9f9",textColor:"#9040f5"},library:{label:"LIBRARY",bgColor:"#f9f9f9",textColor:"#06b6d5"},type:{label:"TYPE",bgColor:"#ffe1e1",textColor:"#db2627"},other:{label:"OTHER",bgColor:"#f9f9f9",textColor:"#646464"}};function ga({type:e,className:t=""}){const r=So[e]||So.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const oy={analyzer:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},capture:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},running:{bgColor:"#e8ffe6",textColor:"#00925d",borderColor:"#c3f3bf"},error:{bgColor:"#fee2e2",textColor:"#991b1b",borderColor:"#fecaca"}};function sr({variant:e,pid:t,label:r,className:s=""}){const a=oy[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${s}`,style:{backgroundColor:a.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:a.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:a.textColor},children:o})})}let ko=!1;function iy(){if(ko)return;const e=document.createElement("style");e.textContent=`
276
+ @keyframes strongPulse {
277
+ 0%, 100% { opacity: 0.2; }
278
+ 50% { opacity: 1; }
279
+ }
280
+ `,document.head.appendChild(e),ko=!0}function ya({size:e="medium",className:t=""}){typeof document<"u"&&iy();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:s,centerDotSize:a,gap:o}=r[e];return l("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const ly=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function cy({request:e,context:t,params:r}){var U,H,D,M,Q,W,F,te;let s=t.analysisQueue;s||(s=await Pt());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,c=r.tab||"current";if(!s)return G({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:c,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=s.getState(),h=await $e();let u=null;if(h&&((U=d==null?void 0:d.currentlyExecuting)!=null&&U.commitSha)){const{project:z,branch:L}=await Ie(h),V=await br({projectId:z.id,branchId:L.id,shas:[d.currentlyExecuting.commitSha]});u=V&&V.length>0?V[0]:null}else u=await yn();const m=async z=>{const L=await tn(z);if(!L)return null;const{getAnalysesForEntity:V}=await Promise.resolve().then(()=>Cu),B=await V(z,!1);return{...L,analyses:B||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async z=>{const L=[];if(z.entityShas&&z.entityShas.length>0){const V=z.entityShas.map(X=>m(X)),B=await Promise.all(V);L.push(...B.filter(X=>X!==null))}return{...z,entities:L}}));let f=null;if(d!=null&&d.currentlyExecuting){const z=d.currentlyExecuting,L=[];if(z.entityShas&&z.entityShas.length>0){const V=z.entityShas.map(X=>m(X)),B=await Promise.all(V);L.push(...B.filter(X=>X!==null))}f={...z,entities:L}}const y=f?p.filter(z=>z.id!==f.id):p,g=((D=(H=u==null?void 0:u.metadata)==null?void 0:H.currentRun)==null?void 0:D.currentEntityShas)||[],v=(await Promise.all(g.map(z=>m(z)))).filter(z=>z!==null),b=[];if(h)try{const{project:z,branch:L}=await Ie(h),V=await br({projectId:z.id,branchId:L.id,limit:100});for(const B of V){const X=((M=B.metadata)==null?void 0:M.historicalRuns)||[];b.push(...X)}}catch(z){console.error("[activity.tsx] Failed to load historical runs from commits:",z)}const N=[...b].sort((z,L)=>{const V=z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt||"";return(L.lastCaptureAt||L.analysisCompletedAt||L.archivedAt||L.createdAt||"").localeCompare(V)}),w=(o-1)*i,E=w+i,C=N.slice(w,E),S=Math.ceil(N.length/i),k=await Promise.all(C.map(async z=>{const L=z.currentEntityShas||[];if(L.length===0)return{...z,entities:[]};const V=await Promise.all(L.map(B=>m(B)));return{...z,entities:V.filter(B=>B!==null)}})),P=!!f,I=y.length,j=N.filter(z=>{const L=!!z.failedAt,V=z.readyToBeCaptured,B=z.capturesCompleted??0,X=V===void 0?!0:V===0||B>=V;return!L&&!!z.analysisCompletedAt&&X}),A=new Set(((Q=f==null?void 0:f.entities)==null?void 0:Q.map(z=>z.sha))||[]),T=j.filter(z=>!(z.currentEntityShas||[]).some(V=>A.has(V))),$=(await Promise.all(T.slice(0,3).map(async z=>{const L=z.currentEntityShas||[];if(L.length===0)return{run:z,entities:[]};const V=await Promise.all(L.map(B=>m(B)));return{run:z,entities:V.filter(B=>B!==null)}}))).flatMap(({run:z,entities:L})=>L.map(V=>({...V,runId:z.id,completedAt:z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt})));let J=[],q=null,Y=null;if((F=(W=u==null?void 0:u.metadata)==null?void 0:W.currentRun)!=null&&F.analysisCompletedAt&&v.length>0){const z=v[0].sha;q=v[0];const L=await Dr(z);L&&L.length>0&&L[0].scenarios&&(J=L[0].scenarios,Y=L[0].status)}return G({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(te=u==null?void 0:u.metadata)==null?void 0:te.currentRun,historicalRuns:k,totalHistoricalRuns:N.length,currentPage:o,totalPages:S,projectSlug:h,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:v,tab:c,hasCurrentActivity:P,queuedCount:I,recentCompletedEntities:$,hasMoreCompletedRuns:T.length>3,currentEntityScenarios:J,currentEntityForScenarios:q,currentAnalysisStatus:Y})}function dy({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:s}){const a=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:s>0,count:s}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:a.map(o=>{const i=e===o.id;return n(de,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
281
+ relative pb-4 px-2 text-sm transition-colors cursor-pointer
282
+ ${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
283
+ `,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
284
+ inline-block w-2 h-2 rounded-full
285
+ ${i?"":"bg-gray-400"}
286
+ `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function uy({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:c,currentEntityScenarios:d,currentEntityForScenarios:h,currentAnalysisStatus:u}){var R,$,J,q;const[m,p]=_({}),[f,y]=_({isKilling:!1,current:0,total:0}),g=mt(),x=!!e,v=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),N=b&&!!(t!=null&&t.capturePid),w=!b,E=x,C=d||[],{lastLine:S}=kt(s,E);ee(()=>{if(!t)return;const Y=[t.analyzerPid,t.capturePid].filter(M=>!!M);if(Y.length===0)return;let U=!0;const H=async()=>{try{const Q=await(await fetch(`/api/process-status?pids=${Y.join(",")}`)).json();if(Q.processes&&U){const W={};Q.processes.forEach(F=>{W[F.pid]={isRunning:F.isRunning,processName:F.processName}}),p(W)}}catch(M){U&&console.error("Failed to fetch process statuses:",M)}};H();const D=setInterval(()=>void H(),5e3);return()=>{U=!1,clearInterval(D)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[k,P]=_(!1),[I,j]=_(!1);ee(()=>{v.length<=3&&k&&P(!1)},[v.length,k]),ee(()=>{i.length<=3&&I&&j(!1)},[i.length,I]);const A=k?v:v.slice(0,3),T=v.length>3;return l("div",{className:"flex flex-col gap-[45px]",children:[E?l("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[l("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(dt,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:N?"Capturing...":"Analyzing..."})]}),A.map(Y=>l("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[l("div",{className:"flex items-center gap-3",children:[n("div",{children:n(et,{type:Y.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col gap-[1px]",children:[l("div",{className:"flex items-center gap-[14px]",children:[n(de,{to:`/entity/${Y.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:Y.name}),Y.entityType&&n(ga,{type:Y.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:Y.filePath,children:Y.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},Y.sha)),T&&!k&&l("button",{onClick:()=>P(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",v.length-3," more"," ",v.length-3===1?"entity":"entities"]}),k&&T&&n("button",{onClick:()=>P(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),N&&C&&C.length>0&&h&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:C.map(Y=>{var F,te,z,L;if(!Y.id)return null;const U=(te=(F=Y.metadata)==null?void 0:F.screenshotPaths)==null?void 0:te[0],H=(z=Y.metadata)==null?void 0:z.noScreenshotSaved,D=U&&!H,M=(L=u==null?void 0:u.scenarios)==null?void 0:L.find(V=>V.name===Y.name),W=M&&M.screenshotStartedAt&&!M.screenshotFinishedAt||!D&&!H;return n(de,{to:`/entity/${h.sha}/scenarios/${Y.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:W?"#f9f9f9":void 0,borderColor:W?"#efefef":"#ccc"},children:D?n(Ge,{screenshotPath:U,alt:Y.name,className:"w-full h-full object-contain bg-gray-100"}):W?n("div",{className:"w-full h-full flex items-center justify-center",children:n(ya,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},Y.id)})}),S&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:S}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(sr,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(w||((R=m[t.analyzerPid])==null?void 0:R.isRunning))&&n(sr,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(sr,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(N||(($=m[t.capturePid])==null?void 0:$.isRunning))&&n(sr,{variant:"running"})]}),(((J=m[t==null?void 0:t.analyzerPid])==null?void 0:J.isRunning)||((q=m[t==null?void 0:t.capturePid])==null?void 0:q.isRunning))&&n("button",{onClick:()=>{const Y=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(D=>{var M;return!!D&&((M=m[D])==null?void 0:M.isRunning)});if(Y.length===0)return;const U=Y.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${U})?`))return;y({isKilling:!0,current:1,total:Y.length}),(async()=>{for(let D=0;D<Y.length;D++){const M=Y[D];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:M,commitSha:a||""})})}catch(Q){console.error(`Failed to kill process ${M}:`,Q)}D<Y.length-1&&y({isKilling:!0,current:D+2,total:Y.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(qo,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),l("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(de,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(de,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),l(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&l("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),l("div",{className:"flex flex-col gap-4",children:[(I?i:i.slice(0,3)).map(Y=>{var D;const U=(D=Y.analyses)==null?void 0:D[0],H=(U==null?void 0:U.scenarios)||[];return U==null||U.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:l("div",{className:"flex flex-col gap-[15px]",children:[l("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(et,{type:Y.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[n(de,{to:`/entity/${Y.sha}`,className:"hover:underline cursor-pointer",title:Y.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:Y.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:Y.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:Y.filePath,children:Y.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:M=>{M.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),H.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:H.map(M=>{var te,z,L;if(!M.id)return null;const Q=(z=(te=M.metadata)==null?void 0:te.screenshotPaths)==null?void 0:z[0],W=(L=M.metadata)==null?void 0:L.noScreenshotSaved,F=Q&&!W;return l("div",{className:"shrink-0 flex flex-col gap-2",children:[n(de,{to:`/entity/${Y.sha}/scenarios/${M.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:F?"#f3f4f6":"#FAFAFA",borderColor:F?"#d1d5db":"#BCCDD3",borderStyle:F?"solid":"dashed"},onMouseEnter:V=>{F&&(V.currentTarget.style.borderColor="#005C75",V.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:V=>{V.currentTarget.style.borderColor=F?"#d1d5db":"#BCCDD3",V.currentTarget.style.boxShadow="none"},children:F?n(Ge,{screenshotPath:Q,alt:M.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M.name})]},M.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},Y.sha)}),i.length>3&&!I&&l("button",{onClick:()=>j(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),I&&i.length>3&&n("button",{onClick:()=>j(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function hy({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(hc,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),l(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[s,a]=_(null),[o,i]=_(null),[c,d]=_(null),[h,u]=_(!1),[m,p]=_(!1),[f,y]=_(new Set),g=mt();ee(()=>{e.length<=3&&m&&p(!1)},[e.length,m]);const x=C=>{a(C)},v=(C,S)=>{C.preventDefault(),i(S)},b=async(C,S)=>{if(C.preventDefault(),!s){i(null);return}const k=e.findIndex(j=>j.id===s);if(k===-1){a(null),i(null);return}if(k===S){a(null),i(null);return}const P=k<S?"down":"up",I=Math.abs(S-k);u(!0);try{for(let j=0;j<I;j++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:P})});g.revalidate()}catch(j){console.error("Failed to reorder job:",j)}finally{u(!1),a(null),i(null)}},N=()=>{h||(a(null),i(null))},w=async C=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:C})}),window.location.reload()}catch(S){console.error("Failed to cancel job:",S)}},E=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(C){console.error("Failed to cancel jobs:",C)}};return l("div",{children:[l("div",{className:"flex items-center justify-between mb-4",children:[l("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void E(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),l("div",{className:"flex flex-col gap-3",children:[(m?e:e.slice(0,3)).map(C=>{var T,R,$,J;const S=e.findIndex(q=>q.id===C.id),k=c===S,P=s===C.id,I=o===S,j=f.has(C.id),A=((T=C.entities)==null?void 0:T.length)>0?j?C.entities:C.entities.slice(0,3):[];return l("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:P||h?.5:1,transform:I&&s!==null&&!P?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:h?"not-allowed":P?"grabbing":"grab"},onMouseEnter:()=>d(S),onMouseLeave:()=>d(null),draggable:!h,onDragStart:q=>{x(C.id),q.dataTransfer.effectAllowed="move"},onDragOver:q=>v(q,S),onDrop:q=>void b(q,S),onDragEnd:N,children:[l("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(mc,{size:16,style:{color:"#005C75"}}),l("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",S+1]})]}),l("div",{className:"flex flex-col gap-2 mt-8",children:[A.length>0?l(ue,{children:[A.map(q=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(et,{type:q.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(de,{to:`/entity/${q.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:q.name}),q.entityType&&n(ga,{type:q.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:q.filePath})]})]})})},q.sha)),((R=C.entities)==null?void 0:R.length)>3&&n("button",{onClick:()=>{y(q=>{const Y=new Set(q);return Y.has(C.id)?Y.delete(C.id):Y.add(C.id),Y})},className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"40px",fontSize:"12px",color:"#646464",fontWeight:500},children:j?"Show less":`+${C.entities.length-3} more ${C.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(fr,{size:18,style:{color:"#8e8e8e"}})}),l("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:(($=C.entityNames)==null?void 0:$[0])||(C.type==="analysis"?"Analysis Job":C.type==="recapture"?"Recapture Job":C.type==="debug-setup"?"Debug Setup":C.type.charAt(0).toUpperCase()+C.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((J=C.filePaths)==null?void 0:J[0])||(C.filePaths&&C.filePaths.length>1?`${C.filePaths.length} files`:C.entityShas&&C.entityShas.length>0?`${C.entityShas.length} ${C.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),l("div",{className:"flex items-center justify-end gap-2 mt-1",children:[k&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(pc,{size:20})}),n("button",{onClick:()=>void w(C.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},C.id)}),e.length>3&&!m&&l("button",{onClick:()=>p(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),m&&e.length>3&&n("button",{onClick:()=>p(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function my({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:a,onShowLogs:o}){if(t===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(fc,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),l(de,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,c]=_(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(m=>{d.push({...m,runCreatedAt:u.createdAt})})});const h=i?d:d.slice(0,3);return l("div",{className:"flex flex-col gap-4",children:[h.map(u=>{var y;const m=(y=u.analyses)==null?void 0:y[0],p=(m==null?void 0:m.scenarios)||[],f=!u.isUncommitted;return l("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[l("div",{className:"flex items-start justify-between mb-3",children:[l("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(et,{type:u.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(de,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),p.length>0&&l("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[p.slice(0,8).map(g=>{var N,w,E;if(!g.id)return null;const x=(w=(N=g.metadata)==null?void 0:N.screenshotPaths)==null?void 0:w[0],v=(E=g.metadata)==null?void 0:E.noScreenshotSaved,b=x&&!v;return n(de,{to:`/entity/${u.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:b?"#ccc":"#BCCDD3",borderStyle:b?"solid":"dashed"},children:b?n(Ge,{screenshotPath:x,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},g.id)}),p.length>8&&l("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",p.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),d.length>3&&!i&&l("button",{onClick:()=>c(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&n("button",{onClick:()=>c(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const py=He(function(){const t=qe(),r=Ho(),[s,a]=_(!1);ft({source:"activity-page"});const o=r.tab||"current";return t?l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(dy,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(uy,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>a(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(hy,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(my,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n(It,{projectSlug:t.projectSlug,onClose:()=>a(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),fy=Object.freeze(Object.defineProperty({__proto__:null,default:py,loader:cy,meta:ly},Symbol.toStringTag,{value:"Module"}));async function ml(e,t,r){var w,E;await Je();const s=await At({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=ge();if(!a)throw new Error("Project root not found");const o=O.join(a,".codeyam","config.json"),i=JSON.parse(K.readFileSync(o,"utf8")),{projectSlug:c}=i;if(!c)throw new Error("Project slug not found in config");const d=zr(c);try{K.writeFileSync(d,"","utf8")}catch{}const{project:h}=await Ie(c),u=((w=h.metadata)==null?void 0:w.packageManager)||"npm",m=3112,p=ht(c),f=((E=h.metadata)==null?void 0:E.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${c}`);const y=i.environmentVariables||[],g=Bd({filePath:s.filePath,webapps:f,environmentVariables:y,port:m,packageManager:u});await gn(e,C=>{if(C&&(C.readyToBeCaptured=!0,C.scenarios))for(const S of C.scenarios)(!t||S.name===t)&&(delete S.screenshotStartedAt,delete S.screenshotFinishedAt,delete S.interactiveStartedAt,delete S.interactiveFinishedAt,delete S.error,delete S.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t,prepOnly:!0}),v=g.startCommand,b={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:p}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${p}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:v,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${m}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:p,projectSlug:c,port:m,packageManager:u,framework:g.framework,instructions:b}}async function gy({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),a=r.searchParams.get("scenarioId")||void 0;if(!s)return G({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await Pt()),!o)return G({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await ml(s,a,o);return G({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),G({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function yy({request:e,context:t}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return G({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return G({error:"Missing required field: analysisId"},{status:400});const i=await ml(a,o,r);return G({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),G({error:"Failed to setup debug environment",details:a},{status:500})}}const xy=Object.freeze(Object.defineProperty({__proto__:null,action:yy,loader:gy},Symbol.toStringTag,{value:"Module"}));function by({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=ge()||process.cwd(),a=O.resolve(s,r);if(!a.startsWith(s+O.sep)&&a!==s)return new Response("Path outside project root",{status:403});try{const o=K.readFileSync(a,"utf8");return new Response(o,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("File not found",{status:404})}}const vy=Object.freeze(Object.defineProperty({__proto__:null,loader:by},Symbol.toStringTag,{value:"Module"})),wy=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function pl(e){const t=Dc("sha256",wy);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function Ny(e,t){return t===pl(e)}async function Cy({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return G({success:!1,error:"Unlock code is required"},{status:400});const s=await $e();return s?Ny(s,r)?(await mn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),G({success:!0})):G({success:!1,error:"Invalid unlock code"},{status:400}):G({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),G({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const Sy=Object.freeze(Object.defineProperty({__proto__:null,action:Cy},Symbol.toStringTag,{value:"Module"}));async function ky({request:e,context:t}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return G({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return G({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return G({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${a} with width ${i}`);const c=await ng(a,i,r);return console.log("[API] Recapture queued",c),G({success:!0,message:"Recapture queued",...c})}catch(s){return console.log("[API] Error during recapture:",s),G({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const Ey=Object.freeze(Object.defineProperty({__proto__:null,action:ky},Symbol.toStringTag,{value:"Module"}));function Ay(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(Py).map(a=>a===""?[]:a.split("/")).reduce((a,o)=>{const i=[];for(let c=0;c<Math.min(a.length,o.length)&&a[c]===o[c];c++)i.push(a[c]);return i}).join("/")}function Py(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(_y(s))r.pop();else break}return r.join("/")}function _y(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function My({request:e}){const r=new URL(e.url).searchParams.getAll("paths");if(r.length===0)return Response.json({error:"Missing required query parameter: paths"},{status:400});const s=Ay(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const jy=Object.freeze(Object.defineProperty({__proto__:null,loader:My},Symbol.toStringTag,{value:"Module"}));function Ty(e,t){var i,c,d,h,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(m=>m.scenarios&&m.scenarios.length>0);if(!r){const m=!!((c=e.metadata)!=null&&c.previousVersionWithAnalyses),p=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||p?s?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const a=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((h=e.metadata)!=null&&h.previousVersionWithAnalyses)||a){const m=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return s&&!m?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:s?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return s?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function $y(e){return Ty(e).hasOutdatedSimulations}function Kr(e,t,r,s,a){var q,Y,U,H,D,M,Q,W;const o=(q=t==null?void 0:t.scenarios)==null?void 0:q.find(F=>F.name===e.name),i=!!(o!=null&&o.startedAt),c=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),h=!!(o!=null&&o.finishedAt),u=1800*1e3,m=c&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!((U=(Y=e.metadata)==null?void 0:Y.screenshotPaths)!=null&&U[0])||!!((H=e.metadata)!=null&&H.executionResult),f=c&&!d,y=o==null?void 0:o.error,g=(M=(D=e.metadata)==null?void 0:D.executionResult)==null?void 0:M.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const F of t.errors)x.push({source:`${F.phase} phase`,message:F.message});if(t!=null&&t.steps)for(const F of t.steps)F.error&&x.push({source:F.name,message:F.error});const v=!p&&!y&&!g&&x.length>0,b=!!(y||g||m||v),N=m?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(v?`Analysis error: ${x[0].message}`:null),w=m?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(g==null?void 0:g.stack)||null,C=(s&&a?a.jobs.some(F=>{var te;return((te=F.entityShas)==null?void 0:te.includes(s))||F.type==="analysis"&&F.entityShas&&F.entityShas.length===0})||((W=(Q=a.currentlyExecuting)==null?void 0:Q.entityShas)==null?void 0:W.includes(s)):!1)&&!i&&!b||!!(o!=null&&o.analyzing)&&!i&&!b,S=i&&!c&&!h&&!b,k=(C||S||f)&&!b,P=(C||S)&&r===!1&&!p;let I;P?I="crashed":b?I="error":p||h?I="completed":f?I="capturing":S?I="starting":C?I="queued":I="pending";let j="📷",A="pending",T=!1,R=`Not captured: ${e.name}`;const $="border-gray-300",J=b||P?"bg-red-50":"bg-white";return b||P?(j="⚠️",A="error",R=`Error: ${P?"Analysis process crashed":N||"Unknown error"}`):C?(j="⋯",A="queued",R=`Queued: ${e.name}`):S?(j="⋯",A="starting",T=!0,R=`Starting server for ${e.name}...`):f&&!b?(j="⋯",A="capturing",T=!0,R=`Capturing ${e.name}...`):p&&(j="✓",A="completed",R=e.name),{hasError:b||P,errorMessage:P?"Analysis process crashed":N,errorStack:P?"Process terminated unexpectedly before completing analysis":w,isCapturing:f,isCaptured:p,hasCrashed:P,isAnalyzing:k,isQueued:C,isServerStarting:S,status:I,icon:j,iconType:A,shouldSpin:T,title:R,borderColor:$,bgColor:J}}function fl({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var w,E,C,S,k,P;const o=Kr(e,void 0,void 0,t,void 0),i=(w=e.metadata)==null?void 0:w.executionResult,c=!!i,h=(((C=(E=e.metadata)==null?void 0:E.data)==null?void 0:C.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((k=(S=i==null?void 0:i.sideEffects)==null?void 0:S.consoleOutput)==null?void 0:k.length)||0,p=((P=i==null?void 0:i.timing)==null?void 0:P.duration)||0;let f=0;h>0&&f++,h>2&&f++,u&&f++,m>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:c?a?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},v=s?`border-2 ${x.border}`:"",b=Array.from({length:3},(I,j)=>n("div",{className:`w-1 h-1 rounded-full ${j<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},j)),N=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:c?`${e.name}
287
+ ${h} args → ${u?"value":"void"}${m>0?` (${m} logs)`:""}
288
+ ${p}ms`:`Not executed: ${e.name}`;return l(de,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${v} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:N,onClick:I=>I.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:o.hasError?"⚠":c?"ƒ":"○"}),c&&!o.hasError&&l("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:h}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),c&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),c&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),c&&!o.hasError&&m>0&&r==="medium"&&l("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function Js({size:e=24,className:t=""}){return l("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function Eo({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:a,size:o="medium",cacheBuster:i,className:c="",viewMode:d}){var g,x;if(t.entityType==="library")return n(fl,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=Kr(e,r,a,t.sha,s),m=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${m.containerClass} ${c}`,f=()=>{const v=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${v}/${d}`:v};if(u.isCaptured){const v=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(de,{to:f(),className:`${p} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(Ge,{screenshotPath:v,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const v={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},b=n(ya,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return l("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Js,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(gc,{...v});default:return b}};return n(de,{to:f(),className:`${p} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:m.iconSize,children:y()})})}const cn=70;function Ry({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:c,entity:d,queueState:h,processIsRunning:u,isEntityAnalyzing:m,areScenariosStale:p,viewMode:f,setViewMode:y,isBreakdownView:g}){var T,R,$,J,q,Y;const x=ve(null),[v,b]=_(new Set),[N,w]=_(!1);ee(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const E=U=>`/entity/${a}/scenarios/${U}`,C=U=>{b(H=>{const D=new Set(H);return D.has(U)?D.delete(U):D.add(U),D})},S=(U,H=2)=>{const M=U.split(`
289
+ `).slice(0,H).join(" ").trim();return M.length>cn?M.substring(0,cn-3):(U.split(`
290
+ `).length>H||U.length>M.length,M)},k=re(()=>{var H;if(!((H=r==null?void 0:r.metadata)!=null&&H.executionFlows)||!(r!=null&&r.scenarios))return null;const U=r.scenarios.filter(D=>{var M;return!((M=D.metadata)!=null&&M.sameAsDefault)});return ha(r.metadata.executionFlows,U)},[r]),P=(k==null?void 0:k.totalFlows)||0,I=(k==null?void 0:k.coveredFlows)||0,j=(k==null?void 0:k.coveragePercentage)||0;(T=d==null?void 0:d.metadata)!=null&&T.defaultWidth||(R=r==null?void 0:r.metadata)!=null&&R.defaultWidth;const A=($=r==null?void 0:r.status)!=null&&$.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return l("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&l("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),l("div",{className:"grid grid-cols-2 gap-2",children:[l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((J=e[0])==null?void 0:J.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(j),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((q=e[0])==null?void 0:q.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[I,"/",P]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),l(de,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((Y=e[0])==null?void 0:Y.id)}`:`/entity/${a}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n(de,{to:`/entity/${a}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&l("div",{className:"py-3 flex items-center justify-between",children:[l("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),A&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:A})]}),m&&(p||e.length===0)?l("div",{className:"",children:[l("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[l("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((U,H)=>{const D=!g&&(s==null?void 0:s.id)===U.id,M=v.has(U.id||"");return U.id?l(de,{to:E(U.id),ref:D?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${D?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(Eo,{scenario:U,entity:{sha:a,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${M?"":"line-clamp-1"}`,children:U.name}),U.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[M?U.description:S(U.description),!M&&U.description.length>cn&&l(ue,{children:["...",n("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),C(U.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),M&&U.description.length>cn&&n("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),C(U.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},H):null})})}),t.length>0&&!(m&&p)&&l("div",{className:"border-t border-[#e1e1e1] pt-3",children:[l("button",{onClick:()=>w(!N),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${N?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),N&&l("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((U,H)=>{const D=!g&&(s==null?void 0:s.id)===U.id,M=v.has(U.id||"");return U.id?l(de,{to:`/entity/${a}/scenarios/${U.id}`,ref:D?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${D?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(Eo,{scenario:U,entity:{sha:a,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${M?"":"line-clamp-1"}`,children:U.name}),U.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[M?U.description:S(U.description),!M&&U.description.length>cn&&l(ue,{children:["...",n("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),C(U.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),M&&U.description.length>cn&&n("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),C(U.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},H):null})})]})]})]})}function Iy({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:c=!1,saveMessage:d=null,showDeleteConfirm:h=!1,onShowDeleteConfirm:u,isDeleting:m=!1,deleteError:p=null}){const[f,y]=_(""),g=async()=>{await r(f)},x=async v=>{await s(f,v),v||y("")};return l("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[l("div",{className:"border-b border-[#e1e1e1] pb-3",children:[l("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(de,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),l("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[l("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:v=>y(v.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),l("button",{onClick:()=>void g(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&l("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),l("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:a,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(de,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),l("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:c||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:c?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:c||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&l(ue,{children:[h?l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),l("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:m,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:m?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:m,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function Dy({scenario:e,analysis:t,entity:r}){var i,c,d;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((d=(c=e.metadata)==null?void 0:c.data)==null?void 0:d.argumentsData)||[],o=h=>{var y,g,x;if(!h)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],m=((y=h.sideEffects)==null?void 0:y.consoleOutput)||[];m.length>0&&(u.push(`Console Output: ${m.length} log ${m.length===1?"entry":"entries"} captured`),m.forEach(v=>{u.push(` [${v.level.toUpperCase()}] ${v.args.join(" ")}`)}));const p=((g=h.sideEffects)==null?void 0:g.fileWrites)||[];p.length>0&&(u.push(`
291
+ File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(v=>{u.push(` ${v.operation}: ${v.path}${v.size?` (${v.size} bytes)`:""}`)}));const f=((x=h.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
292
+ API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(v=>{u.push(` ${v.method} ${v.url}${v.status?` → ${v.status}`:""}${v.duration?` (${v.duration}ms)`:""}`)})),h.error&&u.push(`
293
+ Error: ${h.error.name||"Error"}: ${h.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
294
+ `)};return l("div",{className:"flex w-full h-full gap-0",children:[l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(a,null,2)})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:s?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:s.returnValue!==void 0?JSON.stringify(s.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(s)})})]})]})}const Vt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function ar({scenarioId:e,analysisId:t}){const[r,s]=_(!1),[a,o]=_(!1),[i,c]=_(null),[d,h]=_(!1),u=e||t;if(!u)return null;const m=`/codeyam-diagnose ${u}`,p=async()=>{o(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);c(x),s(!0)}catch(y){console.error("Screenshot capture failed:",y),s(!0)}finally{o(!1)}},f=()=>{s(!1),c(null)};return l(ue,{children:[l("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Vt.heading},children:"Claude can help debug this error."}),n("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:Vt.subtext},children:"Simply run this command in Claude Code:"}),l("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:Vt.commandBoxBg,borderColor:Vt.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[n("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:Vt.commandBoxText},children:m}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(m),h(!0),setTimeout(()=>h(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":Vt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(pt,{size:14}):n(wt,{size:14})})]}),l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void p(),disabled:a,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:Vt.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(ti,{isOpen:r,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:t,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Ao=1440,or=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],bt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function gl({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:c,hasAnApiKey:d=!0,processIsRunning:h,queueState:u}){var B,X,ce,we,ae,he,ye,Me,je,De,Le;const m=Oe(),[p,f]=_(!1),[y,g]=_(!1),[x,v]=_({name:"Desktop",width:Ao,height:900}),[b,N]=_(Ao),[w,E]=_(1),{customSizes:C,addCustomSize:S,removeCustomSize:k}=Jr(c),P=re(()=>[...or,...C],[C]),I=(Ee,ne)=>{N(Ee);const xe=P.find(Ce=>Ce.width===Ee&&Ce.height===ne);v({name:(xe==null?void 0:xe.name)||"Custom",width:Ee,height:ne})},j=Ee=>{N(Ee.width),v({name:Ee.name,width:Ee.width,height:Ee.height})},A=Ee=>{S(Ee,x.width,x.height??900),g(!1),v(ne=>({...ne,name:Ee}))},T=(Ee,ne)=>{N(Ee);const xe=P.find(Ce=>Ce.width===Ee&&Ce.height===ne);v(Ce=>({name:(xe==null?void 0:xe.name)||"Custom",width:Ee,height:Ce.height}))},R=(X=(B=e==null?void 0:e.metadata)==null?void 0:B.screenshotPaths)==null?void 0:X[0],$=re(()=>e?Kr(e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u]),J=re(()=>{var ne,xe;const Ee=[];if((ne=t==null?void 0:t.status)!=null&&ne.errors&&t.status.errors.length>0)for(const Ce of t.status.errors)Ee.push({source:`${Ce.phase} phase`,message:Ce.message,stack:Ce.stack});if((xe=t==null?void 0:t.status)!=null&&xe.steps)for(const Ce of t.status.steps)Ce.error&&Ee.push({source:Ce.name,message:Ce.error,stack:Ce.errorStack});return Ee},[(ce=t==null?void 0:t.status)==null?void 0:ce.errors,(we=t==null?void 0:t.status)==null?void 0:we.steps]),q=($==null?void 0:$.errorMessage)||null,Y=($==null?void 0:$.errorStack)||null,{interactiveServerUrl:U,isStarting:H,isLoading:D,showIframe:M,iframeKey:Q,onIframeLoad:W}=sn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:c,enabled:s==="interactive"}),F=re(()=>U||null,[U]),te=!i&&o&&e&&!((he=(ae=e.metadata)==null?void 0:ae.screenshotPaths)!=null&&he[0])&&((Me=(ye=t==null?void 0:t.status)==null?void 0:ye.scenarios)==null?void 0:Me.some(Ee=>Ee.name===e.name&&Ee.screenshotStartedAt&&!Ee.screenshotFinishedAt)),{lastLine:z}=kt(c,i||s==="interactive"||te||!1);if(!e){if(i&&r)return l(ue,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:l("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:te?"Capturing screenshots...":"Analyzing..."}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),z&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:z}),c&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),p&&c&&n(It,{projectSlug:c,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(J.length>0){const Ee=J.length===1?((je=J[0])==null?void 0:je.message)||"An error occurred during analysis.":`${J.length} errors occurred during analysis.`;return l(ue,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:bt.background,border:`2px solid ${bt.border}`},role:"alert",children:l("div",{className:"flex items-center gap-3",children:[n(Js,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:bt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",Ee," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:bt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(ar,{analysisId:t==null?void 0:t.id})})]})}),p&&c&&n(It,{projectSlug:c,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:l("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return l(ue,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
295
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
296
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
297
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
298
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
299
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||te&&!R)&&!q&&s==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:l("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[l("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:te?`Capturing ${r==null?void 0:r.name}`:`Analyzing ${r==null?void 0:r.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:te?`Taking screenshots for ${((De=t==null?void 0:t.scenarios)==null?void 0:De.length)||0} scenario${((Le=t==null?void 0:t.scenarios)==null?void 0:Le.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&l("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),z&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:l("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:z,children:z})]})]})}),c&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):s==="screenshot"&&(R||q)||s==="interactive"&&(F||H)||s==="data"?l(ue,{children:[q&&!R&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:bt.background,border:`2px solid ${bt.border}`,maxHeight:"50vh"},role:"alert",children:l("div",{className:"flex flex-col gap-3",children:[l("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:bt.text},children:[n(Js,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),l("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:bt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:bt.text},children:q})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(ar,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?l("div",{className:"flex-1 flex flex-col min-h-0",children:[F&&l("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(Gh,{presets:[...or],customSizes:C,currentWidth:x.width,currentHeight:x.height??900,scale:w,onSizeChange:I,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:k}),e&&r&&l(de,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),F&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${or[or.length-1].width}px`,width:"100%"},children:n(Wr,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:j,devicePresets:P})})}),n(qr,{scenarioId:e.id,scenarioName:e.name,iframeUrl:F,isStarting:H,isLoading:D,showIframe:M,iframeKey:Q,onIframeLoad:W,onScaleChange:E,onDimensionChange:T,projectSlug:c,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(Dy,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${b}px`},children:(R||!q)&&n(Ge,{screenshotPath:R,cacheBuster:a,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!R?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),l("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),l("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),z&&l("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:z})]}),c&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):q?l("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:l("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[l("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),l("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),l("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(de,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),l("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:q})})]}),Y&&l("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:Y})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(ar,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):J.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:J,title:"Analysis Error",description:J.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${J.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(ar,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):l("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),p&&c&&n(It,{projectSlug:c,onClose:()=>f(!1)}),y&&n(Hr,{width:x.width,height:x.height??900,onSave:A,onCancel:()=>g(!1)})]})}function Ly({analysis:e,entitySha:t}){mt();const[r,s]=_(e);ee(()=>{s(e)},[e]);const[a,o]=_(null),i=re(()=>{var m;if(!((m=r==null?void 0:r.metadata)!=null&&m.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(p=>{var f;return!((f=p.metadata)!=null&&f.sameAsDefault)});return ha(r.metadata.executionFlows,u)},[r]),c=re(()=>i?Tm(i):[],[i]),d=re(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var m;return!((m=u.metadata)!=null&&m.sameAsDefault)}):[],[r]),h=u=>{var p;const m=((p=u.metadata)==null?void 0:p.coveredFlows)||[];return i?i.executionFlows.filter(f=>m.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:l("div",{className:"p-6 space-y-6",children:[l("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),l("div",{className:"grid grid-cols-4 gap-4 text-center",children:[l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:`text-2xl font-bold ${i.coveragePercentage===100?"text-green-600":i.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[i.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:d.length===0?l("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(de,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,y,g;const m=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],p=h(u);return l("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Ge,{screenshotPath:m,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),l("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:l("div",{children:[n(de,{to:`/entity/${t}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((g=u.metadata)==null?void 0:g.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),p.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:p.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:l(de,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&l("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[l("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),l("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(u=>l("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),c.length>10&&l("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const m=a===u.id,p=u.usedInScenarios.length>0;return l("div",{children:[n("button",{onClick:()=>o(m?null:u.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:l("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:m?"▼":"▶"}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),p?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),m&&l("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&l("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>l("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},y))})]}),p&&l("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&l("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Po({hasIndirectBadge:e,onAnalyze:t}){return l(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),l("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function Oy({entity:e,history:t}){const[r,s]=_("entity"),[a,o]=_(new Set),i=t.filter(u=>u.analyses.length>0).length,c=re(()=>{const u=new Map;return t.forEach(m=>{m.analyses.forEach(p=>{(p.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{u.has(y.name)||u.set(y.name,[]),u.get(y.name).push({version:m,analysis:p,scenario:y})})})}),Array.from(u.entries()).map(([m,p])=>{var f;return{name:m,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),d=c.length,h=u=>{o(m=>{const p=new Set(m);return p.has(u)?p.delete(u):p.add(u),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:l("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:l("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[l("button",{onClick:()=>s("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),l("button",{onClick:()=>s("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?l("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,m)=>l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),l(de,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((p,f)=>{var g;const y=(p.scenarios??[]).filter(x=>{var v;return!((v=x.metadata)!=null&&v.sameAsDefault)});return n("div",{children:y.length===0?n(Po,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):l(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[p.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=p.metadata)==null?void 0:g.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[l("span",{className:"font-medium",children:["What Changed:"," "]}),p.metadata.scenarioChangesOverview]})}),y.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:y.map((x,v)=>{var w,E;const b=(E=(w=x.metadata)==null?void 0:w.screenshotPaths)==null?void 0:E[0],N=`${x.name}-${v}`;return l(de,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(Ge,{screenshotPath:b,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},N)})})})]})},p.id||f)})}):n(Po,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:c.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):c.map((u,m)=>{const p=a.has(u.name),f=p?u.versions:u.versions.slice(0,1),y=u.versions.length-1,g=u.versions[0];return g==null||g.version.sha,e==null||e.sha,l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),l("div",{className:"p-5 bg-white",children:[f.map((x,v)=>{var S,k;const{version:b,analysis:N,scenario:w}=x,E=(k=(S=w.metadata)==null?void 0:S.screenshotPaths)==null?void 0:k[0],C=v===0;return l("div",{className:`flex gap-5 items-start ${C?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(de,{to:`/entity/${b.sha}/scenarios/${w.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:E?n(Ge,{screenshotPath:E,alt:w.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),l("div",{className:"flex-1 flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[b.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),C&&u.versions.length>1&&l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),l(de,{to:`/entity/${b.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:b.sha.substring(0,8)})]}),N.createdAt&&l("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(N.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),N.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${b.sha}-${v}`)}),y>0&&l("button",{onClick:()=>h(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function _o({entity:e,analysisInfo:t,from:r}){const s=Oe(),a=s.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=c=>{c.preventDefault(),c.stopPropagation(),o&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(de,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:l("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Ge,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):n("div",{className:"w-[125px] h-full bg-[#efefef] flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n("span",{className:"text-[40px]",children:n(et,{type:e.entityType})})}),l("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(et,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&l("div",{className:"flex items-center gap-2 mt-2",children:[l("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?l(ue,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):l(ue,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Mo=e=>{var a,o,i;const t=((a=e.analysisStatus)==null?void 0:a.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,s=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:s}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:s}};function Fy({importedEntities:e,importingEntities:t}){const[r]=fn(),s=r.get("from"),a=Oe(),o=a.state!=="idle",i=e.length>0,c=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),h=p=>{const f=d(p);f.length!==0&&a.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,m=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>h(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(p=>n(_o,{entity:p,analysisInfo:Mo(p),from:s},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),m&&n("button",{onClick:()=>h(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),c?n("div",{className:"p-6 space-y-4",children:t.map(p=>n(_o,{entity:p,analysisInfo:Mo(p),from:s},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function zy({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(Fy,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function By({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Ln,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Ln({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,c]=_(r||t<2);if(ee(()=>{c(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return l("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):l("span",{children:[l("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","["]}),!i&&l("span",{children:[e.length,"]"]})]}),i?l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((h,u)=>n("div",{className:"py-0.5",children:n(Ln,{data:h,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const h=Object.keys(e);if(h.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=p=>Array.isArray(p)&&p.length>0;return l("span",{children:[l("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","{"]}),!i&&l("span",{children:[h.length,"}"]})]}),i?l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:h.map(p=>{const f=e[p],y=u(f),g=m(f);return n("div",{className:"py-0.5",children:y?n(xa,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(ba,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:s}):l(ue,{children:[l("span",{className:"text-orange-600",children:[p,": "]}),n(Ln,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},p)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function xa({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=_(s||r<2),c=Object.keys(t);return ee(()=>{i(s||r<2)},[s,r]),l(ue,{children:[l("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&l("span",{className:"text-gray-600",children:[c.length,"}"]})]}),o&&l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:c.map(d=>{const h=t[d],u=h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,m=Array.isArray(h)&&h.length>0;return n("div",{className:"py-0.5",children:u?n(xa,{propertyKey:d,value:h,depth:r+1,defaultExpanded:s,maxDepth:a}):m?n(ba,{propertyKey:d,value:h,depth:r+1,defaultExpanded:s,maxDepth:a}):l(ue,{children:[l("span",{className:"text-orange-600",children:[d,": "]}),n(Ln,{data:h,depth:r+2,defaultExpanded:s,maxDepth:a})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function ba({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=_(s||r<2);return ee(()=>{i(s||r<2)},[s,r]),l(ue,{children:[l("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&l("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&l(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((c,d)=>{const h=c!==null&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,u=Array.isArray(c)&&c.length>0;return n("div",{className:"py-0.5",children:h?n(xa,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:s,maxDepth:a}):u?n(ba,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:s,maxDepth:a}):n(Ln,{data:c,depth:r+2,defaultExpanded:s,maxDepth:a})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function ks({label:e,count:t,isActive:r,onClick:s,badgeColorActive:a,badgeTextActive:o}){return l("button",{onClick:s,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${a} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function jo({label:e,isActive:t,onClick:r,disabled:s=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:s,children:e})}function To({call:e,scenarioName:t}){const[r,s]=_(!1),[a,o]=_("system"),i=p=>new Date(p).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),c=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const y=[];return p&&y.push(`${p.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},h=re(()=>{var p,f,y,g,x;try{const v=JSON.parse(e.response);return(y=(f=(p=v.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&y.content?v.choices[0].message.content:(x=(g=v.content)==null?void 0:g[0])!=null&&x.text?v.content[0].text:e.response}catch{return e.response}},[e.response]),u=re(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=re(()=>{var p;if(t)return t;try{const f=JSON.parse(e.props);return((p=f==null?void 0:f.scenario)==null?void 0:p.name)||null}catch{return null}},[e.props,t]);return l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children:l("div",{className:"flex items-start justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),m&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:m}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),l("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),c(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:c(e.cost)})]}),l("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&l("div",{className:"border-t border-[#e1e1e1]",children:[l("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),a&&l("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[a==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),a==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),a==="response"&&l("div",{children:[e.error&&l("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:h})]}),a==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!a&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:l("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const $o=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function Yy({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var N,w,E,C,S,k,P,I,j;const[o,i]=_("entity"),[c,d]=_("analysis"),[h,u]=_(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[m,p]=_("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=re(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const A=[...a.entityCalls,...a.analysisCalls],T=A.filter($=>$.object_type==="entity"||$o.includes($.prompt_type)),R=A.filter($=>$.object_type!=="entity"&&!$o.includes($.prompt_type));return T.sort(($,J)=>J.created_at-$.created_at),R.sort(($,J)=>J.created_at-$.created_at),{entityLlmCalls:T,scenarioLlmCalls:R,totalLlmCalls:A.length}},[a]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(N=e==null?void 0:e.metadata)==null?void 0:N.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(w=t==null?void 0:t.metadata)==null?void 0:w.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(C=(E=e==null?void 0:e.metadata)==null?void 0:E.isolatedDataStructure)==null?void 0:C.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(S=t==null?void 0:t.metadata)==null?void 0:S.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(k=e==null?void 0:e.metadata)==null?void 0:k.importedExports,"External Dependencies":(P=e==null?void 0:e.metadata)==null?void 0:P.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(I=t==null?void 0:t.metadata)==null?void 0:I.scenariosDataStructure,description:"Structure template used across all scenarios"}],v=x.filter(A=>A.data!==void 0&&A.data!==null).length;let b=null;if(o==="entity"){const A=x.find(T=>T.id===c);A&&A.data!==void 0&&A.data!==null&&(b={title:A.title,description:A.description,data:A.data})}else if(o==="scenarios"&&h){const A=r.find(T=>(T.id||T.name)===h.scenarioId);A&&(b={title:A.name,description:A.description||"Scenario data and configuration",data:A.metadata})}return l("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:l("div",{className:"flex border-b border-gray-200 relative",children:[n(ks,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(ks,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(ks,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((j=t==null?void 0:t.metadata)==null?void 0:j.analyzerVersion)&&l("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?l("div",{className:"flex-1 min-h-0",children:[l("div",{className:"flex gap-4 mb-4",children:[l("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),l("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:m==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(A=>n(To,{call:A},A.id)):y.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):y.map(A=>n(To,{call:A},A.id))})]}):l("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?l(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),v===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(A=>{const T=A.data!==void 0&&A.data!==null;return n(jo,{label:A.title,isActive:c===A.id,onClick:()=>d(A.id),disabled:!T},A.id)})})]}):l(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),r.length===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):n("nav",{className:"space-y-1",children:r.map(A=>{const T=A.id||A.name,R=(h==null?void 0:h.scenarioId)===T;return n(jo,{label:A.name,isActive:R,onClick:()=>u({scenarioId:T})},T)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(Uy,{title:b.title,description:b.description,data:b.data}):o==="scenarios"&&r.length===0?n(Ro,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(Ro,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:s}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function Ro({title:e,description:t,onAnalyze:r}){return l("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function Uy({title:e,description:t,data:r}){const[s,a]=_(!0);return l(ue,{children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),l("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>a(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>a(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n(vn,{content:JSON.stringify(r,null,2),label:"Copy JSON",copiedLabel:"Copied!",className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none transition-colors whitespace-nowrap"})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(By,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function Wy({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=Oe();return ee(()=>{if(e!=null&&e.sha&&a.state==="idle"&&!a.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;a.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,a.state,a.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(Yy,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const Hy={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Jy={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Vy=2e3,qy=e=>{var r;if(!e)return"typescript";switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"ts":case"tsx":return"typescript";case"js":case"jsx":return"javascript";case"json":return"json";case"css":return"css";default:return"typescript"}};function Gy({entity:e,entityCode:t}){const r=Pr(),s=ve(null);return ee(()=>{const a=r.hash;if(!a||!s.current)return;const o=a.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!s.current)return;const c=s.current.querySelector(`[data-line-number="${i}"]`);if(c&&c instanceof HTMLElement){c.scrollIntoView({behavior:"smooth",block:"center"});const d=c.style.backgroundColor;c.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{c.style.backgroundColor=d},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:l("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(vn,{content:t,label:"Copy Code",duration:Vy,className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] disabled:opacity-75 disabled:cursor-not-allowed"})]}),n("div",{className:"p-0",children:t?n("div",{className:"relative",children:n(Vc,{language:qy(e==null?void 0:e.filePath),style:qc,showLineNumbers:!0,customStyle:Hy,lineNumberStyle:Jy,wrapLines:!0,lineProps:a=>({"data-line-number":a,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Ky=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Qy({currentParams:e,nextParams:t,currentUrl:r,nextUrl:s,formMethod:a,defaultShouldRevalidate:o}){return r.pathname===s.pathname&&r.search===s.search?o:!!(e.sha!==t.sha||a)}async function Zy({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),c=(e["*"]||"").split("/").filter(Boolean),d=c[0]||"scenarios",h=c[1]||null,u=c[2]||null,m=r.analysisQueue,p=m?m.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([tn(s),$e(),yn(),ku(ge()||process.cwd())]),v=f?await Lr(f):null,b=f?await yi(f.sha):null;let N={importedEntities:[],importingEntities:[]},w=null,E=[];f&&(N=await xi(f),w=await bi(f),E=await wi(f));const C=!!(f&&E.length>0&&E[0].sha!==f.sha),S=E.length>0?E[0].sha:null,k=!!(E.length>0&&E[0].analyses&&E[0].analyses.length>0),P=f?await vi(f):!1;return G({entity:f??void 0,analysis:v??void 0,currentEntityAnalysis:b??void 0,projectSlug:y,from:o,relatedEntities:N,entityCode:w??void 0,hasNewerVersion:C,newestEntitySha:S,newestVersionHasAnalysis:k,fileModifiedSinceEntity:P,history:E,tab:d,scenarioId:h,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:x,queueState:p})}const Xy=He(function(){var We,Wt,Vn,on,Ma,ja,Ta,$a,Ra,Ia,Da,La,Oa,Fa,za;const t=qe(),a=(Ho()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,c=a[2]||null,d=t.entity,h=t.analysis,u=t.currentEntityAnalysis,m=u||h,p=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,v=t.newestVersionHasAnalysis,b=t.fileModifiedSinceEntity,N=t.history,w=t.currentCommit,E=t.hasAnApiKey,C=t.queueState;(We=m==null?void 0:m.status)==null||We.errors;const S=(m==null?void 0:m.scenarios)||[],k=S.filter(le=>{var Ae;return!((Ae=le.metadata)!=null&&Ae.sameAsDefault)}),P=S.filter(le=>{var Ae;return(Ae=le.metadata)==null?void 0:Ae.sameAsDefault}),I=Ct(),j=ve(null);ee(()=>{j.current===null&&(j.current=window.history.length)},[]);const A=()=>{if(typeof window>"u")return;const le=window.history.state;if(le===null||(le==null?void 0:le.idx)===void 0||(le==null?void 0:le.idx)===0)I("/");else{const Ae=window.history.length,Xe=j.current;if(Xe!==null&&Ae>Xe){const ze=Ae-Xe+1;I(-ze)}else I(-1)}},T=!!C.currentlyExecuting,R=o,$=(Wt=w==null?void 0:w.metadata)==null?void 0:Wt.currentRun,J=!!($!=null&&$.createdAt)&&!($!=null&&$.analysisCompletedAt),q=!!(d!=null&&d.sha&&((Vn=$==null?void 0:$.currentEntityShas)!=null&&Vn.includes(d.sha))),Y=!!(d!=null&&d.sha&&((Ma=(on=C.currentlyExecuting)==null?void 0:on.entityShas)!=null&&Ma.includes(d.sha))),U=!!(d!=null&&d.sha&&((ja=C.jobs)!=null&&ja.some(le=>{var Ae;return(Ae=le.entityShas)==null?void 0:Ae.includes(d.sha)}))),H=q||Y||U,D=H&&((Ta=m==null?void 0:m.status)==null?void 0:Ta.finishedAt)!=null&&k.length>0&&m.entitySha!==(d==null?void 0:d.sha),M=re(()=>{if(R!=="scenarios")return null;if(i){const le=k.find(Ae=>Ae.id===i);if(le)return le}return k.length>0&&!H?k[0]:null},[R,i,k,H]),Q=((Ia=(Ra=($a=M==null?void 0:M.metadata)==null?void 0:$a.executionResult)==null?void 0:Ra.error)==null?void 0:Ia.message)||((Oa=(La=(Da=m==null?void 0:m.status)==null?void 0:Da.errors)==null?void 0:La[0])==null?void 0:Oa.message);ft({source:M?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:M==null?void 0:M.id,analysisId:m==null?void 0:m.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:M==null?void 0:M.name,errorMessage:Q});const[W,F]=_(()=>c&&c!=="edit"?c:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");ee(()=>{c&&c!==W&&c!=="edit"&&F(c)},[c]);const te=c==="edit",[z,L]=_(!1),[V,B]=_(!1),[X,ce]=_(null),[we,ae]=_(!1),[he,ye]=_(!1),[Me,je]=_(null),[De,Le]=_(null),[Ee,ne]=_(0),{interactiveServerUrl:xe,isStarting:Ce,isLoading:it,showIframe:pe,iframeKey:Ye,onIframeLoad:Fe}=sn({analysisId:m==null?void 0:m.id,scenarioId:M==null?void 0:M.id,scenarioName:M==null?void 0:M.name,projectSlug:p,enabled:te&&!!M,refreshTrigger:Ee}),[gt,Pa]=_(!1),[Wn,_a]=_(""),[nt,Bt]=_(!1),[_t,Yt]=_(Date.now()),[Hn,wn]=_(!1),Ze=Oe(),yt=Oe(),Ue=Oe(),Ve=mt(),Xr=C.jobs.some(le=>{var Ae;return(d==null?void 0:d.sha)&&((Ae=le.entityShas)==null?void 0:Ae.includes(d.sha))||le.type==="analysis"&&le.commitSha===(w==null?void 0:w.sha)&&le.entityShas&&le.entityShas.length===0}),Ut=H,an=((Fa=d==null?void 0:d.metadata)==null?void 0:Fa.defaultWidth)||((za=m==null?void 0:m.metadata)==null?void 0:za.defaultWidth)||1440,es=Math.round(an*(900/1440));Ze.state==="submitting"||Ze.state,re(()=>{var le;return!!((le=M==null?void 0:M.metadata)!=null&&le.interactiveExamplePath)},[M]);const{isCompleted:Nn}=kt(p,nt);ee(()=>{Ze.state==="idle"&&Ze.data&&(Ze.data.success?setTimeout(()=>{Yt(Date.now()),Ve.revalidate(),Bt(!1)},1500):Ze.data.error&&(Bt(!1),alert(`Recapture failed: ${Ze.data.error}`)))},[Ze.state,Ze.data,Ve]),ee(()=>{nt&&Nn&&setTimeout(()=>{Yt(Date.now()),Ve.revalidate(),Bt(!1)},1500)},[nt,Nn,Ve]),ee(()=>{yt.state==="idle"&&yt.data&&(yt.data.success?setTimeout(()=>{Yt(Date.now()),Ve.revalidate(),Bt(!1)},1500):yt.data.error&&(Bt(!1),alert(`Recapture failed: ${yt.data.error}`)))},[yt.state,yt.data,Ve]);const Jn=()=>{d&&(g&&x&&x!==d.sha?(I(`/entity/${x}/scenarios`),setTimeout(()=>{Ue.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):Ue.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};ee(()=>{Ue.state==="idle"&&Ue.data&&(Ue.data.success?Ve.revalidate():Ue.data.error&&alert(`Analysis failed: ${Ue.data.error}`))},[Ue.state,Ue.data,d==null?void 0:d.sha,Ve]),ee(()=>{const le=setTimeout(()=>{Ve.revalidate()},500);return()=>clearTimeout(le)},[]),ee(()=>{if(J||Ut){const le=setInterval(()=>{Ve.revalidate()},3e3);return()=>clearInterval(le)}},[J,Ut,Ve]);const ts=(le,Ae)=>le==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${le}`,ns=(le,Ae)=>`/entity/${d==null?void 0:d.sha}/scenarios/${le}/${Ae}`,rs=le=>{F(le),M!=null&&M.id&&(le==="interactive"?I(`/entity/${d==null?void 0:d.sha}/scenarios/${M.id}/fullscreen`,{replace:!0}):I(ns(M.id,le),{replace:!0}))},lt=async le=>{var Ae,Xe;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:le,hasSelectedScenario:!!M,hasAnalysis:!!m}),!M||!m){const ze="Error: No scenario or analysis available";console.error("[EntityDetail]",ze),ce(ze);return}L(!0),ce(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:le,scenarioId:M.id,scenarioName:M.name,currentData:M.data});try{const ze=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:le,existingScenarios:m.scenarios,scenariosDataStructure:(Ae=m.metadata)==null?void 0:Ae.scenariosDataStructure,editingMockName:M.name,editingMockData:De||((Xe=M.metadata)==null?void 0:Xe.data)})}),xt=await ze.json();if(!ze.ok||!xt.success)throw new Error(xt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",xt.data),Le(xt.data);const qn=(m.scenarios||[]).map(Qe=>Qe.id===M.id?{...Qe,metadata:{...Qe.metadata,data:xt.data}}:Qe),Cn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:qn})}),rt=await Cn.json();if(!Cn.ok||!rt.success)throw console.error("[EntityDetail] Temp save failed:",rt),new Error(rt.error||"Failed to apply preview");if(ce("Generating preview. Capturing screenshot..."),xe){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:xe});const Qe=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:xe,scenarioId:M.id,projectId:m.projectId,viewportWidth:1440})}),Sn=await Qe.json();!Qe.ok||!Sn.success?(console.error("[EntityDetail] Direct capture failed:",Sn),ce("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),ce('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Qe=new FormData;Qe.append("analysisId",m.id||""),Qe.append("scenarioId",M.id||"");const Sn=await fetch("/api/recapture-scenario",{method:"POST",body:Qe}),as=await Sn.json();!Sn.ok||!as.success?(console.warn("[EntityDetail] Recapture failed:",as.error),ce("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",as.jobId),ce('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}ne(Qe=>Qe+1),Ve.revalidate()}catch(ze){console.error("Error applying changes:",ze),ce(`Error: ${ze instanceof Error?ze.message:String(ze)}`)}finally{L(!1)}},ss=async(le,Ae)=>{var Xe;if(!M||!m){ce("Error: No scenario or analysis available");return}B(!0),ce(null),console.log("[EntityDetail] Saving scenario to database",{description:le,saveAsNew:Ae});try{const ze=De||((Xe=M.metadata)==null?void 0:Xe.data);let xt;if(Ae){const rt={...M,id:`${M.name}-${Date.now()}`,name:`${M.name} (Copy)`,metadata:{...M.metadata,data:ze},description:le||M.description};xt=[...m.scenarios||[],rt]}else xt=(m.scenarios||[]).map(rt=>rt.id===M.id?{...rt,metadata:{...rt.metadata,data:ze},description:le||rt.description}:rt);const qn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:xt})}),Cn=await qn.json();if(!qn.ok||!Cn.success)throw new Error(Cn.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),ce(Ae?"New scenario created successfully":"Scenario saved successfully"),Le(null),Ve.revalidate()}catch(ze){console.error("Error saving scenario:",ze),ce(`Error: ${ze instanceof Error?ze.message:String(ze)}`)}finally{B(!1)}},se=()=>{M!=null&&M.id&&(d!=null&&d.sha)&&I(`/entity/${d.sha}/scenarios/${M.id}/dev`)},fe=async()=>{var le;if(!(M!=null&&M.id)){je("Cannot delete scenario without ID");return}ae(!0),je(null);try{const Ae=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:M.id,screenshotPaths:((le=M.metadata)==null?void 0:le.screenshotPaths)||[]})}),Xe=await Ae.json();if(!Ae.ok||!Xe.success)throw new Error(Xe.error||"Failed to delete scenario");I(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(Ae){console.error("[EntityDetail] Error deleting scenario:",Ae),je(Ae instanceof Error?Ae.message:"Failed to delete scenario"),ye(!1)}finally{ae(!1)}},ke=m&&d&&m.entitySha!==d.sha,Re=d?$y(d):!1;return n(Vr,{children:l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:A,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:k.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"code",label:"Code"},{id:"data",label:"Data Structure"},{id:"history",label:"History"}].map(le=>n(de,{to:ts(le.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${R===le.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:R===le.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[le.label,le.count!==void 0&&le.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${R===le.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:le.count})]})},le.id))})]})}),(g||ke&&!u||b&&Re)&&!H&&!Xr&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:l("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:ke&&!g?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:g?"You are viewing an older version. A newer version is available.":ke?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&v?n(de,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:le=>{le.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:le=>{le.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Jn,disabled:Ue.state!=="idle",className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#C69538"},onMouseEnter:le=>{Ue.state==="idle"&&(le.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:le=>{Ue.state==="idle"&&(le.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),l("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[R==="scenarios"&&l(ue,{children:[te&&M?n(Iy,{scenario:M,entitySha:(d==null?void 0:d.sha)||"",onApply:lt,onSave:ss,onEditMockData:se,onDelete:fe,isApplying:z,isSaving:V,saveMessage:X,showDeleteConfirm:he,onShowDeleteConfirm:ye,isDeleting:we,deleteError:Me}):n(Ry,{scenarios:k,hiddenScenarios:P,analysis:m,selectedScenario:M,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:_t,activeTab:R,entityType:d==null?void 0:d.entityType,entity:d,queueState:C,processIsRunning:T,isEntityAnalyzing:H,areScenariosStale:D,viewMode:W,setViewMode:rs,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(Ly,{analysis:m??null,entitySha:(d==null?void 0:d.sha)||""}):te&&M?n(qr,{scenarioId:M.id||M.name,scenarioName:M.name,iframeUrl:xe,isStarting:Ce,isLoading:it,showIframe:pe,iframeKey:Ye,onIframeLoad:Fe,projectSlug:p,defaultWidth:1440,defaultHeight:900}):l("div",{className:"flex flex-col flex-1 min-h-0",children:[M&&l("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:M.name}),l("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[an," × ",es]})]}),l("div",{className:"flex items-center gap-2",children:[n(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${M.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),l("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),l(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${M.id}/dev`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Dev Mode - Live preview with data editor and code sync",children:[l("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n("polyline",{points:"16 18 22 12 16 6"}),n("polyline",{points:"8 6 2 12 8 18"})]}),"Dev Mode"]}),l(de,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${M.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(gl,{selectedScenario:M,analysis:m,entity:d,viewMode:W,cacheBuster:_t,hasScenarios:k.length>0,isAnalyzing:Ut,projectSlug:p,hasAnApiKey:E,processIsRunning:T,queueState:C})]})]}),R==="related"&&n(zy,{relatedEntities:f}),R==="data"&&n(Wy,{entity:d,analysis:m,scenarios:k,onAnalyze:Jn}),R==="code"&&n(Gy,{entity:d,entityCode:y}),R==="history"&&n(Oy,{entity:d,history:N})]}),Hn&&p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>wn(!1),children:l("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:le=>le.stopPropagation(),children:[l("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>wn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(It,{projectSlug:p,onClose:()=>wn(!1)})})]})})]})})}),ex=Object.freeze(Object.defineProperty({__proto__:null,default:Xy,loader:Zy,meta:Ky,shouldRevalidate:Qy},Symbol.toStringTag,{value:"Module"}));async function tx(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:a,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await Je();const i=ge();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const c=Z.join(i,".codeyam","config.json"),d=JSON.parse(await be.readFile(c,"utf8")),{projectSlug:h,branchId:u}=d;if(!h||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${h}, Branch: ${u}`);const m=zr(h);try{await be.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Ie(h);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await ut({shas:t});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let g=r;if((!g||g.length===0)&&(g=[...new Set(y.map(b=>b.filePath).filter(b=>!!b))],console.log(`[analyzeEntities] Found ${g.length} unique files`)),!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const x=await Nu(p,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await Rt({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:b=>{if(!b)return;const N=b.currentRun;if(N&&N.id&&N.archivedAt)return;N&&(N.analysesCompleted&&N.analysesCompleted>0||N.capturesCompleted&&N.capturesCompleted>0)&&$u(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:h,filePaths:g,entityShas:t,entityNames:y.map(b=>b.name),...s?{context:s}:{},...a?{scenarioCount:a}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${v} for ${t.length} entities`),{jobId:v}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function nx({request:e,context:t}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Pt()),!r)return G({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("entitySha"),o=s.get("entityShas"),i=s.get("filePath"),c=s.get("context"),d=s.get("scenarioCount");let h;if(o)h=o.split(",").filter(Boolean);else if(a)h=[a];else return G({error:"Missing required field: entitySha or entityShas"},{status:400});if(h.length===0)return G({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${h.length} entity(ies)`);const u=await ut({shas:h}),p=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await tx({entityShas:h,filePaths:i?[i]:void 0,context:c||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),G({success:!0,message:`Analysis queued for ${h.length} entity(ies)`,entityCount:h.length,fileCount:p,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),G({error:"Failed to start analysis",details:s.message},{status:500})}}const rx=Object.freeze(Object.defineProperty({__proto__:null,action:nx},Symbol.toStringTag,{value:"Module"}));function sx(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function yl(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const a=t.getHours(),o=t.getMinutes(),i=a>=12?"pm":"am",c=a%12||12,d=o.toString().padStart(2,"0");return`Today, ${c}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function st(e,t=[],r=!1){var u,m;if(t.some(p=>{var f,y;return!!((f=p.entityShas)!=null&&f.includes(e.sha)||(y=p.entities)!=null&&y.some(g=>g.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const a=e.analyses[0];if(!(((u=a.status)==null?void 0:u.scenarios)&&a.status.scenarios.length>0&&a.status.scenarios.some(p=>p.screenshotFinishedAt||p.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,c=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,d=a.scenarios||[],h=d.some(p=>{var f,y,g;return((y=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=p.metadata)==null?void 0:g.executionResult)});return i>=c?d.length>0&&h?d.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const ax=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function ox({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await rn();return G({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),G({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const ix=He(function(){const t=qe(),r=t.entities,s=t.queueState;ft({source:"simulations-page"});const[a,o]=_(""),[i,c]=_("visual"),d=re(()=>{const g=[];return r.forEach(x=>{var b;const v=(b=x.analyses)==null?void 0:b[0];if(v!=null&&v.scenarios){const N=v.scenarios.filter(w=>{var E;return!((E=w.metadata)!=null&&E.sameAsDefault)}).map(w=>{var j,A,T,R,$;const E=(A=(j=w.metadata)==null?void 0:j.screenshotPaths)==null?void 0:A[0],C=(T=w.metadata)==null?void 0:T.noScreenshotSaved,S=E&&!C,k=($=(R=v.status)==null?void 0:R.scenarios)==null?void 0:$.find(J=>J.name===w.name),P=k&&k.screenshotStartedAt&&!k.screenshotFinishedAt;let I;return S?I="completed":P?I="capturing":I="error",{scenarioName:w.name,scenarioDescription:w.description||"",screenshotPath:E||"",scenarioId:w.id,state:I}}).filter(w=>w.state==="completed"||w.state==="capturing");N.length>0&&g.push({entity:x,screenshots:N,createdAt:v.createdAt||""})}}),g.sort((x,v)=>new Date(v.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),h=re(()=>r.filter(g=>{var b,N;const x=(b=g.analyses)==null?void 0:b[0];return!((N=x==null?void 0:x.scenarios)==null?void 0:N.some(w=>{var E,C;return(C=(E=w.metadata)==null?void 0:E.screenshotPaths)==null?void 0:C[0]}))}),[r]),u=re(()=>d.filter(({entity:g})=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[d,a,i]),m=re(()=>h.filter(g=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),v=i==="all"||g.entityType===i;return x&&v}),[h,a,i]),p=ie(g=>{o(g.target.value)},[]),f=ie(g=>{c(g.target.value)},[]),y=d.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:l("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative",children:[l("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(ot,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[n(On,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:a,onChange:p})]})]})]}),y&&u.length>0&&n("div",{className:"mb-2",children:l("div",{className:"flex items-center py-3",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),l("div",{className:"flex flex-col gap-3",children:[y&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(ue,{children:u.map(({entity:g,screenshots:x})=>n(lx,{entity:g,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},g.sha))})),!y&&(m.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):m.map(g=>n(cx,{entity:g},g.sha)))]})]})})});function lx({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=Ct(),a=Oe(),[o,i]=_(!1),c=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},h=()=>{i(!0),a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};ee(()=>{a.state==="idle"&&o&&i(!1)},[a.state,o]);const u=st(e,r),m=sx(u),p=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:l("div",{className:"flex flex-col",children:[l("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(et,{type:e.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[l(de,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",c,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:m.bgColor,color:m.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:m.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),l("div",{className:"flex-shrink-0 flex items-center gap-2",children:[p&&n(ue,{children:o||a.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(dt,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:h,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void s(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>l("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:v=>{x.state==="completed"&&(v.currentTarget.style.borderColor="#005C75",v.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:v=>{v.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",v.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(Ge,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(ya,{size:"medium"}):null})}),l("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:l("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&l(ue,{children:[": ",x.scenarioDescription]}),n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},x.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function cx({entity:e}){const t=Oe(),[r,s]=_(!1),a=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return ee(()=>{t.state==="idle"&&r&&s(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:a,children:l("div",{className:"px-5 py-4 flex items-center",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(et,{type:e.entityType}),l("div",{className:"min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-0.5",children:[n(de,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),n("span",{className:"text-[10px] font-semibold px-1 py-0.5 rounded",style:{color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#0DBFE9":e.entityType==="type"?"#dc2626":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":e.entityType==="functionCall"?"#7c3aed":e.entityType==="class"?"#059669":e.entityType==="method"?"#0891b2":"#6b7280",backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"?"#cffafe":e.entityType==="type"?"#fee2e2":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#ffedd5":e.entityType==="functionCall"?"#f3e8ff":e.entityType==="class"?"#d1fae5":e.entityType==="method"?"#cffafe":"#f3f4f6"},children:e.entityType?e.entityType.toUpperCase():"UNKNOWN"})]}),n("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),n("div",{className:"w-32 flex justify-center",children:n("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),n("div",{className:"w-32 text-center text-[10px] text-gray-500",children:yl(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(dt,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:a,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const dx=Object.freeze(Object.defineProperty({__proto__:null,default:ix,loader:ox,meta:ax},Symbol.toStringTag,{value:"Module"}));function ux({request:e,context:t}){const r=t.dbNotifier||Nt;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const s=new ReadableStream({start(a){const o=new TextEncoder;a.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
300
+
301
+ `)),Math.random().toString(36).substring(7);let i=!1;const c=()=>{if(!i){i=!0,r.off("change",d),clearInterval(h);try{a.close()}catch{}}},d=u=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
302
+
303
+ `))}catch{c()}};r.on("change",d);const h=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
304
+
305
+ `))}catch{c()}},3e4);e.signal.addEventListener("abort",c)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const hx=Object.freeze(Object.defineProperty({__proto__:null,loader:ux},Symbol.toStringTag,{value:"Module"}));function mx(){return new Response(JSON.stringify({status:"ok",version:la,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const px=Object.freeze(Object.defineProperty({__proto__:null,loader:mx},Symbol.toStringTag,{value:"Module"}));function va(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],a=r[2],o={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),c=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?o.paths=i[1].split(`
306
+ `).filter(h=>h.trim().startsWith("-")).map(h=>h.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):c&&(o.paths=c[1].split(",").map(h=>h.replace(/['"]/g,"").trim()).filter(Boolean));const d=s.match(/^category:\s*(.+)$/m);return d&&(o.category=d[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function Qr(e,t=""){const r=[];try{const s=await be.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await Qr(Z.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function Un(e){const t=await Qr(e),r=[];for(const s of t){const a=Z.join(e,s);try{const o=await be.readFile(a,"utf-8"),{frontmatter:i,body:c}=va(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:c})}catch{}}return r}function xl(e){const t=Z.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function bl(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>$s(e,s,{matchBase:!0}));const r=xl(t);return r?$s(e,r,{matchBase:!0}):!1}function fx(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!xl(e)?[]:t.filter(r=>bl(r,e))}const gx=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function wa(e){const t=[];async function r(s,a){try{const o=await Ne.readdir(s,{withFileTypes:!0});for(const i of o){const c=O.join(s,i.name),d=a?`${a}/${i.name}`:i.name;i.isDirectory()&&gx.has(i.name)||(i.isDirectory()?await r(c,d):i.isFile()&&t.push(d))}}catch{}}return await r(e,""),t}const yx="codeyam-rule-state.json",Es=1;function vl(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return zn.createHash("sha256").update(t).digest("hex")}function wl(e){return Z.join(e,".claude",yx)}async function Nl(e){const t=wl(e);try{const r=await be.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==Es?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:Es,rules:{}}):s}catch{return{version:Es,rules:{}}}}async function Cl(e,t){const r=wl(e),s=Z.dirname(r);await be.mkdir(s,{recursive:!0}),await be.writeFile(r,JSON.stringify(t,null,2)+`
307
+ `,"utf-8")}async function Na(e,t){const r=await Nl(e),s=new Set(t.map(a=>a.filePath));for(const a of Object.keys(r.rules))s.has(a)||delete r.rules[a];for(const a of t){const o=await be.readFile(a.absolutePath,"utf-8"),i=vl(o),c=r.rules[a.filePath];c?c.contentHash!==i&&(r.rules[a.filePath]={...c,contentHash:i,reviewed:!1}):r.rules[a.filePath]={contentHash:i,reviewed:!1}}return await Cl(e,r),r}async function Io(e,t,r,s){const a=await Nl(e);if(r){const o=Z.join(e,".claude","rules"),i=Z.join(o,t),c=await be.readFile(i,"utf-8"),d=vl(c);a.rules[t]?(a.rules[t].reviewed=!0,a.rules[t].contentHash=d):a.rules[t]={contentHash:d,reviewed:!0}}else a.rules[t]&&(a.rules[t].reviewed=!1);await Cl(e,a)}function Ca(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function Sl(e,t=""){const r=[],s=await be.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await Sl(Z.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function Sr(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
308
+ `).filter(s=>!(!s.startsWith("+")&&!s.startsWith("-")||s.startsWith("+++")||s.startsWith("---"))).map(s=>s.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(s=>r.test(s))}async function xx({request:e}){const t=ge();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),a=Z.join(t,".claude","rules");if(s==="recent-changes")return vx(t,a);if(s==="reviewed-status")return Nx(t,a);if(s==="audit")return Cx(t,a);if(s==="source-files")return Sx(t);if(s==="rule-coverage")return kx(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?wx(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?Ex(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await Qr(a),i=[];for(const u of o){const m=Z.join(a,u);try{const p=await be.readFile(m,"utf-8"),f=await be.stat(m),{frontmatter:y,body:g}=va(p);i.push({filePath:u,content:p,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,m)=>new Date(m.lastModified).getTime()-new Date(u.lastModified).getTime());let c=i.length>0;if(!c)try{await be.access(Z.join(t,".claude","codeyam-rule-state.json")),c=!0}catch{}const d=await Un(a),h={};if(d.length>0){const u=await Na(t,d);for(const m of d)h[m.filePath]=Ca(u,m.filePath)}return Response.json({memories:i,memoryInitialized:c,reviewedStatus:h})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function bx(e,t){const r=[];try{const s=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const a of s.split(`
309
+ `).filter(Boolean)){const o=a.substring(0,2);let i=a.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const c=o[0],d=o[1];let h=[i];if(i.endsWith("/")&&c==="?"){const u=Z.join(e,i);try{h=(await Sl(u)).map(p=>i+p)}catch{continue}}for(const u of h){if(u.endsWith("/"))continue;const m=u.replace(".claude/rules/","");let p="modified";c==="A"||c==="?"?p="added":c==="D"||d==="D"?p="deleted":(c==="M"||d==="M")&&(p="modified");let f="";try{if(p==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(p==="added"&&c==="?"){const y=`${e}/${u}`;try{const g=await be.readFile(y,"utf-8");f=`diff --git a/${u} b/${u}
310
+ new file mode 100644
311
+ --- /dev/null
312
+ +++ b/${u}
313
+ @@ -0,0 +1,${g.split(`
314
+ `).length} @@
315
+ ${g.split(`
316
+ `).map(x=>"+"+x).join(`
317
+ `)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
318
+ ... (truncated)`)}catch{f="(diff not available)"}p==="modified"&&Sr(f)||r.push({filePath:m,changeType:p,diff:f})}}}catch{}return r}async function vx(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await Un(t),o={};if(a.length>0){const u=await Na(e,a);for(const m of a)o[m.filePath]=Ca(u,m.filePath)}const c=(await bx(e,r)).filter(u=>!o[u.filePath]);c.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:c});const h=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
319
+ `).filter(Boolean).slice(0,20);for(const u of h){const[m,p,...f]=u.split("|"),y=f.join("|");if(!m||!p)continue;const g=r(`git diff-tree --no-commit-id --name-status -r ${m} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const v of g.split(`
320
+ `).filter(Boolean)){const[b,N]=v.split(" ");if(!N||!N.startsWith(".claude/rules/"))continue;const w=N.replace(".claude/rules/","");let E="modified";if(b==="A"?E="added":b==="D"&&(E="deleted"),o[w])continue;let C="";try{C=r(`git show ${m} --format="" -- "${N}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),C.length>5e3&&(C=C.substring(0,5e3)+`
321
+ ... (truncated)`)}catch{C="(diff not available)"}E==="modified"&&Sr(C)||x.push({filePath:w,changeType:E,diff:C})}x.length>0&&s.push({commitHash:m.substring(0,8),date:p,message:y,files:x})}return Response.json({changes:s,reviewedStatus:o})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function wx(e,t){try{const{execSync:r}=await import("child_process"),s=`.claude/rules/${t}`,a=r(`git rev-list --count HEAD -- "${s}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),o=parseInt(a.trim(),10)||0,i=r(`git diff HEAD -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});if(i.trim()){if(Sr(i))return Response.json({diff:null});const g=i.length>5e3?i.substring(0,5e3)+`
322
+ ... (truncated)`:i;return Response.json({diff:{diff:g,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:o}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const g=Z.join(e,s);try{const x=await be.readFile(g,"utf-8"),v=`diff --git a/${s} b/${s}
323
+ new file mode 100644
324
+ --- /dev/null
325
+ +++ b/${s}
326
+ @@ -0,0 +1,${x.split(`
327
+ `).length} @@
328
+ ${x.split(`
329
+ `).map(b=>"+"+b).join(`
330
+ `)}`;return Response.json({diff:{diff:v.length>5e3?v.substring(0,5e3)+`
331
+ ... (truncated)`:v,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const h=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!h)return Response.json({diff:null});const[u,m,...p]=h.split("|"),f=p.join("|");if(!u||!m)return Response.json({diff:null});let y=r(`git show ${u} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return y.trim()?Sr(y)?Response.json({diff:null}):(y.length>5e3&&(y=y.substring(0,5e3)+`
332
+ ... (truncated)`),Response.json({diff:{diff:y,commitMessage:f,date:m,isUncommitted:!1,commitCount:o}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function Nx(e,t){try{const r=await Un(t),s={};if(r.length>0){const a=await Na(e,r);for(const o of r)s[o.filePath]=Ca(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function Cx(e,t){try{const r=await Un(t),s=await wa(e),a=[];for(const o of s){const i=r.filter(c=>bl(o,c));if(i.length>0){const c=i.reduce((d,h)=>d+h.body.length,0);a.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:c})}}return a.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:a,totalFilesWithCoverage:a.length,allSourceFiles:s})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Sx(e){try{const t=await wa(e);return Response.json({files:t})}catch(t){return console.error("[API] Error getting source files:",t),Response.json({error:"Failed to get source files",details:t instanceof Error?t.message:String(t)},{status:500})}}async function kx(e,t){try{const[r,s]=await Promise.all([Un(t),wa(e)]),a={};for(const o of r)a[o.filePath]=fx(o,s).length;return Response.json({coverage:a})}catch(r){return console.error("[API] Error getting rule coverage:",r),Response.json({error:"Failed to get rule coverage",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Ex(e,t){try{const r=await Qr(e),s=[];for(const o of r){const i=Z.join(e,o);try{const c=await be.readFile(i,"utf-8"),d=await be.stat(i),{frontmatter:h,body:u}=va(c);h.paths&&h.paths.some(m=>$s(t,m,{matchBase:!0}))&&s.push({filePath:o,content:c,frontmatter:h,body:u,lastModified:d.mtime.toISOString()})}catch{}}const a=s.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:s,totalTextLength:a})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Ax({request:e}){const t=ge();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=Z.join(t,".claude","rules");try{const s=await e.json(),{action:a,filePath:o,content:i,lastModified:c}=s;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(a==="mark-reviewed")return await Io(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(a==="mark-unreviewed")return await Io(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=Z.normalize(o);if(d.includes("..")||Z.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const h=Z.join(r,d);switch(a){case"create":case"update":return i?(await be.mkdir(Z.dirname(h),{recursive:!0}),await be.writeFile(h,i,"utf-8"),console.log(`[API] Memory ${a}d: ${o}`),Response.json({success:!0,message:`Memory ${a}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await be.unlink(h),console.log(`[API] Memory deleted: ${o}`);const u=Z.dirname(h);try{(await be.readdir(u)).length===0&&u!==r&&await be.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(s){return console.error("[API] Error managing memory:",s),Response.json({error:"Failed to manage memory",details:s instanceof Error?s.message:String(s)},{status:500})}}const Px=Object.freeze(Object.defineProperty({__proto__:null,action:Ax,loader:xx},Symbol.toStringTag,{value:"Module"}));async function _x({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await Pt()),!r)return G({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return G({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return G({error:"Missing jobId parameter for job query"},{status:400});const c=r.getState();if(((o=c.currentlyExecuting)==null?void 0:o.id)===i)return G({jobId:i,status:"running",job:c.currentlyExecuting});const d=c.jobs.find(u=>u.id===i);if(d){const u=c.jobs.indexOf(d);return G({jobId:i,status:"queued",position:u,job:d})}const h=r.getJobResult(i);return h?G({jobId:i,status:h.status==="error"?"failed":"completed",error:h.error}):G({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),c=await Promise.all(i.jobs.map(async h=>{const u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>tn(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}return{id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}));let d;if(i.currentlyExecuting){const h=i.currentlyExecuting,u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>tn(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}d={id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}return G({state:{...i,jobsWithEntities:c,currentlyExecutingWithEntities:d}})}return G({error:"Unknown queryType"},{status:400})}async function Mx({request:e,context:t}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(t||{})),console.log("[Queue API] analysisQueue exists:",!!(t!=null&&t.analysisQueue));let r=t.analysisQueue;if(r||(r=await Pt(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),G({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:a,...o}=s;if(console.log("[Queue API] Action:",a,"Params:",Object.keys(o)),a==="enqueue"){const{jobId:i,completion:c}=r.enqueue(o);return c.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),G({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),G({status:"resumed"});if(a==="pause")return r.pause(),G({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?G({status:"removed",jobId:i}):G({error:"Job not found in queue"},{status:404}):G({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return G({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:c}=o;return!i||!c?G({error:"Missing jobId or direction parameter"},{status:400}):c!=="up"&&c!=="down"?G({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,c)?G({status:"reordered",jobId:i,direction:c}):G({error:"Could not reorder job (not found or at boundary)"},{status:400})}return G({error:"Unknown action"},{status:400})}const jx=Object.freeze(Object.defineProperty({__proto__:null,action:Mx,loader:_x},Symbol.toStringTag,{value:"Module"})),Tx=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],$x=He(function(){return Oe(),n(Vr,{children:l("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-center h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[l("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),l("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:l("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(gl,{selectedScenario:null,analysis:void 0,entity:{sha:"mock-sha",name:"Dashboard",filePath:"codeyam-cli/src/webserver/app/routes/_index.tsx",entityType:"visual"},viewMode:"screenshot",cacheBuster:Date.now(),hasScenarios:!1,isAnalyzing:!1,projectSlug:null,hasAnApiKey:!0})]})]})})}),Rx=Object.freeze(Object.defineProperty({__proto__:null,default:$x,meta:Tx},Symbol.toStringTag,{value:"Module"})),Ix=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function Dx({request:e}){var t,r;try{const s=await Or();if(!s)return G({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const d=await $e();if(d){const{project:h}=await Ie(d);a=((r=(t=h.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=ge()||process.cwd(),i=await Fr(o),c=Mi(s.projectSlug);return G({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:c,simulationsEnabled:a,error:null})}catch(s){return console.error("Failed to load config:",s),G({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function Lx(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],s=t.length>1?t.slice(1):void 0;return{command:r,args:s}}async function Ox({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),a=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),c=t.get("pathsToIgnore"),d=t.get("memorySettings");let h;if(r)try{h=JSON.parse(r)}catch{return G({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return G({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let m;c&&(m=c.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let p;if(d)try{p=JSON.parse(d)}catch{return G({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await Or();x!=null&&x.webapps&&(f=x.webapps.map((v,b)=>{if(u[b]!==void 0){const N=Lx(u[b]);return{...v,startCommand:N}}return v}))}if(!await Ni({universalMocks:h,pathsToIgnore:m,webapps:f,memory:p}))return G({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(a!==void 0||o!==void 0||i!==void 0){const x=ge()||process.cwd(),v=await Fr(x);g=a!==void 0&&a!==(v.GROQ_API_KEY||"")||o!==void 0&&o!==(v.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(v.OPENAI_API_KEY||""),await Su(x,{...v,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return G({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),G({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Do(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Lo({mock:e,onSave:t,onCancel:r}){const[s,a]=_(e.entityName),[o,i]=_(e.filePath),[c,d]=_(e.content);return l("div",{className:"space-y-3",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:u=>a(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:c,onChange:u=>d(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),l("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!s.trim()||!o.trim()||!c.trim()){alert("All fields are required");return}t({entityName:s,filePath:o,content:c})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Fx(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const zx=He(function(){var Me,je,De,Le,Ee;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=qe(),i=Wl(),c=Oe(),d=mt(),[h,u]=_(a?"project-metadata":"memory");ft({source:"settings-page"});const[m,p]=_((t==null?void 0:t.universalMocks)||[]),[f,y]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[v,b]=_((r==null?void 0:r.GROQ_API_KEY)||""),[N,w]=_((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[E,C]=_((r==null?void 0:r.OPENAI_API_KEY)||""),[S,k]=_(!1),[P,I]=_(!1),[j,A]=_(!1),[T,R]=_(!1),[$,J]=_(!1),[q,Y]=_(!1),[U,H]=_(null),[D,M]=_(!1),[Q,W]=_({}),[F,te]=_(((Me=t==null?void 0:t.memory)==null?void 0:Me.conversationReflection)??!0),[z,L]=_(((je=t==null?void 0:t.memory)==null?void 0:je.ruleMaintenance)??!0),[V,B]=_(((De=t==null?void 0:t.memory)==null?void 0:De.promptModel)??"haiku");ee(()=>{var ne,xe,Ce,it;if(t){p(t.universalMocks||[]);const pe=(t.pathsToIgnore||[]).join(", ");y(pe),x(pe);const Ye={};(ne=t.webapps)==null||ne.forEach((Fe,gt)=>{Fe.startCommand&&(Ye[gt]=Do(Fe.startCommand))}),W(Ye),te(((xe=t.memory)==null?void 0:xe.conversationReflection)??!0),L(((Ce=t.memory)==null?void 0:Ce.ruleMaintenance)??!0),B(((it=t.memory)==null?void 0:it.promptModel)??"haiku")}r&&(b(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),C(r.OPENAI_API_KEY||""))},[t,r]),ee(()=>{if(i!=null&&i.success){R(!0);const ne=setTimeout(()=>R(!1),3e3);return()=>clearTimeout(ne)}},[i]),ee(()=>{if(c.state==="idle"&&c.data&&!q){console.log("[Settings] Fetcher data:",c.data);const ne=c.data;if(ne.success){console.log("[Settings] Save successful, revalidating..."),R(!0),Y(!0),(f!==g||ne.requiresRestart)&&J(!0),d.revalidate();const xe=setTimeout(()=>{R(!1),Y(!1)},3e3);return()=>clearTimeout(xe)}}},[c.state,c.data,q,d,f,g]);const X=ne=>{ne.preventDefault();const xe=new FormData(ne.currentTarget);xe.set("universalMocks",JSON.stringify(m)),xe.set("startCommands",JSON.stringify(Q)),xe.set("memorySettings",JSON.stringify({conversationReflection:F,ruleMaintenance:z,promptModel:V})),console.log("[Settings] Submitting form data:",{universalMocks:xe.get("universalMocks"),startCommands:xe.get("startCommands"),openAiApiKey:xe.get("openAiApiKey")?"***":"(empty)"}),c.submit(xe,{method:"post"})},ce=ne=>{p([...m,ne]),M(!1)},we=(ne,xe)=>{const Ce=[...m];Ce[ne]=xe,p(Ce),H(null)},ae=ne=>{p(m.filter((xe,Ce)=>Ce!==ne))};if(o)return l("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const he=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],ye=a?he:he.filter(ne=>ne.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[l("div",{className:"mb-8 flex justify-between items-start",children:[l("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:c.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:c.state==="submitting"?"Saving...":"Save Settings"})]}),(T||$||(i==null?void 0:i.error)||c.data&&typeof c.data=="object"&&"error"in c.data)&&l("div",{className:"mb-4 space-y-3",children:[T&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),$&&l("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),l("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(vn,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(c.data&&typeof c.data=="object"&&"error"in c.data){const ne=c.data;return typeof ne.error=="string"?n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:ne.error}):null}return null})()]}),l("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:ye.map(ne=>n("li",{children:n("button",{type:"button",onClick:()=>u(ne.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${h===ne.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:ne.label})},ne.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:l("form",{id:"settings-form",onSubmit:X,className:"space-y-6",children:[h==="project-metadata"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),l("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((ne,xe)=>{var Ce;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ne.path==="."?"Root":ne.path})]}),ne.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ne.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ne.framework})]}),ne.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",l("span",{className:"text-gray-900 font-mono text-xs",children:[ne.startCommand.command," ",(Ce=ne.startCommand.args)==null?void 0:Ce.join(" ")]})]})]})},xe)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),h==="ai-provider"&&l("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),l("div",{className:"space-y-6",children:[l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:S?"text":"password",id:"groqApiKey",name:"groqApiKey",value:v,onChange:ne=>b(ne.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>k(!S),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:S?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:P?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:N,onChange:ne=>w(ne.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>I(!P),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:P?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:j?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:E,onChange:ne=>C(ne.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>A(!j),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:j?"Hide":"Show"})]})]})]})]})]}),h==="commands"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((ne,xe)=>l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[l("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:ne.path==="."?"Root":ne.path}),n("div",{className:"text-sm text-gray-600",children:ne.framework})]}),l("div",{children:[n("label",{htmlFor:`startCommand-${xe}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${xe}`,name:`startCommand-${xe}`,value:Q[xe]||"",onChange:Ce=>W({...Q,[xe]:Ce.target.value}),placeholder:"e.g., pnpm dev --port $PORT",className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},xe))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),h==="paths-to-ignore"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:ne=>y(ne.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),l("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),h==="universal-mocks"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),m.length===0?l("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>M(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:m.map((ne,xe)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:U===xe?n(Lo,{mock:ne,onSave:Ce=>we(xe,Ce),onCancel:()=>H(null)}):n(ue,{children:l("div",{className:"flex justify-between items-start mb-2",children:[l("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:ne.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:ne.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:ne.content})]}),l("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>H(xe),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),n("button",{type:"button",onClick:()=>ae(xe),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},xe))}),m.length>0&&n("button",{type:"button",onClick:()=>M(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),h==="memory"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),l("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":F,onClick:()=>te(!F),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${F?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${F?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":z,onClick:()=>L(!z),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${z?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${z?"translate-x-5":"translate-x-0"}`})})]})}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(ne=>l("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${V===ne.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:ne.value,checked:V===ne.value,onChange:()=>B(ne.value),className:"mt-1 accent-[#005C75]"}),l("div",{children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:ne.label}),ne.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:ne.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:ne.description})]})]},ne.value))})]})]})]}),h==="current-configuration"&&l("div",{className:"space-y-6",children:[t&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:l("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&l("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((ne,xe)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ne.path==="."?"Root":ne.path})]}),ne.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ne.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ne.framework})]}),ne.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Do(ne.startCommand)})]})]})},xe))})]})]}),s&&l("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:s.webserverVersion.version||"unknown"})]}),s.templateVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:s.templateVersion.version||((Le=s.templateVersion.gitCommit)==null?void 0:Le.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&l("span",{className:"text-gray-500 ml-2",children:["(built"," ",Fx(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:s.cachedAnalyzerVersion.version||((Ee=s.cachedAnalyzerVersion.gitCommit)==null?void 0:Ee.slice(0,7))||"unknown"}),s.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!s.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),D&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Lo,{mock:{entityName:"",filePath:"",content:""},onSave:ce,onCancel:()=>M(!1)})]})})]})})}),Bx=Object.freeze(Object.defineProperty({__proto__:null,action:Ox,default:zx,loader:Dx,meta:Ix},Symbol.toStringTag,{value:"Module"}));async function Yx({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=ge();if(!r)return new Response("Project root not found",{status:500});const a=Z.extname(t)!==""?t:`${t}.html`,o=Z.join(r,".codeyam","captures","static",a);try{await be.access(o);let i=await be.readFile(o);const c=Z.extname(o).toLowerCase();let d="application/octet-stream";if(c===".html"){d="text/html";let h=i.toString("utf-8");const u=h.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const p=u[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;h=h.replace(u[0],y)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(h,"utf-8")}else c===".js"||c===".mjs"?d="application/javascript":c===".css"?d="text/css":c===".json"?d="application/json":c===".png"?d="image/png":c===".jpg"||c===".jpeg"?d="image/jpeg":c===".svg"?d="image/svg+xml":c===".woff"?d="font/woff":c===".woff2"?d="font/woff2":c===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const Ux=Object.freeze(Object.defineProperty({__proto__:null,loader:Yx},Symbol.toStringTag,{value:"Module"}));function Wx(e,t,r=10){var d;const s=new Map,a=h=>h.entityType==="visual"||h.entityType==="library";for(const h of e)a(h)&&s.set(h.sha,{entity:h,depth:0});const o=new Map;for(const h of t){const u=(d=h.metadata)==null?void 0:d.importedBy;if(u)for(const m of Object.keys(u))for(const p of Object.keys(u[m])){const{shas:f}=u[m][p];for(const y of f)o.has(h.sha)||o.set(h.sha,new Set),o.get(h.sha).add(y)}}const i=[],c=new Set;for(const h of e)i.push({sha:h.sha,depth:0}),c.add(h.sha);for(;i.length>0;){const{sha:h,depth:u}=i.shift();if(u>=r)continue;const m=o.get(h);if(m)for(const p of m){if(c.has(p))continue;c.add(p);const f=t.find(y=>y.sha===p);if(f){if(a(f)){const y=u+1,g=s.get(p);(!g||y<g.depth)&&s.set(p,{entity:f,depth:y})}i.push({sha:p,depth:u+1})}}}return Array.from(s.values()).sort((h,u)=>h.depth!==u.depth?h.depth-u.depth:h.entity.name.localeCompare(u.entity.name))}function kr(e){const t=new Map;for(const s of e)t.has(s.name)||t.set(s.name,[]),t.get(s.name).push(s);const r=[];for(const s of t.values())if(s.length===1)r.push(s[0]);else{const a=s.sort((o,i)=>{var h,u;const c=((h=o.metadata)==null?void 0:h.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(c)});r.push(a[0])}return r}function kl(e,t){const r=new Map,s=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&s.add(a.oldPath);for(const a of e){const o=t.filter(d=>d.filePath===a.path||a.status==="renamed"&&a.oldPath&&d.filePath===a.oldPath),i=o.filter(d=>{var h,u;return s.has(d.filePath)&&((h=d.metadata)==null?void 0:h.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),c=kr(i);r.set(a.path,{status:a,entities:o,editedEntities:c})}return r}function Hx(e,t,r){const s=new Map;if(!r){for(const o of e)if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),c=kr(i);s.set(o.path,{status:o,entities:c})}return s}const a=new Map;for(const o of r.fileComparisons){const i=new Set;for(const c of o.newEntities)i.add(c.name);for(const c of o.modifiedEntities)i.add(c.name);for(const c of o.deletedEntities)i.add(c.name);i.size>0&&a.set(o.filePath,i)}for(const o of e){const i=a.get(o.path);if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const c=i?t.filter(h=>(h.filePath===o.path||o.status==="renamed"&&o.oldPath&&h.filePath===o.oldPath)&&i.has(h.name)):[],d=kr(c);s.set(o.path,{status:o,entities:d})}}return s}function Jx(e,t){const r=new Map,s=El(e,t);for(const a of s){const i=Wx([a],t).filter(({depth:c})=>c>0);r.set(a.sha,i)}return r}function El(e,t){const r=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&r.add(a.oldPath);const s=t.filter(a=>{var o,i;return r.has(a.filePath)&&((o=a.metadata)==null?void 0:o.isUncommitted)&&!((i=a.metadata)!=null&&i.isSuperseded)});return kr(s)}function Vx({recentSimulations:e}){const t=re(()=>{const r=new Map;return e.forEach(s=>{const a=s.entitySha,o=r.get(a);o?o.push(s):r.set(a,[s])}),Array.from(r.entries()).map(([s,a])=>({entitySha:s,entityName:a[0].entityName,scenarios:a}))},[e]);return l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?l(ue,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>l("div",{children:[l("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Rn,{size:16,style:{color:"#8B5CF6"}})}),n(de,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((s,a)=>n(de,{to:s.scenarioId?`/entity/${s.entitySha}/scenarios/${s.scenarioId}`:`/entity/${s.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:s.scenarioName,children:n(Ge,{screenshotPath:s.screenshotPath,alt:s.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},s.scenarioId||`${s.entitySha}-${a}`))})]},r.entitySha))}),n(de,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):l("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(Rn,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),l("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(de,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(de,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const qx="/assets/codeyam-name-logo-CvKwUgHo.svg",Gx=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Kx({request:e,context:t}){var r,s,a,o,i;try{const c=await $e();if(c){const{project:T}=await Ie(c);if(((r=T.metadata)==null?void 0:r.editorMode)??!1)return Wa("/editor");if(!(((a=(s=T.metadata)==null?void 0:s.labs)==null?void 0:a.simulations)??!1))return Wa("/memory")}const d=t.analysisQueue,h=d?d.getState():{paused:!1,jobs:[]},[u,m]=await Promise.all([rn(),yn()]),p=rl(),f=u?kl(p,u):new Map,y=Array.from(f.entries()).sort((T,R)=>T[0].localeCompare(R[0])),g=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter(T=>T.entityType==="visual").length)||0,v=(u==null?void 0:u.filter(T=>T.entityType==="library").length)||0,b=u?El(p,u):[],N=b.length,w=(u==null?void 0:u.filter(T=>(T.analyses??[]).filter(R=>R.scenarios&&R.scenarios.length>0).length>0).length)||0,E=(u==null?void 0:u.reduce((T,R)=>{var J,q,Y;const $=((Y=(q=(J=R.analyses)==null?void 0:J[0])==null?void 0:q.scenarios)==null?void 0:Y.length)||0;return T+$},0))||0,C=(u==null?void 0:u.reduce((T,R)=>{var q,Y;const J=(((Y=(q=R.analyses)==null?void 0:q[0])==null?void 0:Y.scenarios)||[]).filter(U=>{var H,D;return(D=(H=U.metadata)==null?void 0:H.screenshotPaths)==null?void 0:D[0]}).length;return T+J},0))||0,S=[];u==null||u.forEach(T=>{var $;const R=($=T.analyses)==null?void 0:$[0];R!=null&&R.scenarios&&R.scenarios.filter(q=>{var Y;return!((Y=q.metadata)!=null&&Y.sameAsDefault)}).forEach(q=>{var U,H;const Y=(H=(U=q.metadata)==null?void 0:U.screenshotPaths)==null?void 0:H[0];Y&&S.push({entitySha:T.sha,entityName:T.name,scenarioId:q.id,scenarioName:q.name,screenshotPath:Y,createdAt:R.createdAt||""})})}),S.sort((T,R)=>new Date(R.createdAt).getTime()-new Date(T.createdAt).getTime());const k=S.slice(0,16),P=(u==null?void 0:u.filter(T=>T.entityType==="visual").filter(T=>{var J,q;const R=(J=T.analyses)==null?void 0:J[0];return!((q=R==null?void 0:R.scenarios)==null?void 0:q.some(Y=>{var U,H;return(H=(U=Y.metadata)==null?void 0:U.screenshotPaths)==null?void 0:H[0]}))}).slice(0,8))||[],I=(o=m==null?void 0:m.metadata)==null?void 0:o.currentRun,j=((i=I==null?void 0:I.currentEntityShas)==null?void 0:i.length)||0,A=h.jobs.length||0;return G({stats:{totalEntities:g,visualEntities:x,libraryEntities:v,uncommittedEntities:N,entitiesWithAnalyses:w,totalScenarios:E,capturedScreenshots:C,currentlyAnalyzing:j,filesOnQueue:A},uncommittedFiles:y,uncommittedEntitiesList:b,recentSimulations:k,visualEntitiesForSimulation:P,projectSlug:c,queueState:h,currentCommit:m})}catch(c){return console.error("Failed to load dashboard data:",c),G({stats:{totalEntities:0,visualEntities:0,libraryEntities:0,uncommittedEntities:0,entitiesWithAnalyses:0,totalScenarios:0,capturedScreenshots:0,currentlyAnalyzing:0,filesOnQueue:0},uncommittedFiles:[],uncommittedEntitiesList:[],recentSimulations:[],visualEntitiesForSimulation:[],projectSlug:null,queueState:{paused:!1,jobs:[]},currentCommit:null,error:"Failed to load dashboard data"})}}const Qx=He(function(){var U,H;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:c,currentCommit:d}=qe(),h=Oe(),u=mt(),{showToast:m}=ra();ft({source:"dashboard"});const[p,f]=_(new Set),[y,g]=_(null),[x,v]=_(!1),[b,N]=_(!1),{lastLine:w,isCompleted:E}=kt(i,!!y),{simulatingEntity:C,scenarios:S,scenarioStatuses:k,allScenariosCaptured:P}=re(()=>{var L,V;const D={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return D;const M=o==null?void 0:o.find(B=>B.sha===y);if(!M)return D;const Q=(L=M.analyses)==null?void 0:L[0],W=(Q==null?void 0:Q.scenarios)||[],F=((V=Q==null?void 0:Q.status)==null?void 0:V.scenarios)||[],te=F.filter(B=>B.screenshotFinishedAt).length,z=W.length>0&&te===W.length;return{simulatingEntity:M,scenarios:W,scenarioStatuses:F,allScenariosCaptured:z}},[y,o]);ee(()=>{(E||P)&&g(null)},[E,P]);const I=(U=d==null?void 0:d.metadata)==null?void 0:U.currentRun,j=new Set((I==null?void 0:I.currentEntityShas)||[]),A=new Set(c.jobs.flatMap(D=>D.entityShas||[])),T=new Set(((H=c.currentlyExecuting)==null?void 0:H.entityShas)||[]),R=s.filter(D=>D.entityType==="visual"||D.entityType==="library"),$=R.filter(D=>!j.has(D.sha)&&!A.has(D.sha)&&!T.has(D.sha)),J=()=>{if($.length===0){m("All entities are already queued or analyzing","info",3e3);return}const D=$.map(M=>M.sha);N(!0),m(`Starting analysis for ${$.length} entities...`,"info",3e3),h.submit({entityShas:D.join(",")},{method:"post",action:"/api/analyze"})};ee(()=>{if(h.state==="idle"&&h.data){const D=h.data;D.success?(console.log("[Analyze All] Success:",D.message),m(`Analysis started for ${D.entityCount} entities in ${D.fileCount} files. Watch the logs for progress.`,"success",6e3),N(!1)):D.error&&(console.error("[Analyze All] Error:",D.error),m(`Error: ${D.error}`,"error",8e3),N(!1))}},[h.state,h.data,m]);const q=D=>{f(M=>{const Q=new Set(M);return Q.has(D)?Q.delete(D):Q.add(D),Q})},Y=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12",children:[l("header",{className:"mb-8 flex justify-between items-center",children:[l("div",{className:"flex items-center gap-4",children:[n("img",{src:qx,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),n("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,D=>D.toUpperCase()):"Project"})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:Y.map((D,M)=>n(de,{to:D.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg no-underline cursor-pointer",style:{borderLeft:`4px solid ${D.color}`},children:l("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[l("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[l("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:D.label}),l("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[D.tooltip,n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:D.color},children:"View All →"})]}),l("div",{className:"flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${D.color}15`},children:[D.iconType==="folder"&&n(yc,{size:20,style:{color:D.color}}),D.iconType==="check"&&n(qs,{size:20,style:{color:D.color}}),D.iconType==="image"&&n(Rn,{size:20,style:{color:D.color}}),D.iconType==="code-xml"&&n(xc,{size:20,style:{color:D.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:D.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:D.color},children:"View All →"})]})]})},M))}),l("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[l("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[l("div",{className:"flex justify-between items-start mb-5",children:[l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),R.length>0&&n("button",{onClick:J,disabled:h.state!=="idle"||b||$.length===0,className:"px-5 py-2.5 text-white border-none rounded-lg text-sm font-semibold cursor-pointer transition-all hover:-translate-y-px disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:D=>D.currentTarget.style.backgroundColor="#004560",onMouseLeave:D=>D.currentTarget.style.backgroundColor="#005C75",children:h.state!=="idle"||b?"Starting analysis...":$.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([D,M])=>{const Q=p.has(D),W=M.editedEntities||[];return l("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>q(D),role:"button",tabIndex:0,children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:Q?"▼":"▶"}),l("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[l("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),l("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:D}),l("span",{className:"text-xs text-gray-500",children:[W.length," entit",W.length!==1?"ies":"y"]})]})]})}),Q&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:W.length>0?W.map(F=>{const te=j.has(F.sha),z=A.has(F.sha)||T.has(F.sha);return l(de,{to:`/entity/${F.sha}`,className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg no-underline transition-all hover:shadow-md hover:-translate-y-0.5",style:{borderColor:"inherit"},onMouseEnter:L=>L.currentTarget.style.borderColor="#005C75",onMouseLeave:L=>L.currentTarget.style.borderColor="inherit",children:[l("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:F.entityType==="visual"?"#8B5CF615":F.entityType==="library"?"#6366F1":"#EC4899"},children:[F.entityType==="visual"&&n(Rn,{size:16,style:{color:"#8B5CF6"}}),F.entityType==="library"&&n(Vo,{size:16,className:"text-white"}),F.entityType==="other"&&n(bc,{size:16,className:"text-white"})]}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:F.name}),F.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),F.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),F.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),F.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:F.description})]}),l("div",{className:"flex items-center gap-2 shrink-0",children:[te&&l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(dt,{size:14,className:"animate-spin"}),"Analyzing..."]}),!te&&z&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!te&&!z&&n("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),m(`Starting analysis for ${F.name}...`,"info",3e3),h.submit({entityShas:F.sha},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:L=>L.currentTarget.style.backgroundColor="#004560",onMouseLeave:L=>L.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},F.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},D)})}):l("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:l("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(Vx,{recentSimulations:a}),y&&l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:a.length>0?`Latest ${a.length} captured screenshot${a.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&l("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[C&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(et,{type:"visual"})}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",C.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:C.filePath})]})]})}),P?l("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),l("span",{children:["Complete (",S.length," scenario",S.length!==1?"s":"",")"]})]}):w?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(dt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:w,children:w}),i&&n("button",{onClick:()=>v(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):h.state!=="idle"?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(dt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(dt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),S.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:S.slice(0,8).map((D,M)=>{var V,B,X;const Q=(V=C==null?void 0:C.analyses)==null?void 0:V[0],W=Kr(D,Q==null?void 0:Q.status,void 0,y||void 0,void 0),F=(X=(B=D.metadata)==null?void 0:B.screenshotPaths)==null?void 0:X[0],te=W.isCaptured,z=W.status==="capturing"||W.status==="starting",L=W.hasError;return te?n(de,{to:`/entity/${y}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(Ge,{screenshotPath:F,alt:D.name,title:D.name,className:"max-w-full max-h-full object-contain object-center"})},M):L?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:W.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},M):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${z?"Capturing":"Pending"} ${D.name}...`,children:n("span",{className:z?"animate-pulse":"text-gray-400",children:z?"⋯":"⏹️"})},M)})})]})]})]}),x&&i&&n(It,{projectSlug:i,onClose:()=>v(!1)})]})})}),Zx=Object.freeze(Object.defineProperty({__proto__:null,default:Qx,loader:Kx,meta:Gx},Symbol.toStringTag,{value:"Module"}));function Al(e){const[t,r]=_(null),[s,a]=_(!1),o=ie(()=>{e&&(a(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(i=>i.json()).then(i=>{r(i),a(!1)}).catch(()=>{r({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),a(!1)}))},[e]);return ee(()=>{e&&o()},[e,o]),{results:t,isRunning:s,runTests:o}}function Pn({imgSrc:e,name:t,isActive:r,onSelect:s}){return l("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${r?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e?n("img",{src:e,alt:t,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-32 ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function As({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=Al(e);if(s&&!r)return l("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const o=t?r.testCases.filter(c=>{const d=`${t} > `;return c.fullName.startsWith(d)||c.fullName===t}):r.testCases;if(o.length===0)return null;const i=t?`${t} > `:"";return l("div",{className:"px-2 pt-1 space-y-0.5",children:[o.map(c=>{var h;const d=i&&c.fullName.startsWith(i)?c.fullName.slice(i.length):c.fullName;return l("div",{children:[l("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):c.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${c.status==="passed"?"text-green-400":c.status==="failed"?"text-red-400":"text-gray-500"}`,children:d})]}),c.status==="failed"&&((h=c.failureMessages)==null?void 0:h.map((u,m)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:u,children:u.split(`
333
+ `)[0]},m)))]},c.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function qt({filePath:e,projectRoot:t}){if(!e)return null;const s=`file://${t?`${t}/${e}`:e}`;return l("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[l("a",{href:s,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n("button",{onClick:()=>void navigator.clipboard.writeText(e),title:"Copy path",className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors bg-transparent border-none p-0 cursor-pointer",children:l("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:[n("rect",{x:"4",y:"4",width:"7",height:"7",rx:"1",stroke:"currentColor",strokeWidth:"1.2"}),n("path",{d:"M8 4V2C8 1.45 7.55 1 7 1H2C1.45 1 1 1.45 1 2V7C1 7.55 1.45 8 2 8H4",stroke:"currentColor",strokeWidth:"1.2"})]})})]})}function Xx(e){if(!e||e==="/")return"Home";const r=e.split("?")[0].replace(/^\//,"").split("/")[0];return r.charAt(0).toUpperCase()+r.slice(1)}function eb({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,onZoomChange:o,analyzedEntities:i=[],glossaryFunctions:c=[],activeAnalyzedScenarioId:d,onAnalyzedScenarioSelect:h,entityImports:u,pageFilePaths:m={}}){const{pageGroups:p,componentGroups:f}=re(()=>{const C=new Map,S=new Map;for(const P of e)if(P.componentName){const I=S.get(P.componentName)||[];I.push(P),S.set(P.componentName,I)}else{const I=Xx(P.url),j=C.get(I)||[];j.push(P),C.set(I,j)}const k=new Map([...S.entries()].sort(([P],[I])=>P.localeCompare(I)));return{pageGroups:C,componentGroups:k}},[e]),y=re(()=>{const C=new Set((i||[]).filter(k=>k.entityType==="visual").map(k=>k.name)),S=new Map;for(const[k,P]of f)C.has(k)||S.set(k,P);return S},[f,i]),{visualEntities:g,libraryEntities:x}=re(()=>{const C=i.filter(k=>k.entityType==="visual").sort((k,P)=>k.name.localeCompare(P.name)),S=i.filter(k=>k.entityType==="library"||k.entityType==="functionCall").sort((k,P)=>k.name.localeCompare(P.name));return{visualEntities:C,libraryEntities:S}},[i]),v=re(()=>{const C=new Set(x.map(S=>S.name));return c.filter(S=>!C.has(S.name)).sort((S,k)=>S.name.localeCompare(k.name))},[c,x]),b=i.some(C=>C.isAnalyzing),N=ve(null),w=ve(0),E=ie(()=>{N.current&&(w.current=N.current.scrollTop)},[]);if(ee(()=>{N.current&&w.current>0&&(N.current.scrollTop=w.current)}),e.length===0&&i.length===0&&v.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(a){const C=f.get(a)||[],S=new Set((u==null?void 0:u[a])||[]),k=S.size>0,P=k?g.filter(j=>S.has(j.name)):[],I=k?x.filter(j=>S.has(j.name)):[];return n("div",{className:"flex-1 overflow-auto",children:l("div",{className:"p-3 space-y-1",children:[l("button",{onClick:()=>o(void 0),className:"w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All scenarios"]}),n("div",{className:"px-3 py-1.5",children:n("span",{className:"text-xs font-semibold text-white uppercase tracking-wider",children:a})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:C.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):C.map(j=>n(Pn,{imgSrc:j.screenshotPath?`/api/editor-scenario-image/${j.id}.png`:null,name:j.name,isActive:j.id===r,onSelect:()=>s(j)},j.id))}),P.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),P.map(j=>l("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>o(j.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:j.name})}),n(qt,{filePath:j.filePath,projectRoot:t}),(j.scenarios.length>0||j.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:j.scenarios.map(A=>n(Pn,{imgSrc:A.screenshotPath?`/api/screenshot/${A.screenshotPath}`:null,name:A.name,isActive:A.id===d,onSelect:()=>h==null?void 0:h({analysisId:j.analysisId,scenarioId:A.id,scenarioName:A.name,entitySha:j.sha,entityName:j.name})},A.id))})]},j.sha))]}),I.length>0&&l("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),I.map(j=>l("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:j.name})}),n(qt,{filePath:j.filePath,projectRoot:t}),j.testFile&&n(As,{testFile:j.testFile,entityName:j.name})]},j.sha))]})]})})}return n("div",{ref:N,onScroll:E,className:"flex-1 overflow-auto",children:l("div",{className:"p-3 space-y-3",children:[p.size>0&&l("div",{children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),[...p.entries()].sort(([C],[S])=>C==="Home"?-1:S==="Home"?1:C.localeCompare(S)).map(([C,S])=>l("div",{className:"px-2 pt-1",children:[n("div",{className:"py-0.5",children:n("span",{className:"text-[11px] font-medium text-gray-400",children:C})}),m[C]&&n(qt,{filePath:m[C],projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:S.map(k=>n(Pn,{imgSrc:k.screenshotPath?`/api/editor-scenario-image/${k.id}.png`:null,name:k.name,isActive:k.id===r&&!d,onSelect:()=>s(k)},k.id))})]},C))]}),y.size>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...y.entries()].map(([C,S])=>{var k;return l("div",{className:"mt-2",children:[n("div",{className:"flex items-center justify-between px-2 py-1",children:n("button",{onClick:()=>o(C),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:C})}),((k=S[0])==null?void 0:k.componentPath)&&n(qt,{filePath:S[0].componentPath,projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:S.map(P=>n(Pn,{imgSrc:P.screenshotPath?`/api/editor-scenario-image/${P.id}.png`:null,name:P.name,isActive:P.id===r&&!d,onSelect:()=>s(P)},P.id))})]},C)})]}),g.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[l("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),b&&e.length===0&&i.every(C=>C.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),g.map(C=>l("div",{className:"mt-2",children:[l("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>o(C.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:C.name}),C.isAnalyzing&&C.scenarioCount===0&&l("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(qt,{filePath:C.filePath,projectRoot:t}),(C.scenarios.length>0||C.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[C.scenarios.map(S=>n(Pn,{imgSrc:S.screenshotPath?`/api/screenshot/${S.screenshotPath}`:null,name:S.name,isActive:S.id===d,onSelect:()=>h==null?void 0:h({analysisId:C.analysisId,scenarioId:S.id,scenarioName:S.name,entitySha:C.sha,entityName:C.name})},S.id)),C.pendingScenarios.map(S=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:S,children:S},S))]})]},C.sha))]}),(x.length>0||v.length>0)&&l("div",{className:`pt-2 mt-1 ${g.length>0?"":"border-t border-[#3d3d3d]"}`,children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),x.map(C=>l("div",{className:"mt-2",children:[l("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:C.name}),C.isAnalyzing&&C.scenarioCount===0&&l("span",{className:"ml-2 inline-flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(qt,{filePath:C.filePath,projectRoot:t}),C.testFile?n(As,{testFile:C.testFile,entityName:C.name}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},C.sha)),v.map(C=>l("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:C.name})}),n(qt,{filePath:C.filePath,projectRoot:t}),n(As,{testFile:C.testFile,entityName:C.name})]},C.name))]})]})})}const tb={feature:{label:"Feature",color:"bg-[#005c75]"},fix:{label:"Fix",color:"bg-amber-700"},refactor:{label:"Refactor",color:"bg-purple-700"},scaffold:{label:"Scaffold",color:"bg-green-700"},data:{label:"Data",color:"bg-blue-700"},milestone:{label:"Milestone",color:"bg-yellow-600"}};function nb(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function rb(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}function sb({isActive:e,onScreenshotClick:t}){const[r,s]=_([]),[a,o]=_(!0),[i,c]=_(new Set),d=ie(m=>{c(p=>{const f=new Set(p);return f.has(m)?f.delete(m):f.add(m),f})},[]),h=ie(async()=>{try{const m=await fetch("/api/editor-journal");if(m.ok){const p=await m.json();s(p.entries||[])}}catch{}finally{o(!1)}},[]);if(ee(()=>{h()},[h]),ee(()=>{e&&h()},[e,h]),ee(()=>{const m=new EventSource("/api/events");return m.addEventListener("message",p=>{try{const f=JSON.parse(p.data);f.type==="db-change"&&f.changeType==="journal"&&h()}catch{}}),()=>m.close()},[h]),a)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(r.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const u=Qp(r);return n("div",{className:"flex-1 overflow-auto",children:n("div",{className:"p-3 space-y-4",children:[...u.entries()].map(([m,p])=>l("div",{children:[n("div",{className:"px-3 py-1.5 sticky top-0 bg-[#1e1e1e] z-10",children:n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:rb(m)})}),n("div",{className:"space-y-2",children:p.map((f,y)=>{const g=tb[f.type]||{label:f.type,color:"bg-gray-600"},x=`${f.time}-${y}`,v=i.has(x);return l("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[l("div",{className:`p-3 space-y-2 ${v?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2",children:l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:f.title}),n("span",{className:`${g.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:g.label})]}),n("span",{className:"text-[10px] text-gray-500",children:nb(f.time)})]})}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:f.description}),f.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${f.screenshot.replace("screenshots/","")}`,commitSha:f.commitSha,commitMessage:f.commitMessage,scenarioName:f.title}),children:n("img",{src:`/api/editor-journal-image/${f.screenshot.replace("screenshots/","")}`,alt:f.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),f.scenarioScreenshots&&f.scenarioScreenshots.length>0&&(()=>{const b=Zp(f.scenarioScreenshots);return n("div",{className:"space-y-1.5",children:b.map(([N,w])=>l("div",{children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:N}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:w.map(E=>n("button",{type:"button",className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${E.path.replace("screenshots/","")}`,commitSha:f.commitSha,commitMessage:f.commitMessage,scenarioName:E.name}),children:n("img",{src:`/api/editor-journal-image/${E.path.replace("screenshots/","")}`,alt:E.name,title:E.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},E.path))})]},N))})})(),f.commitSha&&l("div",{className:"flex items-center gap-1.5 text-[10px]",children:[n("span",{className:"font-mono text-[#00a0c4] bg-[#00a0c4]/10 px-1.5 py-0.5 rounded",children:f.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:f.commitMessage})]})]}),l("button",{onClick:()=>d(x),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",v?"Collapse":"Expand"," ———"]})]},x)})})]},m))})})}function Tt({imgSrc:e,name:t,isActive:r,onSelect:s}){return l("button",{onClick:s,className:"flex flex-col items-center gap-1 cursor-pointer group",title:t,children:[n("div",{className:`w-24 h-24 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${r?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e?n("img",{src:e,alt:t,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-24 ${r?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:t})]})}function Oo({filePath:e,projectRoot:t}){if(!e)return null;const s=`file://${t?`${t}/${e}`:e}`;return l("div",{className:"flex items-center gap-1 mt-0.5",children:[l("a",{href:s,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n("button",{onClick:()=>void navigator.clipboard.writeText(e),title:"Copy path",className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors bg-transparent border-none p-0 cursor-pointer",children:l("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:[n("rect",{x:"4",y:"4",width:"7",height:"7",rx:"1",stroke:"currentColor",strokeWidth:"1.2"}),n("path",{d:"M8 4V2C8 1.45 7.55 1 7 1H2C1.45 1 1 1.45 1 2V7C1 7.55 1.45 8 2 8H4",stroke:"currentColor",strokeWidth:"1.2"})]})})]})}function ab(e){if(!e||e==="/")return"Home";const r=e.split("?")[0].replace(/^\//,"").split("/")[0];return r.charAt(0).toUpperCase()+r.slice(1)}function ob({hasProject:e,scenarios:t,analyzedEntities:r,glossaryFunctions:s=[],projectRoot:a,activeScenarioId:o,onScenarioSelect:i,onAnalyzedScenarioSelect:c,onSwitchToBuild:d,zoomComponent:h,onZoomChange:u,entityImports:m,pageFilePaths:p={}}){const{pageGroups:f,componentGroups:y}=re(()=>{const w=new Map,E=new Map;for(const S of t)if(S.componentName){const k=E.get(S.componentName)||[];k.push(S),E.set(S.componentName,k)}else{const k=ab(S.url),P=w.get(k)||[];P.push(S),w.set(k,P)}const C=new Map([...E.entries()].sort(([S],[k])=>S.localeCompare(k)));return{pageGroups:w,componentGroups:C}},[t]),g=ve(null),x=ve(0),v=ie(()=>{g.current&&(x.current=g.current.scrollTop)},[]);if(ee(()=>{g.current&&x.current>0&&(g.current.scrollTop=x.current)}),!e)return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Ready to build something?"}),n("button",{onClick:d,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});const b=re(()=>r.filter(w=>w.entityType==="visual").sort((w,E)=>w.name.localeCompare(E.name)),[r]);if(!(t.length>0||b.length>0))return n("div",{className:"flex-1 flex items-center justify-center",children:l("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] leading-relaxed max-w-[280px]",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:d,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});if(h){const w=f.get(h)||[],E=y.get(h)||[],C=b.find(A=>A.name===h),S=f.has(h),k=new Set((m==null?void 0:m[h])||[]),P=k.size>0,I=P?[...y.entries()].filter(([A])=>k.has(A)):[...y.entries()],j=P?b.filter(A=>k.has(A.name)):b;return n("div",{className:"flex-1 overflow-auto",children:l("div",{className:"p-4 space-y-3",children:[l("button",{onClick:()=>u(void 0),className:"flex items-center gap-2 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All"]}),n("h2",{className:"text-sm font-semibold text-white m-0 font-['IBM_Plex_Sans'] uppercase tracking-wider",children:h}),w.length>0&&n("div",{className:"flex flex-wrap gap-2",children:w.map(A=>n(Tt,{imgSrc:A.screenshotPath?`/api/editor-scenario-image/${A.id}.png`:null,name:A.name,isActive:A.id===o,onSelect:()=>i(A)},A.id))}),E.length>0&&n("div",{className:"flex flex-wrap gap-2",children:E.map(A=>n(Tt,{imgSrc:A.screenshotPath?`/api/editor-scenario-image/${A.id}.png`:null,name:A.name,isActive:A.id===o,onSelect:()=>i(A)},A.id))}),C&&(C.scenarios.length>0||C.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2",children:[C.scenarios.map(A=>n(Tt,{imgSrc:A.screenshotPath?`/api/screenshot/${A.screenshotPath}`:null,name:A.name,isActive:!1,onSelect:()=>c({analysisId:C.analysisId,scenarioId:A.id,scenarioName:A.name,entitySha:C.sha,entityName:C.name})},A.id)),C.pendingScenarios.map(A=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:A,children:A},A))]}),S&&I.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),I.map(([A,T])=>l("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(A),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:A})}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:T.map(R=>n(Tt,{imgSrc:R.screenshotPath?`/api/editor-scenario-image/${R.id}.png`:null,name:R.name,isActive:R.id===o,onSelect:()=>i(R)},R.id))})]},A))]}),S&&j.length>0&&l("div",{className:`${I.length===0?"pt-2 mt-1 border-t border-[#3d3d3d]":"mt-2"}`,children:[I.length===0&&n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),j.map(A=>l("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(A.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:A.name})}),(A.scenarios.length>0||A.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 pt-1",children:[A.scenarios.map(T=>n(Tt,{imgSrc:T.screenshotPath?`/api/screenshot/${T.screenshotPath}`:null,name:T.name,isActive:!1,onSelect:()=>c({analysisId:A.analysisId,scenarioId:T.id,scenarioName:T.name,entitySha:A.sha,entityName:A.name})},T.id)),A.pendingScenarios.map(T=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:T,children:T},T))]})]},A.sha))]}),w.length===0&&E.length===0&&!C&&n("div",{className:"text-xs text-gray-500",children:"No scenarios for this entity"})]})})}return n("div",{ref:g,onScroll:v,className:"flex-1 overflow-auto",children:l("div",{className:"p-4 space-y-4",children:[n("h2",{className:"text-sm font-medium text-gray-300 m-0 font-['IBM_Plex_Sans']",children:"What do you want to work on next?"}),n("button",{onClick:d,className:"w-full py-3 border-2 border-dashed border-[#4d4d4d] rounded-lg text-sm text-gray-400 hover:border-[#005c75] hover:text-white transition-colors cursor-pointer bg-transparent",children:"+ New Page"}),f.size>0&&l("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),[...f.entries()].sort(([w],[E])=>w==="Home"?-1:E==="Home"?1:w.localeCompare(E)).map(([w,E])=>l("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(w),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:w})}),p[w]&&n(Oo,{filePath:p[w],projectRoot:a}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:E.map(C=>n(Tt,{imgSrc:C.screenshotPath?`/api/editor-scenario-image/${C.id}.png`:null,name:C.name,isActive:C.id===o,onSelect:()=>i(C)},C.id))})]},w))]}),y.size>0&&n("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),[...y.entries()].map(([w,E])=>l("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>u(w),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:w})}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:E.map(C=>n(Tt,{imgSrc:C.screenshotPath?`/api/editor-scenario-image/${C.id}.png`:null,name:C.name,isActive:C.id===o,onSelect:()=>i(C)},C.id))})]},w)),b.map(w=>l("div",{children:[l("div",{className:"flex items-center gap-2 py-1",children:[n("button",{onClick:()=>u(w.name),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:w.name}),w.isAnalyzing&&w.scenarioCount===0&&l("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),(w.scenarios.length>0||w.pendingScenarios.length>0)&&l("div",{className:"flex flex-wrap gap-2 pt-1",children:[w.scenarios.map(E=>n(Tt,{imgSrc:E.screenshotPath?`/api/screenshot/${E.screenshotPath}`:null,name:E.name,isActive:!1,onSelect:()=>c({analysisId:w.analysisId,scenarioId:E.id,scenarioName:E.name,entitySha:w.sha,entityName:w.name})},E.id)),w.pendingScenarios.map(E=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:E,children:E},E))]})]},w.sha)),s.length>0&&l("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),s.map(w=>l("div",{className:"mt-2",children:[l("div",{className:"flex items-center gap-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:w.name}),w.testFile&&n("span",{className:"text-[9px] text-green-400 bg-green-400/10 px-1.5 py-0.5 rounded",children:"tested"})]}),w.description&&n("p",{className:"text-[10px] text-gray-500 mt-0 mb-0 leading-relaxed",children:w.description}),n(Oo,{filePath:w.filePath,projectRoot:a})]},w.name))]})]})})}function ib({items:e,onNavigate:t}){return e.length===0?null:n("nav",{className:"flex items-center gap-1 text-xs",children:e.map((r,s)=>{const a=s===e.length-1;return l("span",{className:"flex items-center gap-1",children:[s>0&&n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),a?n("span",{className:"text-white font-medium",children:r.name}):n("button",{onClick:()=>t(r.componentName),className:"text-gray-400 hover:text-white transition-colors cursor-pointer",children:r.name})]},r.componentName||"app")})})}function Fo({scenarioId:e,name:t,isActive:r,onSelect:s}){const[a,o]=_(!1);return l("button",{onClick:s,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all ${r?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:a?n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center",children:n("span",{className:"text-[9px] text-gray-400",children:"No preview"})}):n("img",{src:`/api/editor-scenario-image/${e}.png`,alt:t,className:"w-full h-full object-contain bg-white",loading:"lazy",onError:()=>o(!0)})}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${r?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:t})]})}function lb({filePath:e,projectRoot:t}){if(!e)return null;const s=`file://${t?`${t}/${e}`:e}`;return l("div",{className:"flex items-center gap-1 mt-0.5",children:[l("a",{href:s,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-400 hover:text-gray-600 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n("button",{onClick:()=>void navigator.clipboard.writeText(e),title:"Copy path",className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors bg-transparent border-none p-0 cursor-pointer",children:l("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:[n("rect",{x:"4",y:"4",width:"7",height:"7",rx:"1",stroke:"currentColor",strokeWidth:"1.2"}),n("path",{d:"M8 4V2C8 1.45 7.55 1 7 1H2C1.45 1 1 1.45 1 2V7C1 7.55 1.45 8 2 8H4",stroke:"currentColor",strokeWidth:"1.2"})]})})]})}function cb({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=Al(e);if(s&&!r)return l("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:r.errorMessage})});const o=t?r.testCases.filter(c=>{const d=`${t} > `;return c.fullName.startsWith(d)||c.fullName===t}):r.testCases;if(o.length===0)return null;const i=t?`${t} > `:"";return l("div",{className:"pt-1 space-y-0.5",children:[o.map(c=>{var h;const d=i&&c.fullName.startsWith(i)?c.fullName.slice(i.length):c.fullName;return l("div",{children:[l("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):c.status==="failed"?n("span",{className:"text-red-500 text-[10px]",children:"✗"}):n("span",{className:"text-gray-400 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${c.status==="passed"?"text-green-600":c.status==="failed"?"text-red-500":"text-gray-400"}`,children:d})]}),c.status==="failed"&&((h=c.failureMessages)==null?void 0:h.map((u,m)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:u,children:u.split(`
334
+ `)[0]},m)))]},c.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function db(e){if(!e||e==="/")return"Home";const r=e.split("?")[0].replace(/^\//,"").split("/")[0];return r.charAt(0).toUpperCase()+r.slice(1)}function ub({scenarios:e,glossaryFunctions:t=[],projectRoot:r,activeScenarioId:s,onScenarioSelect:a,onClose:o}){const{pageGroups:i,componentGroups:c}=re(()=>{const d=new Map,h=new Map;for(const m of e)if(m.componentName){const p=h.get(m.componentName)||[];p.push(m),h.set(m.componentName,p)}else{const p=db(m.url),f=d.get(p)||[];f.push(m),d.set(p,f)}const u=new Map([...h.entries()].sort(([m],[p])=>m.localeCompare(p)));return{pageGroups:d,componentGroups:u}},[e]);return e.length===0&&t.length===0?l("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:o,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):l("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[l("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),n("button",{onClick:o,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"})]}),n("div",{className:"flex-1 overflow-auto p-4",children:l("div",{className:"space-y-5",children:[i.size>0&&l("div",{children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),n("div",{className:"space-y-3 pl-1",children:[...i.entries()].sort(([d],[h])=>d==="Home"?-1:h==="Home"?1:d.localeCompare(h)).map(([d,h])=>l("div",{children:[n("div",{className:"mb-1.5",children:n("span",{className:"text-[11px] font-medium text-gray-600",children:d})}),n("div",{className:"flex flex-wrap gap-3",children:h.map(u=>n(Fo,{scenarioId:u.id,name:u.name,isActive:u.id===s,onSelect:()=>a(u)},u.id))})]},d))})]}),c.size>0&&l("div",{className:i.size>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),n("div",{className:"space-y-3 pl-1",children:[...c.entries()].map(([d,h])=>l("div",{children:[n("div",{className:"mb-1.5",children:n("span",{className:"text-[11px] font-medium text-gray-600",children:d})}),n("div",{className:"flex flex-wrap gap-3",children:h.map(u=>n(Fo,{scenarioId:u.id,name:u.name,isActive:u.id===s,onSelect:()=>a(u)},u.id))})]},d))})]}),t.length>0&&l("div",{className:e.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:t.map(d=>l("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:d.name})}),n(lb,{filePath:d.filePath,projectRoot:r}),d.testFile?n(cb,{testFile:d.testFile,entityName:d.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},d.name))})]})]})})]})}function hb(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:a,proxyUrl:o,devServerUrl:i,zoomComponent:c}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const h=a.find(u=>u.id===s);if(h!=null&&h.url){const u=o||i;return u?h.url.startsWith("/")?`${u}${h.url}`:h.url:null}}const d=o||i;if(!d)return null;if(c&&s){const h=a.find(m=>m.id===s),u=h?Gt(h.name):"Default";return`${d}/__codeyam__/${c}/${u}`}return d}function mb(e,t){const r=t.width,s=t.height??900,a=e.width,o=e.height;return r<=a&&s<=o?1:Math.min(a/r,o/s)}const pb=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];async function fb({request:e}){var u,m;const t=await $e();let r=!1,s=[];if(t){const{project:p}=await Ie(t);r=((u=p.metadata)==null?void 0:u.editorMode)??!1;try{const f=Te();for(const N of["component_name","component_path","screenshot_path","url"])try{await f.schema.alterTable("editor_scenarios").addColumn(N,"varchar").execute()}catch{}const y=ge()||process.cwd(),g=O.join(y,".codeyam","editor-step.json");let x=null;try{const N=K.readFileSync(g,"utf8");x=JSON.parse(N).featureStartedAt||null}catch{}let v=f.selectFrom("editor_scenarios").selectAll().where("project_id","=",p.id);if(x){const N=Os(x);v=v.where("created_at",">=",N)}const b=await v.orderBy("created_at","asc").execute();if(s=ua(b,N=>`${N.name}::${N.url||"/"}`).map(N=>({id:N.id,name:N.name,description:N.description||"",componentName:N.component_name||null,componentPath:N.component_path||null,screenshotPath:N.screenshot_path||null,url:N.url||null})),x){const N=S=>!S||S==="/"?"/":"/"+S.split("?")[0].replace(/^\//,"").split("/")[0],w=new Set(s.filter(S=>!S.componentName).map(S=>N(S.url))),E=Os(x),C=await f.selectFrom("editor_scenarios").selectAll().where("project_id","=",p.id).where("component_name","is",null).where("created_at","<",E).orderBy("created_at","desc").execute();for(const S of C){const k=N(S.url||null);w.has(k)||s.push({id:S.id,name:S.name,description:S.description||"",componentName:null,componentPath:null,screenshotPath:S.screenshot_path||null,url:S.url||null})}}}catch{}}const a=[...new Set(s.map(p=>p.componentName).filter(p=>p!==null))];let o=[];try{const p=ge()||process.cwd(),f=O.join(p,".codeyam","glossary.json");if(K.existsSync(f)){const y=K.readFileSync(f,"utf8");o=JSON.parse(y)}}catch{}const i=o.filter(p=>p.testFile&&p.returnType!=="JSX.Element"&&p.returnType!=="React.ReactNode").map(p=>({name:p.name,filePath:p.filePath,description:p.description||"",testFile:p.testFile,feature:p.feature}));let c=[];try{c=(await rn()||[]).filter(f=>f.analyses&&f.analyses.length>0).map(f=>{var C;const y=f.analyses[0],g=y.scenarios||[],x=!((C=y.status)!=null&&C.finishedAt),v=f.entityType||"visual",b=v==="library"||v==="functionCall",N=g.filter(S=>{var k,P,I,j,A;return b?!!((k=S.metadata)!=null&&k.executionResult):((I=(P=S.metadata)==null?void 0:P.screenshotPaths)==null?void 0:I[0])&&!((j=S.metadata)!=null&&j.noScreenshotSaved)&&!((A=S.metadata)!=null&&A.sameAsDefault)}),w=g.filter(S=>{var k,P,I,j;return b?!((k=S.metadata)!=null&&k.executionResult):!((I=(P=S.metadata)==null?void 0:P.screenshotPaths)!=null&&I[0])||((j=S.metadata)==null?void 0:j.noScreenshotSaved)}),E=o.find(S=>S.filePath===(f.filePath||""));return{sha:f.sha,name:f.name,entityType:v,filePath:f.filePath||"",analysisId:y.id,isAnalyzing:x,scenarioCount:g.length,scenarios:N.map(S=>{var k,P;return{id:S.id,name:S.name,description:S.description||"",screenshotPath:((P=(k=S.metadata)==null?void 0:k.screenshotPaths)==null?void 0:P[0])||null}}),pendingScenarios:w.map(S=>S.name),testFile:E==null?void 0:E.testFile}})}catch{}const d={};try{if(c.length>0){const p=c.map(y=>y.sha);await Je();const f=await ut({shas:p});if(f&&f.length>0){const y=new Set([...c.map(g=>g.name),...a]);for(const g of f){const v=(((m=g.metadata)==null?void 0:m.importedExports)||[]).map(b=>b.name).filter(b=>y.has(b));v.length>0&&(d[g.name]=v)}}}}catch{}const h={};try{const p=ge()||process.cwd(),f=O.join(p,"app");if(K.existsSync(f)){const y=(g,x)=>{for(const v of K.readdirSync(g,{withFileTypes:!0}))if(v.name!=="codeyam-isolate"){if(v.isDirectory())y(O.join(g,v.name),x?`${x}/${v.name}`:v.name);else if(v.name==="page.tsx"||v.name==="page.js"){const b=x?`app/${x}/${v.name}`:`app/${v.name}`;let N;if(!x)N="Home";else{const w=x.split("/")[0];N=w.charAt(0).toUpperCase()+w.slice(1)}h[N]=b}}};y(f,"")}}catch{}return G({projectSlug:t,projectRoot:ge(),hasProject:!!t,editorMode:r,devServerUrl:null,scenarios:s,components:a,analyzedEntities:c,glossaryFunctions:i,entityImports:d,pageFilePaths:h})}const Ps=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}];function gb({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:c,isLoading:d}=sn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return ee(()=>{o(i,c||d)},[i,c,d,o]),null}const yb=He(function(){const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,analyzedEntities:o,glossaryFunctions:i,entityImports:c,pageFilePaths:d}=qe(),h=mt(),[u,m]=fn(),p=ve(null),f=ve(null),y=ve(null),g=u.get("zoom")||void 0,x=u.get("scenario")||void 0;ee(()=>{if(!x)return;const se=a.find(ke=>ke.id===x);if(!se)return;const fe=Gt(se.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:fe,scenarioId:se.id})}).catch(()=>{})},[x,a]),ee(()=>{const se=new BroadcastChannel("codeyam-editor");return se.onmessage=fe=>{var ke;if(((ke=fe.data)==null?void 0:ke.type)==="switch-scenario"&&fe.data.scenarioId){const Re=fe.data.scenarioId,We=a.find(on=>on.id===Re);if(!We)return;const Wt=new URLSearchParams(u);Wt.set("scenario",Re),Wt.delete("zoom"),m(Wt),R(null),J(null),H(null);const Vn=Gt(We.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Vn,scenarioId:Re})}).then(()=>{_t(on=>on+1),I(!1)}).catch(()=>{})}},()=>se.close()},[u,m,a]),ee(()=>{if(u.get("ref")!=="link"||!x)return;const se=new BroadcastChannel("codeyam-editor");se.postMessage({type:"switch-scenario",scenarioId:x}),se.close(),window.close()},[]);const[v,b]=_(null),[N,w]=_(null),[E,C]=_(!1),[S,k]=_(null),[P,I]=_(!1),[j,A]=_(!0),[T,R]=_(null),[$,J]=_(null),[q,Y]=_(!1),[U,H]=_(null),[D,M]=_(!1),[Q,W]=_(null),F=ie(se=>{H(se),W(null)},[]),te=ie((se,fe)=>{J(ke=>(se&&se!==ke&&I(!1),se)),!fe&&se&&I(!0),Y(fe)},[]),z=ie(se=>{H(null),R(ke=>(ke&&ke.analysisId===se.analysisId||(J(null),_t(We=>We+1)),se)),Y(!0),I(!1);const fe=new URLSearchParams(u);fe.delete("scenario"),fe.delete("zoom"),m(fe)},[u,m]),[L,V]=_(1440),[B,X]=_({name:"Desktop",width:1440,height:900}),[ce,we]=_(!1),[ae,he]=_(null),[ye,Me]=_("app"),je=ie(()=>{Me("build"),Le(!0)},[]),[De,Le]=_(!1),[Ee,ne]=_(!1),xe=ie(se=>{ne(se)},[]),[Ce,it]=_(!1),pe=ie(()=>{it(!0),Me("build"),Le(!0)},[]),Ye=ie(()=>{it(!1)},[]),[Fe,gt]=_(!1),Pa=ie(()=>{if(Fe){gt(!1);return}typeof Notification<"u"&&Notification.permission==="default"?Notification.requestPermission().then(se=>{se==="granted"&&gt(!0)}):gt(!0)},[Fe]);ee(()=>{if(ye==="build"){ne(!1);const se=setTimeout(()=>{var fe,ke;(fe=p.current)==null||fe.scrollToBottom(),(ke=p.current)==null||ke.focus()},50);return()=>clearTimeout(se)}},[ye]);const[Wn,_a]=_(null);ee(()=>{const se=y.current;if(!se)return;const fe=new ResizeObserver(ke=>{const Re=ke[0];Re&&_a({width:Re.contentRect.width,height:Re.contentRect.height})});return fe.observe(se),()=>fe.disconnect()},[]);const nt=re(()=>Wn?mb(Wn,B):1,[Wn,B]),[Bt,_t]=_(0),[Yt,Hn]=_(null),wn=ie(se=>{Hn(se||null),_t(fe=>fe+1)},[]),{customSizes:Ze,addCustomSize:yt}=Jr(t),Ue=re(()=>[...Ps,...Ze],[Ze]),Ve=ve(!1);ee(()=>{let se=!1,fe=null;const ke=async()=>{try{const Re=await fetch("/api/editor-dev-server");if(se)return;const We=await Re.json();if(We.status==="error")b(null),w(null),C(!1),k(We.errorMessage||"Dev server crashed");else if(We.url)b(We.url),w(We.proxyUrl||null),C(!1),k(null),A(!0);else if(We.status==="starting")C(!0),k(null),A(!0);else if(We.status==="stopped")if(v)b(null),C(!1);else if(Ve.current)C(!1);else{Ve.current=!0;try{(await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})})).ok?C(!0):A(!1)}catch{}}}catch{}};return ke(),fe=setInterval(()=>void ke(),2e3),()=>{se=!0,fe&&clearInterval(fe)}},[v]),ee(()=>{const se=new EventSource("/api/events");let fe=null;return se.addEventListener("message",ke=>{try{const Re=JSON.parse(ke.data);(Re.type==="db-change"||Re.type==="unknown")&&(fe&&clearTimeout(fe),fe=setTimeout(()=>{h.revalidate()},2e3))}catch{}}),()=>{fe&&clearTimeout(fe),se.close()}},[h]);const Xr=re(()=>{const se=[{name:"App"}];return g&&se.push({name:g,componentName:g}),se},[g]),Ut=ie(se=>{const fe=new URLSearchParams(u);if(se){fe.set("zoom",se);const ke=a.find(Re=>Re.componentName===se||Re.componentName===null&&se==="Home");if(ke){fe.set("scenario",ke.id);const Re=Gt(ke.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Re,scenarioId:ke.id})}).catch(()=>{}),_t(We=>We+1),I(!1)}else fe.delete("scenario")}else fe.delete("zoom"),fe.delete("scenario");m(fe)},[u,m,a]),an=ie(se=>{R(null),J(null),H(null);const fe=new URLSearchParams(u);fe.set("scenario",se.id),m(fe);const ke=Gt(se.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:ke,scenarioId:se.id})}).catch(()=>{}),_t(Re=>Re+1),I(!1)},[u,m]),es=(se,fe)=>{V(se);const ke=Ue.find(Re=>Re.width===se&&Re.height===fe);X({name:(ke==null?void 0:ke.name)||"Custom",width:se,height:fe})},Nn=se=>{V(se.width),X({name:se.name,width:se.width,height:se.height})},Jn=se=>{yt(se,B.width,B.height??900),we(!1),X(fe=>({...fe,name:se}))},ts=()=>{T||I(!0)},ns=ie(()=>{k(null),C(!0),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),rs=ie(()=>{k(null),C(!0),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]),lt=re(()=>hb({activeAnalyzedScenario:!!T,analyzedPreviewUrl:$,activeScenarioId:x||null,scenarios:a,proxyUrl:N,devServerUrl:v,zoomComponent:g||null}),[N,v,g,x,a,T,$]),ss=re(()=>{if(!lt||!Yt)return lt;try{const se=new URL(lt);return se.pathname=Yt,se.href}catch{return lt}},[lt,Yt]);return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[T&&n(gb,{analysisId:T.analysisId,scenarioId:T.scenarioId,scenarioName:T.scenarioName,entityName:T.entityName,projectSlug:t,onStateChange:te},T.analysisId),n("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:$r,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:"Editor"}),g&&l(ue,{children:[n("div",{className:"w-px h-4 bg-gray-600"}),n(ib,{items:Xr,onNavigate:Ut})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-auto",children:"Code + Data"})]})}),l("div",{className:"flex-1 flex min-h-0",children:[l("div",{className:"flex-1 flex flex-col min-w-0",children:[l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Ps[Ps.length-1].width}px`,width:"100%"},children:n(Wr,{currentViewportWidth:L,currentPresetName:B.name,onDevicePresetClick:Nn,devicePresets:Ue,hideLabel:!0,onHoverChange:he,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(ae==null?void 0:ae.name)||B.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:B.name,onChange:se=>{const fe=Ue.find(ke=>ke.name===se.target.value);fe&&Nn(fe)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[Ue.map(se=>n("option",{value:se.name,children:se.name},se.name)),B.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:B.width,onChange:se=>{const fe=parseInt(se.target.value,10);!isNaN(fe)&&fe>0&&es(fe,B.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"x"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:B.height??900}),B.name==="Custom"&&n("button",{onClick:()=>we(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{ref:y,className:"flex-1 flex items-center justify-center overflow-hidden p-8",style:{backgroundImage:`
335
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
336
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
337
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
338
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
339
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:U?l("div",{className:"flex flex-col items-center gap-6 max-w-[700px] w-full",children:[l("div",{className:"text-center",children:[n("h2",{className:"text-lg font-semibold text-[#333] m-0 font-['IBM_Plex_Sans']",children:"Journal Screenshot"}),n("p",{className:"text-sm text-[#888] mt-1 m-0 font-['IBM_Plex_Sans']",children:"This is a snapshot from a previous version — not a live preview"})]}),n("div",{className:"rounded-lg overflow-hidden border-2 border-[#ccc] shadow-md max-w-full w-fit",children:n("img",{src:U.screenshotUrl,alt:U.scenarioName,className:"max-w-full h-auto block"})}),l("div",{className:"flex items-center gap-2 text-sm text-[#666]",children:[U.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:U.commitSha.slice(0,7)}),l("span",{className:"truncate",children:[U.scenarioName,U.commitMessage&&` — ${U.commitMessage}`]})]}),l("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>H(null),className:"text-sm text-[#888] hover:text-[#333] transition-colors cursor-pointer px-3 py-1.5 rounded border border-[#ccc] hover:border-[#999] bg-white",children:"Back to live preview"}),U.commitSha&&n("button",{onClick:()=>{M(!0),W(null),fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:U.commitSha})}).then(se=>se.json()).then(se=>{se.success?(H(null),C(!0),I(!1)):W(se.error||"Failed to load commit")}).catch(se=>{W(se instanceof Error?se.message:"Network error")}).finally(()=>{M(!1)})},disabled:D,className:"bg-[#005c75] hover:bg-[#004d63] disabled:opacity-50 text-white text-sm font-medium px-4 py-1.5 rounded transition-colors cursor-pointer",children:D?"Loading...":"Load this version"})]}),Q&&n("div",{className:"bg-red-50 border border-red-200 rounded px-4 py-2 text-sm text-red-600 w-full text-center",children:Q})]}):lt?n("div",{style:{width:`${B.width*nt}px`,height:`${(B.height??900)*nt}px`},children:l("div",{className:"relative bg-white origin-top-left",style:{width:`${B.width}px`,height:`${B.height??900}px`,transform:nt<1?`scale(${nt})`:void 0},children:[!P&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Lt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),n("iframe",{ref:f,src:ss||lt,className:"w-full h-full border-none",title:"Editor preview",onLoad:ts,style:{opacity:P?1:0}},Bt)]})}):n("div",{className:"bg-white rounded-lg shadow-sm flex flex-col items-center justify-center",style:{width:`${B.width*nt}px`,height:`${(B.height??900)*nt}px`},children:S?l("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-600 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-gray-100 text-gray-800 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:S}),n("button",{onClick:ns,className:"mx-auto px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Retry"})]}):E||q?l(ue,{children:[n("div",{className:"mb-4",children:n(Lt,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:q?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:q?"Loading component preview...":"Your dev server is starting up..."})]})]}):l("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Code + Data Editor"}),n("p",{className:"text-sm text-[#888] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the chat"})]})})})]}),l("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-r border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden order-first",children:[l("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-0",children:[l("button",{onClick:()=>Me("app"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${ye==="app"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["App",ye==="app"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>{Me("build"),Le(!0)},className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${ye==="build"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Build",Ee&&ye!=="build"&&n("span",{className:"ml-1.5 inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),ye==="build"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>Me("data"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${ye==="data"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Data",ye==="data"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),l("button",{onClick:()=>Me("journal"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${ye==="journal"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Journal",ye==="journal"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),typeof Notification<"u"&&n("button",{onClick:Pa,className:`px-2 py-1 text-[10px] rounded transition-colors cursor-pointer ${Fe?"text-green-400 hover:text-green-300":"text-gray-500 hover:text-gray-300"}`,title:Fe?"Click to turn off notifications":"Click to get notified when Claude finishes",children:Fe?"Notifications On":"Notifications Off"})]}),l("div",{className:"flex-1 overflow-hidden relative",children:[De&&l("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:ye==="build"?"visible":"hidden"},children:[n("div",{className:Ce?"flex-1 min-h-0":"flex-1",style:Ce?{flex:"1 1 50%"}:void 0,children:n(Ri,{ref:p,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:wn,onShowResults:pe,onHideResults:Ye,editorMode:!0,onIdleChange:xe,notificationsEnabled:Fe})}),Ce&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(ub,{scenarios:a,glossaryFunctions:i,projectRoot:r,activeScenarioId:x,onScenarioSelect:an,onClose:Ye})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:ye==="app"?"visible":"hidden"},children:n(ob,{hasProject:s,scenarios:a,analyzedEntities:[],glossaryFunctions:i,projectRoot:r,activeScenarioId:x,onScenarioSelect:an,onAnalyzedScenarioSelect:z,onSwitchToBuild:je,zoomComponent:g,onZoomChange:Ut,entityImports:c,pageFilePaths:d})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:ye==="data"?"visible":"hidden"},children:n(eb,{scenarios:a,projectRoot:r,activeScenarioId:x,onScenarioSelect:an,zoomComponent:g,onZoomChange:Ut,analyzedEntities:[],glossaryFunctions:i,activeAnalyzedScenarioId:T==null?void 0:T.scenarioId,onAnalyzedScenarioSelect:z,entityImports:c,pageFilePaths:d})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:ye==="journal"?"visible":"hidden"},children:n(sb,{isActive:ye==="journal",onScreenshotClick:F})})]})]})]}),n($i,{serverUrl:v,isStarting:E,projectSlug:t,devServerError:S,onStartServer:j?rs:void 0}),ce&&n(Hr,{width:B.width,height:B.height??900,onSave:Jn,onCancel:()=>we(!1)})]})}),xb=Object.freeze(Object.defineProperty({__proto__:null,default:yb,loader:fb,meta:pb},Symbol.toStringTag,{value:"Module"}));function Pl({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Kc,{remarkPlugins:[Qc],components:{h1:({children:s})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:s}),h2:({children:s})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:s}),h3:({children:s})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:s}),p:({children:s})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:s}),ul:({children:s})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),ol:({children:s})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),li:({children:s})=>n("li",{className:"leading-relaxed",children:s}),code:({children:s,className:a})=>(a==null?void 0:a.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:s})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:s}),pre:({children:s})=>n(ue,{children:s}),strong:({children:s})=>n("strong",{className:"font-semibold text-gray-900",children:s}),blockquote:({children:s})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:s}),table:({children:s})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:s})}),thead:({children:s})=>n("thead",{className:"bg-gray-50",children:s}),th:({children:s})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:s}),td:({children:s})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:s}),a:({children:s,href:a})=>n("a",{href:a,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:s})},children:r})}function _l(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const s=r.filePath.split("/");s.pop();let a=t,o="";for(const i of s)o=o?`${o}/${i}`:i,a.children.has(i)||a.children.set(i,{name:i,path:o,memories:[],children:new Map}),a=a.children.get(i);s.length===0?t.memories.push(r):a.memories.push(r)}return t}function Ml(e){let t=e.memories.length;for(const r of e.children.values())t+=Ml(r);return t}function Zr(e,t){var s;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((s=t.split("/").pop())==null?void 0:s.replace(".md",""))||t}function $n(e){return Math.round(e/3.5)}function dn(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const d=r.getTime()-t.getTime(),h=Math.floor(d/(1e3*60)),u=Math.floor(d/(1e3*60*60));return h<3?"Just now":h<60?`${h}min ago`:u===1?"1h ago":`${u}h ago`}const a=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),c=r.getFullYear();return i===c?`${a} ${o}`:`${a} ${o}, ${i}`}function bb({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:c,changeDate:d,diff:h,isFadingOut:u,showLeftBorder:m}){const[p,f]=_(!1),[y,g]=_(!1),x=re(()=>Zr(e.body,e.filePath),[e.body,e.filePath]),v=$n(e.body.length),b=p?"#3e3e3e":c?"#d97706":"#c7c7c7",N=`rounded-lg border overflow-hidden transition-all ease-in-out ${c?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,w={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return l("div",{className:N,style:w,children:[n("div",{className:`p-4 cursor-pointer ${c?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!p),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:p?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:b})})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:c?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),c&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),l("span",{className:"text-xs text-gray-400",children:["~",v.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&l(ue,{children:[e.frontmatter.paths.slice(0,2).map((E,C)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:E},C)),e.frontmatter.paths.length>2&&l("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),l("div",{className:"flex items-center gap-3 flex-shrink-0",children:[d&&n("span",{className:"text-xs text-gray-400",children:dn(d)}),o&&n("button",{onClick:E=>{E.stopPropagation(),o(e.filePath,e.lastModified,a??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${a?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:a?"Mark as unreviewed":"Mark as reviewed",children:a&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),p&&l("div",{className:`border-t ${c?"border-amber-200":"border-gray-100"}`,children:[l("div",{className:`px-4 py-3 flex items-center justify-between ${c?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&h&&l("button",{onClick:E=>{E.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?c?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(pr,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&l("div",{className:"flex items-center gap-2",children:[l("button",{onClick:E=>{E.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(vc,{className:"w-3 h-3"}),"Edit"]}),l("button",{onClick:E=>{E.stopPropagation(),r(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[n(wc,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&h&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.split(`
340
+ `).map((E,C)=>{let S="";return E.startsWith("+")&&!E.startsWith("+++")?S="text-green-400":E.startsWith("-")&&!E.startsWith("---")?S="text-red-400":E.startsWith("@@")&&(S="text-cyan-400"),n("div",{className:S,children:E},C)})}),l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),l("div",{className:"flex items-center gap-2",children:[l("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(vn,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((E,C)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:E},C))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(Pl,{content:e.body})})]})]})}function vb(){return new Date().toISOString().split(".")[0]+"",`---
341
+ paths:
342
+ - '**/*.ts'
343
+ ---
344
+
345
+ ## Title
346
+
347
+ Description here.
348
+ `}function wb({rule:e,onSave:t,onCancel:r}){const[s,a]=_(e?`.claude/rules/${e.filePath}`:""),[o,i]=_((e==null?void 0:e.content)||vb()),[c,d]=_(!!e),[h,u]=_(!1),m=!e;return l("div",{className:"p-6",children:[l("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Fn,{className:"w-5 h-5"})})]}),m&&l("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:l("div",{className:"flex items-start gap-3",children:[n(pr,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),l("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),l("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),u(!0),setTimeout(()=>u(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:h?n(pt,{className:"w-4 h-4 text-green-500"}):n(wt,{className:"w-4 h-4"})})]})]})]})}),l("button",{onClick:()=>d(!c),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:c?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(c||!m)&&l("div",{className:"space-y-4",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),l("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:p=>a(p.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(s)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n(wt,{className:"w-4 h-4"})})]})]}),e&&l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),l("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${s}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${s}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n(wt,{className:"w-4 h-4"})})]})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:p=>i(p.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),o),disabled:!s.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function Nb({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=re(()=>_l(e),[e]),i=(h,u,m)=>{if(h.target.closest(".chevron-toggle")){m&&a(u||"root");return}const f=u||null;r(t===f?null:f),m&&!s.has(u||"root")&&a(u||"root")},c=h=>{r(t===h?null:h)},d=(h,u=0)=>{const m=s.has(h.path||"root"),p=Ml(h),f=h.children.size>0,y=h.name==="root"?"(root)":h.name,g=h.memories.length>0||f,x=h.path||"",v=t===x||t===null&&x==="";return l("div",{children:[l("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${v?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,h.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),a(h.path||"root")},children:n(Ot,{className:`w-3 h-3 text-gray-500 transition-transform ${m?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(Go,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${v?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),l("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[p," rules"]})]}),m&&l("div",{className:"relative",children:[(h.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),h.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:h.memories.map(b=>{var w;const N=t===b.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${N?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>c(b.filePath),children:n("span",{className:"text-xs",children:(w=b.filePath.split("/").pop())==null?void 0:w.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(h.children.values()).sort((b,N)=>b.name.localeCompare(N.name)).map(b=>d(b,u+1))})]})]},h.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function Cb({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:c,onViewRule:d}){const[h,u]=_({});ee(()=>{u({})},[o]);const m=re(()=>({...o,...h}),[o,h]),p=re(()=>_l(e),[e]),f=(g,x,v)=>{u(b=>({...b,[g]:!v})),v?c(g):i(g,x)},y=(g,x=0)=>{const v=s.has(g.path||"root"),b=g.children.size>0,N=g.name==="root"?"root":g.name,w=g.memories.length>0||b;return l("div",{children:[l("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>w&&a(g.path||"root"),children:[w&&n(Ot,{className:`w-4 h-4 text-gray-500 transition-transform ${v?"rotate-90":""}`}),!w&&n("div",{className:"w-4"}),n(Go,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:N})]}),v&&l("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||b)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),g.memories.length>0&&n("div",{className:"space-y-2",children:g.memories.map(E=>n(bb,{rule:E,onEdit:t,onDelete:r,onView:d,isReviewed:m[E.filePath]??!1,onToggleReviewed:f},E.filePath))}),b&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((E,C)=>E.name.localeCompare(C.name)).map(E=>y(E,x+1))})]})]},g.path||"root")};return n("div",{children:y(p)})}function Sb({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=_("unreviewed"),[i,c]=_("by-date"),[d,h]=_(null),[u,m]=_(!0),[p,f]=_(new Map),y=ve(t),g=ve([]);ee(()=>()=>{g.current.forEach(clearTimeout)},[]),ee(()=>{(async()=>{m(!0);try{const C=await(await fetch("/api/memory?action=rule-coverage")).json();h(C.coverage??null)}catch{h(null)}finally{m(!1)}})()},[s]),ee(()=>{const w=y.current,E=[];for(const[C,S]of Object.entries(t))S&&!w[C]&&E.push(C);y.current=t,E.length!==0&&(f(C=>{const S=new Map(C);return E.forEach(k=>S.set(k,"approved")),S}),g.current.push(setTimeout(()=>{f(C=>{const S=new Map(C);return E.forEach(k=>S.set(k,"fading")),S})},1500)),g.current.push(setTimeout(()=>{f(C=>{const S=new Map(C);return E.forEach(k=>S.delete(k)),S})},2500)))},[t]);const x=re(()=>{const w=[...e];return i==="by-impact"&&d!==null?w.sort((E,C)=>{const S=d[E.filePath]??0,k=d[C.filePath]??0;return k!==S?k-S:new Date(C.lastModified).getTime()-new Date(E.lastModified).getTime()}):w.sort((E,C)=>new Date(C.lastModified).getTime()-new Date(E.lastModified).getTime()),w},[e,i,d]),v=re(()=>x.filter(w=>!t[w.filePath]).length,[x,t]),b=re(()=>a==="unreviewed"?x.filter(w=>!t[w.filePath]||p.has(w.filePath)):x,[x,a,t,p]),N=!u&&d!==null;return l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",v,")"]})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),l("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),l("button",{onClick:()=>N&&c("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${N?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(ot,{className:"w-3 h-3"})]}),l("button",{onClick:()=>c("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(ot,{className:"w-3 h-3"})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",l("span",{className:"relative group",children:[n(Ms,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto max-h-[400px]",children:b.map(w=>{const E=t[w.filePath]??!1,C=p.get(w.filePath),S=Zr(w.body,w.filePath),k=(d==null?void 0:d[w.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${C==="fading"?"duration-1000":"duration-300"}`,style:{opacity:C==="fading"?0:1},children:l("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${C==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(w),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:S})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):d!==null?n("span",{className:k>0?"text-gray-700 font-medium":"text-gray-300",children:k}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:dn(w.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${E?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:E&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},w.filePath)})}),b.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function kb(e,t){const r=t.map(s=>`- \`${s}\``).join(`
349
+ `);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
350
+
351
+ ${r}
352
+
353
+ Please review these rules in conjunction with one another as they all apply to this file.
354
+
355
+ Review each rule with the other rules in mind:
356
+ - Necessary: Is this rule really necessary to avoid confusion in future work sessions?
357
+ - Efficiency: Are the rules concise and well-structured?
358
+ - Effectiveness: Does the rules provide clear, actionable guidance?
359
+ - Context window impact: Can the rules be shortened without losing important information?
360
+ - Overlap: Is there any redundant information across the rules that can be consolidated?
361
+ - Duplication: Are there any rules that are nearly identical that can be merged or removed?
362
+
363
+ Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
364
+
365
+ Note: Each rule may apply to multiple files, not just the file listed above. Consider this when suggesting changes — modifications should not negatively impact the rule's usefulness for other files it covers.`}function Eb({filePath:e,rulePaths:t,onClose:r}){const[s,a]=_(!1),o=kb(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:c=>c.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Fn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:o,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(o),a(!0),setTimeout(()=>a(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:s?l(ue,{children:[n(pt,{className:"w-4 h-4"}),"Copied!"]}):l(ue,{children:[n(wt,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function Ab({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=_("unreviewed"),[i,c]=_(null),[d,h]=_(""),[u,m]=_(0),[p,f]=_(!1),[y,g]=_(null),[x,v]=_(null),b=ve(null),N=ve(null),[w,E]=_({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[C,S]=_(!0);ee(()=>{(async()=>{S(!0);try{const q=await(await fetch("/api/memory?action=audit")).json();E({topPaths:q.topPaths||[],totalFilesWithCoverage:q.totalFilesWithCoverage||0,allSourceFiles:q.allSourceFiles||[]})}catch(J){console.error("Failed to load audit data:",J)}finally{S(!1)}})()},[e]);const k=re(()=>a==="all"?w.topPaths:w.topPaths.filter($=>$.matchingRules.some(J=>!t[J.filePath])),[w.topPaths,a,t]);re(()=>w.topPaths.filter($=>$.matchingRules.some(J=>!t[J.filePath])).length,[w.topPaths,t]);const P=$=>$.split("/").pop()||$,I=re(()=>{const $=new Map;for(const J of w.topPaths)$.set(J.filePath,J);return $},[w.topPaths]),j=re(()=>{if(!d.trim())return[];const $=d.toLowerCase(),J=[],q=[];for(const Y of w.allSourceFiles){const U=Y.toLowerCase();if(!U.includes($))continue;const H=I.get(Y)||{filePath:Y,matchingRules:[],totalTextLength:0};U.startsWith($)?J.push(H):q.push(H)}return J.sort((Y,U)=>Y.filePath.localeCompare(U.filePath)),q.sort((Y,U)=>Y.filePath.localeCompare(U.filePath)),[...J,...q].slice(0,8)},[d,w.allSourceFiles,I]),A=ie($=>{var J;g($),c($.filePath),h($.filePath),f(!1),(J=b.current)==null||J.blur()},[]),T=ie(()=>{var $;h(""),g(null),c(null),($=b.current)==null||$.focus()},[]),R=ie($=>{var J;!p||j.length===0||($.key==="ArrowDown"?($.preventDefault(),m(q=>Math.min(q+1,j.length-1))):$.key==="ArrowUp"?($.preventDefault(),m(q=>Math.max(q-1,0))):$.key==="Enter"?($.preventDefault(),A(j[u])):$.key==="Escape"&&(f(!1),(J=b.current)==null||J.blur()))},[p,j,u,A]);return ee(()=>{m(0)},[j]),l("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),l("div",{className:"relative flex-1 max-w-[300px]",children:[n(On,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:b,type:"text",value:d,onChange:$=>{h($.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:R,placeholder:"Search files...",className:`w-full pl-8 ${d?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:$=>{$.preventDefault(),T()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),p&&j.length>0&&n("div",{ref:N,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:j.map(($,J)=>l("div",{onMouseDown:q=>{q.preventDefault(),A($)},onMouseEnter:()=>m(J),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${J===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(fr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:$.filePath,children:(()=>{const q=$.filePath.toLowerCase().indexOf(d.toLowerCase());if(q===-1)return $.filePath;const Y=$.filePath.slice(0,q),U=$.filePath.slice(q,q+d.length),H=$.filePath.slice(q+d.length);return l(ue,{children:[Y,n("span",{className:"font-semibold text-[#005C75]",children:U}),H]})})()}),l("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[$.matchingRules.length," rule",$.matchingRules.length!==1?"s":""]})]},$.filePath))})]}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:"All"})]})]}),l("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",l("span",{className:"relative group",children:[n(Ms,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",l("span",{className:"relative group",children:[n(Ms,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Estimated tokens from unreviewed rules / Total number of tokens from all rules that apply to this file"})]})]})]}),C&&n("div",{className:"px-5 py-6",children:l("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!C&&(k.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...k.filter(J=>J.filePath!==y.filePath)].slice(0,8):k.slice(0,8)).map(($,J)=>{const q=$.matchingRules.length,Y=$.matchingRules.filter(W=>!t[W.filePath]),U=Y.length,H=Y.reduce((W,F)=>W+F.bodyLength,0),D=U>0,M=i===$.filePath,Q=(y==null?void 0:y.filePath)===$.filePath;return l("div",{children:[l("div",{onClick:()=>c(M?null:$.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${Q?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[l("div",{className:"flex items-center gap-2 min-w-0",children:[M?n(ot,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(Ot,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(fr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:$.filePath,children:Q?$.filePath:P($.filePath)})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:D?"font-semibold text-[#1A5276]":"text-gray-400",children:U}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:q})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:D?"font-semibold text-[#1A5276]":"text-gray-400",children:$n(H).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:$n($.totalTextLength).toLocaleString()})]})]}),M&&l("div",{className:"bg-gray-50 border-b border-gray-100",children:[$.matchingRules.map(W=>{const F=r.find(z=>z.filePath===W.filePath),te=t[W.filePath]??!1;return l("div",{onClick:z=>{z.stopPropagation(),F&&s(F)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(mr,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:F?Zr(F.body,F.filePath):W.filePath}),l("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[$n(W.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${te?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:te&&n("svg",{width:"8",height:"6",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]},W.filePath)}),l("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:W=>{W.stopPropagation(),v({filePath:$.filePath,rulePaths:$.matchingRules.map(F=>F.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},$.filePath)})}),!C&&k.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:a==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(Eb,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>v(null)})]})}function Pb({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const c=Zr(e.body,e.filePath),d=$n(e.body.length),h=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[m,p]=_(null),f=(t==null?void 0:t.changeType)==="added"||m!=null&&m.commitCount!=null&&m.commitCount<=1&&!(m.commitCount===1&&m.isUncommitted);return ee(()=>{p(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&p(y.diff)}).catch(()=>{})},[e.filePath]),ee(()=>{const y=g=>{g.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:l("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:y=>y.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"min-w-0 flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:c}),t&&l(ue,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:dn(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),h&&l("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:h})]}),l("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(vn,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),l("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",d.toLocaleString()]})]}),l("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[l("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(pt,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:a,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(Fn,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((y,g)=>{const x=y.split("/"),v=x.pop()||y,b=x.length>0?x.join("/")+"/":"";return l("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(fr,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),l("span",{children:[b&&n("span",{className:"text-gray-500",children:b}),n("span",{className:"font-bold text-gray-900",children:v})]})]},g)})})]}),f?n("div",{className:"px-6 pb-4",children:l("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?dn(t.date):m!=null&&m.date?dn(m.date):"recently"]})}):m&&n("div",{className:"px-6 pb-4",children:l("details",{children:[l("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",m.commitMessage," —"," ",dn(m.date)]}),n("pre",{className:"mt-2 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:m.diff.split(`
366
+ `).map((y,g)=>{let x="";return y.startsWith("+")&&!y.startsWith("+++")?x="text-green-400":y.startsWith("-")&&!y.startsWith("---")?x="text-red-400":y.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:y},g)})})]})}),l("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(Pl,{content:e.body})})]})]})})}function _b(){return l("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function Mb(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function jb(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[l("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),l("ol",{className:"space-y-5",children:[l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),l("div",{children:[l("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(zo,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),l("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),l("div",{className:"space-y-6",children:[l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[l("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),l("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(zo,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function zo({value:e}){const[t,r]=_(!1);return l("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(pt,{className:"w-3.5 h-3.5 text-green-400"}):l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function ir({label:e,count:t,icon:r,bgColor:s,iconBgColor:a,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:l("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:a},children:r}),l("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function Tb({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:a}){return l("div",{className:"mb-8",children:[l("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[l("div",{children:[l("div",{className:"flex items-center gap-3 mb-2",children:[n(_b,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),l("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative",children:[n(On,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),l("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Gs,{className:"w-4 h-4"}),"New Rule"]})]})]}),l("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(ir,{label:"Total Rules",count:a.total,icon:n(Mb,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(ir,{label:"Unreviewed",count:a.unreviewed,icon:n(Nc,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(ir,{label:"Reviewed",count:a.reviewed,icon:n(pt,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(ir,{label:"Stale",count:a.stale,icon:n(qo,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function $b({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Fn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),l("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[l("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:l("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(Gs,{className:"w-4 h-4"}),"New Rule"]})})]})})}function Rb({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),l("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const Bo="Can you help me perform an interactive rules audit? Please look at all of the rules in `.claude/rules`. Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts `folder1/folder2/file1` and `folder1/folder2/folder3/file2` then the rule should be in `.claude/rules/folder1/folder2`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!",Yo="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Uo({text:e}){const[t,r]=_(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?l(ue,{children:[n(pt,{className:"w-4 h-4"}),"Copied!"]}):l(ue,{children:[n(wt,{className:"w-4 h-4"}),"Copy Prompt"]})})}function Ib({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(Fn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit All Rules"}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can review all rules to look for information that is inconsistent, inappropriate, duplicative, inefficient, etc."}),n("textarea",{readOnly:!0,value:Bo,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Uo,{text:Bo})}),l("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:Yo,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Uo,{text:Yo})})]})]})})}function Db(){const[e,t]=_(!1);return l(ue,{children:[l("div",{className:"border border-gray-200 rounded-lg px-5 py-4 mb-8 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit All Rules"}),n("p",{className:"text-sm text-gray-500",children:"Ask Claude to review, audit, and improve all rules."}),n("button",{onClick:()=>t(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),e&&n(Ib,{onClose:()=>t(!1)})]})}const Lb=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function Ob({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?G({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?G({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):G({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),G({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const Fb=He(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=qe(),o=Oe(),i=mt(),[c,d]=_(""),[h,u]=_(null),[m,p]=_(new Set(["root"])),[f,y]=_(null),[g,x]=_(!1),[v,b]=_(null),[N,w]=_(0),[E,C]=_(!1),[S,k]=_(null),[P,I]=_(null),[j,A]=_({}),T=z=>{p(L=>{const V=new Set(L);return V.has(z)?V.delete(z):V.add(z),V})};ft({source:"memory-page"});const R=re(()=>({...r,...j}),[r,j]),$=ve(o.state);ee(()=>{const z=$.current==="loading"||$.current==="submitting",L=o.state==="idle";z&&L&&o.data&&(i.revalidate(),y(null),x(!1),w(V=>V+1)),$.current=o.state},[o.state,o.data,i]),ee(()=>{A(z=>{const L={};for(const[V,B]of Object.entries(z))r[V]!==B&&(L[V]=B);return Object.keys(L).length===Object.keys(z).length?z:L})},[r]);const J=(z,L)=>{A(V=>({...V,[z]:!0})),o.submit({action:"mark-reviewed",filePath:z,lastModified:L},{method:"POST",action:"/api/memory",encType:"application/json"})},q=z=>{A(L=>({...L,[z]:!1})),o.submit({action:"mark-unreviewed",filePath:z},{method:"POST",action:"/api/memory",encType:"application/json"})},Y=(z,L)=>{k(z),I(L??null)},U=re(()=>{let z=t;if(c.trim()){const L=c.toLowerCase();z=z.filter(V=>{var X;return(((X=V.filePath.split("/").pop())==null?void 0:X.replace(".md",""))||"").toLowerCase().includes(L)||V.body.toLowerCase().includes(L)})}return z},[t,c]),H=re(()=>h?U.some(L=>L.filePath===h)?U.filter(L=>L.filePath===h):U.filter(L=>L.filePath.startsWith(h+"/")||L.filePath===h):U,[U,h]),D=(z,L)=>{const V=f?"update":"create";o.submit({action:V,filePath:z,content:L},{method:"POST",action:"/api/memory",encType:"application/json"})},M=z=>{o.submit({action:"delete",filePath:z.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},Q=re(()=>{const z=t.filter(L=>R[L.filePath]).length;return{total:t.length,reviewed:z,unreviewed:t.length-z,stale:0}},[t,R]),W=re(()=>{const z=new Set(["root"]);for(const L of U){const V=L.filePath.split("/");V.pop();let B="";for(const X of V)B=B?`${B}/${X}`:X,z.add(B)}return z},[U]),F=W.size===m.size&&[...W].every(z=>m.has(z)),te=()=>{p(F?new Set(["root"]):new Set(W))};return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:a})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(Tb,{searchFilter:c,onSearchChange:d,onCreateNew:()=>x(!0),onLearnMore:()=>C(!0),reviewCounts:Q}),(g||f)&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>{x(!1),y(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:z=>z.stopPropagation(),children:n(wb,{rule:f,onSave:D,onCancel:()=>{x(!1),y(null)}})})}),l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(Sb,{memories:U,reviewedStatus:R,onViewRule:Y,refreshKey:N}),n(Ab,{onEditRule:y,onDeleteRule:b,refreshKey:N,reviewedStatus:R,onMarkReviewed:J,onMarkUnreviewed:q,memories:t,onViewRule:Y})]}),n(Db,{}),l("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:W.size>1&&n("button",{onClick:te,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:F?"Collapse All":"Expand All"})})]}),l("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(Nb,{memories:U,selectedPath:h,onSelectPath:u,expandedFolders:m,onToggleFolder:T})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Cc,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),l("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),l("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(Gs,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):l("div",{children:[h&&l("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:h||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(Cb,{memories:H,onEdit:y,onDelete:b,expandedFolders:m,onToggleFolder:T,reviewedStatus:R,onMarkReviewed:J,onMarkUnreviewed:q,onViewRule:Y})]})})]}),n("div",{className:"mt-8 mb-8",children:n(de,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:l("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:l("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),l("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),S&&!f&&(()=>{const z=t.find(L=>L.filePath===S.filePath)??S;return n(Pb,{rule:z,changeInfo:P??void 0,isReviewed:R[z.filePath]??!1,onApprove:()=>{R[z.filePath]??!1?q(z.filePath):J(z.filePath,z.lastModified),k(null)},onEdit:()=>{y(z)},onDelete:()=>{b(z),k(null)},onClose:()=>k(null)})})(),E&&n($b,{onClose:()=>C(!1),onCreateNew:()=>{C(!1),x(!0)}}),v&&n(Rb,{rule:v,onConfirm:M,onCancel:()=>b(null)})]})}):n(jb,{})}),zb=Object.freeze(Object.defineProperty({__proto__:null,default:Fb,loader:Ob,meta:Lb},Symbol.toStringTag,{value:"Module"}));function _s(e){return`${e.filePath||""}::${e.name}`}function jl(e,t){const r=Oe(),{showToast:s}=ra(),[a,o]=_(new Map);ee(()=>{if(r.state==="idle"&&r.data){const p=r.data;p!=null&&p.error&&s(`Error: ${p.error}`,"error",6e3)}},[r.state,r.data,s]),ee(()=>{var f;if(a.size===0)return;const p=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{a.forEach((v,b)=>{v===x&&p.add(b)})})}),e==null||e.forEach(y=>{a.forEach((g,x)=>{g===y&&p.add(x)})}),p.size>0&&o(y=>{const g=new Map(y);return p.forEach(x=>g.delete(x)),g})},[t,e,a]);const i=ie(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=_s(p);o(g=>new Map(g).set(f,p.sha));const y=new FormData;y.append("entitySha",p.sha),y.append("filePath",p.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),c=ie(p=>{const f=p.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const v=new Map(x);return f.forEach(b=>v.set(_s(b),b.sha)),v});const y=f.map(x=>x.sha).join(","),g=new FormData;g.append("entityShas",y),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),d=ie(p=>(e==null?void 0:e.includes(p))??!1,[e]),h=ie(p=>{const f=_s(p);return a.has(f)},[a]),u=ie(p=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(p)}))??!1},[t]),m=re(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:c,isEntityBeingAnalyzed:d,isEntityPending:h,isEntityInQueue:u,pendingEntityKeys:m}}function Sa({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:a=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:l("div",{className:"flex justify-between items-center px-3 py-2",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),l("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),l("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:s&&n("button",{onClick:s,disabled:a,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:a?o:"Analyze all entities",children:o})})]})]})]})})}function Bb({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},s={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=s[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const a=r[e]||{label:"?",bgColor:"bg-gray-500"};return l("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${a.bgColor}`,title:e,children:a.label}),a.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function ka({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:c,actionButton:d,uncommittedCount:h,children:u,isNotAnalyzable:m=!1,isUncommitted:p=!1}){return l("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[l("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${m?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(ri,{filePath:e}),s&&n(Bb,{status:typeof s=="string"?s:s.status,variant:"full"}),p&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(p||i==="out-of-date")&&l("div",{className:"flex gap-1.5 items-center",children:[p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:a}),l("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:l("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:yl(c)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Ea({entities:e,maxPreviews:t=3}){var s,a,o,i,c;const r=[];for(const d of e){if(r.length>=t)break;const h=((a=(s=d.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(d.entityType==="library"){const u=h.find(m=>{var p,f;return((p=m.metadata)==null?void 0:p.executionResult)||((f=m.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=h.find(m=>{var p,f;return(f=(p=m.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const m=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],p=!!((c=u.metadata)!=null&&c.error);m&&r.push({type:"screenshot",screenshot:m,hasError:p,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ue,{children:r.map((d,h)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return l(de,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:m=>m.stopPropagation(),children:[n(Ge,{screenshotPath:d.screenshot,alt:`Preview ${h+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(hr,{size:12,color:"white"})})]},`screenshot-${h}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(fl,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${h}`):null})})}function Aa({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,m;const a=t||r?[{entityShas:[e.sha]}]:[],o=st(e,a,t),i=e.entityType==="visual"||e.entityType==="library",c=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,h=(((m=(u=e.analyses)==null?void 0:u[0])==null?void 0:m.scenarios)||[]).filter(p=>{var f,y;return(y=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return l("div",{className:"bg-white rounded-lg",children:[l(de,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(et,{type:"type"})})}):n(et,{type:e.entityType||"other"}),n("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),n(ga,{type:e.entityType||"other"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),l("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):c&&n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),h.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:h.map((p,f)=>{var g,x;const y=(x=(g=p.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(de,{to:`/entity/${e.sha}?scenario=${p.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:v=>v.stopPropagation(),children:n(Ge,{screenshotPath:y,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function Yb({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:c,pendingEntityKeys:d,onGenerateSimulation:h,onGenerateAllSimulations:u,totalFilesCount:m,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,v]=fn(),[b,N]=_(new Set),[w,E]=_(""),[C,S]=_(!1),[k,P]=_("all"),[I,j]=_("desc"),A=o||"all",T=re(()=>{let M=e;return A!=="all"&&(M=M.filter(Q=>Q.entityType===A)),a==="analyzed"&&(M=M.filter(Q=>Q.analyses&&Q.analyses.length>0)),M},[e,A,a]),R=re(()=>{const M=new Map,Q=new Map,W=new Map;T.forEach(L=>{var X,ce;const V=`${L.filePath}::${L.name}`,B=Q.get(V);if(!B)Q.set(V,L),W.set(V,[]);else{const we=((X=B.metadata)==null?void 0:X.editedAt)||B.createdAt||"",ae=((ce=L.metadata)==null?void 0:ce.editedAt)||L.createdAt||"";let he=!1;if(ae>we)he=!0;else if(ae===we){const ye=B.createdAt||"";he=(L.createdAt||"")>ye}he?(W.get(V).push(B),Q.set(V,L)):W.get(V).push(L)}}),Q.forEach((L,V)=>{var X;if(!(L.analyses&&L.analyses.length>0)&&((X=L.metadata)!=null&&X.previousVersionWithAnalyses)){const we=(W.get(V)||[]).find(ae=>{var he;return ae.sha===((he=L.metadata)==null?void 0:he.previousVersionWithAnalyses)});we&&we.analyses&&we.analyses.length>0&&(L.analyses=we.analyses)}}),Array.from(Q.values()).sort((L,V)=>{var ce,we,ae,he;const B=!((ce=L.metadata)!=null&&ce.notExported)&&!((we=L.metadata)!=null&&we.namedExport),X=!((ae=V.metadata)!=null&&ae.notExported)&&!((he=V.metadata)!=null&&he.namedExport);return B&&!X?-1:!B&&X?1:0}).forEach(L=>{var we,ae,he,ye,Me;const V=L.filePath??"No File Path";M.has(V)||M.set(V,{filePath:V,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const B=M.get(V);B.entities.push(L),B.totalCount++,(we=L.metadata)!=null&&we.isUncommitted&&B.uncommittedCount++;const X=((ye=(he=(ae=L.analyses)==null?void 0:ae[0])==null?void 0:he.scenarios)==null?void 0:ye.length)||0;B.simulationCount+=X;const ce=((Me=L.metadata)==null?void 0:Me.editedAt)||L.updatedAt;ce&&(!B.lastUpdated||new Date(ce)>new Date(B.lastUpdated))&&(B.lastUpdated=ce)});const F=(i==null?void 0:i.jobs)||[],te=L=>{const V=`${L.filePath||""}::${L.name}`;return(d==null?void 0:d.includes(V))||!1};M.forEach(L=>{const V=L.entities.map(B=>te(B)?"queued":st(B,F));V.includes("analyzing")||V.includes("queued")?L.state="analyzing":V.includes("incomplete")?L.state="incomplete":V.includes("out-of-date")?L.state="out-of-date":V.includes("not-analyzed")?L.state="not-analyzed":L.state="up-to-date"}),M.forEach(L=>{var V,B,X,ce,we;for(const ae of L.entities){if(L.previewScreenshots.length+L.previewLibraryScenarios.length>=3)break;const ye=((B=(V=ae.analyses)==null?void 0:V[0])==null?void 0:B.scenarios)||[];if(ae.entityType==="library"){const Me=ye.find(je=>{var De,Le;return((De=je.metadata)==null?void 0:De.executionResult)||((Le=je.metadata)==null?void 0:Le.error)});Me&&L.previewLibraryScenarios.push({scenario:Me,entitySha:ae.sha})}else{const Me=ye.find(je=>{var De,Le;return(Le=(De=je.metadata)==null?void 0:De.screenshotPaths)==null?void 0:Le[0]});if(Me){const je=(ce=(X=Me.metadata)==null?void 0:X.screenshotPaths)==null?void 0:ce[0],De=!!((we=Me.metadata)!=null&&we.error);je&&!L.previewScreenshots.includes(je)&&(L.previewScreenshots.push(je),L.previewScreenshotErrors.push(De))}}}});const z=Array.from(M.values());return z.sort((L,V)=>{if(a==="analyzed"){const ce=Math.max(...L.entities.filter(ae=>{var he,ye;return(ye=(he=ae.analyses)==null?void 0:he[0])==null?void 0:ye.createdAt}).map(ae=>new Date(ae.analyses[0].createdAt).getTime()),0),we=Math.max(...V.entities.filter(ae=>{var he,ye;return(ye=(he=ae.analyses)==null?void 0:he[0])==null?void 0:ye.createdAt}).map(ae=>new Date(ae.analyses[0].createdAt).getTime()),0);return I==="desc"?we-ce:ce-we}if(L.uncommittedCount>0&&V.uncommittedCount===0)return-1;if(L.uncommittedCount===0&&V.uncommittedCount>0)return 1;const B=L.lastUpdated?new Date(L.lastUpdated).getTime():0,X=V.lastUpdated?new Date(V.lastUpdated).getTime():0;return I==="desc"?X-B:B-X}),z},[T,a,I,i,d]),$=re(()=>{let M=R;if(k!=="all"&&(M=M.filter(Q=>Q.state===k)),w.trim()){const Q=w.toLowerCase();M=M.filter(W=>W.filePath.toLowerCase().includes(Q))}return M},[R,w,k]),J=(t-1)*r,q=J+r,Y=$.slice(J,q),U=Math.ceil($.length/r),H=M=>{N(Q=>{const W=new Set(Q);return W.has(M)?W.delete(M):W.add(M),W})},D=()=>{j(M=>M==="desc"?"asc":"desc")};return l("div",{children:[l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative w-[130px]",children:[l("select",{value:A,onChange:M=>{const Q=M.target.value,W=new URLSearchParams(x);Q==="all"?W.delete("entityType"):W.set("entityType",Q),W.set("page","1"),v(W)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(ot,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"relative w-[130px]",children:[l("select",{value:k,onChange:M=>P(M.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(ot,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[n(On,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:w,onChange:M=>E(M.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),m!==void 0&&p!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:$.length})," ",$.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:$.reduce((M,Q)=>M+Q.totalCount,0)})," ",$.reduce((M,Q)=>M+Q.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?l("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[$.filter(M=>M.uncommittedCount>0).length," ","uncommitted"," ",$.filter(M=>M.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):l("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),Y.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:()=>{N(new Set(Y.map(M=>M.filePath))),S(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Ko,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:()=>{N(new Set),S(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Qo,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(Sa,{showActions:!0,sortOrder:I,onSortChange:D}),n("div",{className:"flex flex-col gap-[3px]",children:Y.map(M=>{const Q=b.has(M.filePath),F=M.entities.filter(V=>(V.entityType==="visual"||V.entityType==="library")&&(st(V,(i==null?void 0:i.jobs)||[])==="not-analyzed"||st(V,(i==null?void 0:i.jobs)||[])==="out-of-date"||st(V,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,te=V=>{var B;return((B=s==null?void 0:s.currentEntityShas)==null?void 0:B.includes(V))||!1},z=V=>{var B;return c!=null&&c(V)?!0:((B=i==null?void 0:i.jobs)==null?void 0:B.some(X=>{var ce;return(ce=X.entityShas)==null?void 0:ce.includes(V.sha)}))||!1},L=V=>{h==null||h(V)};return n(ka,{filePath:M.filePath,isExpanded:Q,onToggle:()=>H(M.filePath),simulationPreviews:n(Ea,{entities:M.entities,maxPreviews:1}),entityCount:M.totalCount,state:M.state,lastModified:M.lastUpdated,uncommittedCount:M.uncommittedCount,isUncommitted:M.uncommittedCount>0,actionButton:F?n("button",{onClick:V=>{V.stopPropagation();const B=M.entities.filter(X=>(X.entityType==="visual"||X.entityType==="library")&&(st(X,(i==null?void 0:i.jobs)||[])==="not-analyzed"||st(X,(i==null?void 0:i.jobs)||[])==="out-of-date"||st(X,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(B)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:M.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:M.entities.sort((V,B)=>{var he,ye,Me,je;const X=!((he=V.metadata)!=null&&he.notExported)&&!((ye=V.metadata)!=null&&ye.namedExport),ce=!((Me=B.metadata)!=null&&Me.notExported)&&!((je=B.metadata)!=null&&je.namedExport);if(X&&!ce)return-1;if(!X&&ce)return 1;const we=V.entityType==="visual"||V.entityType==="library",ae=B.entityType==="visual"||B.entityType==="library";return we&&!ae?-1:!we&&ae?1:V.name.localeCompare(B.name)}).map(V=>n(Aa,{entity:V,isActivelyAnalyzing:te(V.sha),isQueued:z(V),onGenerateSimulation:L},V.sha))},M.filePath)})}),U>1&&l("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),l("span",{children:["Page ",t," of ",U]}),t<U&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Ub=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function Wb({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),a=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,c=i?i.getState():{paused:!1,jobs:[]},[d,h]=await Promise.all([rn(),yn()]);return G({entities:d,currentCommit:h,page:s,filter:a,entityType:o,queueState:c})}catch(r){return console.error("Failed to load entities:",r),G({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Hb=He(function(){var w,E,C;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:c}=qe();mt();const[d,h]=fn(),[u,m]=_(!1);ft({source:"files-page"});const{handleGenerateSimulation:p,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=jl((E=(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun)==null?void 0:E.currentEntityShas,i),x=t||[],v=re(()=>{const S=new Set([]);for(const k of x)S.add(k.filePath??"No File Path");return Array.from(S)},[x]),b=re(()=>{let S=x;return u&&(S=S.filter(k=>{var P;return(P=k.metadata)==null?void 0:P.isUncommitted})),S.sort((k,P)=>{var I,j,A,T,R,$;return(I=k.metadata)!=null&&I.isUncommitted&&!((j=P.metadata)!=null&&j.isUncommitted)?-1:!((A=k.metadata)!=null&&A.isUncommitted)&&((T=P.metadata)!=null&&T.isUncommitted)?1:new Date(((R=P.metadata)==null?void 0:R.editedAt)||0).getTime()-new Date((($=k.metadata)==null?void 0:$.editedAt)||0).getTime()})},[x,u]),N=re(()=>{var k;const S=new Set([]);for(const P of x)(k=P.metadata)!=null&&k.isUncommitted&&S.add(P.filePath??"No File Path");return Array.from(S)},[x]);return c?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:c})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:l("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),l("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(Yb,{entities:b,page:s,itemsPerPage:50,currentRun:(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:p,onGenerateAllSimulations:f,totalFilesCount:v.length,totalEntitiesCount:x.length,uncommittedFilesCount:N.length,showOnlyUncommitted:u,onToggleUncommitted:()=>m(!u)})]})})}),Jb=Object.freeze(Object.defineProperty({__proto__:null,default:Hb,loader:Wb,meta:Ub},Symbol.toStringTag,{value:"Module"})),Vb=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function qb({request:e}){var t;try{const r=await $e();if(!r)return G({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await Ie(r),a=ge()||process.cwd(),o=dl(a)||"";let i="";try{const d=await Or();if(d!=null&&d.webapps&&Array.isArray(d.webapps)){const h=d.webapps.map(u=>u.framework).filter(Boolean);h.length>0&&(i=h.join(", "))}}catch{}const c=pl(r);return G({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:c,error:null})}catch(r){return console.error("Failed to load labs config:",r),G({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function Gb({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return G({success:!1,error:"Missing feature name"},{status:400});const a=await $e();return a?(r==="clearAccess"?await mn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await mn({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),G({success:!0,error:null})):G({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),G({success:!1,error:"Failed to save labs configuration"},{status:500})}}const Kb=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible.",defaultEnabled:!0},{id:"enhancedClaudeTesting",name:"Enhanced Claude Testing",description:"Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!0},{id:"gitIntegration",name:"Git Integration Showing Impacted Files",description:"Lorem Ipsum Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!1}],Wo="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",Qb=[{title:"CodeYam Simulations",status:"apply for early access",desc:"CodeYam Simulations are the core of the CodeYam development experience. They leverage static code analysis and AI to generate robust data scenarios that are used to hydrate code. This creates a whole new dimension to the software development experience"},{title:"The Full CodeYam Experience",status:"more to come",desc:"CodeYam is completely rethinking the software development experience in the AI era. Focused on navigating the challenges of iteration speed, complexity, and communication, CodeYam will provide a powerful software development experience."}];function Zb({onClose:e}){const t=ve(null),r=ve(0);return ee(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let c=null,d=!1;const h=()=>{r.current=Date.now(),!c&&!d&&(c=setInterval(()=>{const u=Date.now()-r.current,m=s.scrollTop>a,p=u>o;m&&p&&(s.scrollTo({top:0,behavior:"smooth"}),d=!0,c&&(clearInterval(c),c=null))},i))};return s.addEventListener("scroll",h,{passive:!0}),()=>{s.removeEventListener("scroll",h),c&&clearInterval(c)}},[]),l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),l("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[l("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${Wo}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:l("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),l("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:Wo,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function Xb({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,c;const a=(i=s.data)==null?void 0:i.error,o=(c=s.data)==null?void 0:c.success;return l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:d=>{d.target===d.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),l(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:d=>r(d.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||s.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:s.state==="submitting"?"Validating...":"Unlock"}),a&&n("p",{className:"text-red-600 text-sm mt-2",children:a}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const ev=He(function(){const{labs:t,unlockCode:r,error:s}=qe(),a=Oe(),o=Oe(),i=Oe(),[c,d]=_(""),[h,u]=_(!1),[m,p]=_(!1);ft({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return s?n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:s})})]})}):f?l("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:Kb.map(y=>{var v;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=o.state==="submitting"&&((v=o.formData)==null?void 0:v.get("feature"))===y.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:l("div",{className:"flex items-center justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),l(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:l("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),l("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),l(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):l("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[h&&n(Zb,{onClose:()=>u(!1)}),m&&n(Xb,{onClose:()=>p(!1),unlockCodeInput:c,setUnlockCodeInput:d,unlockFetcher:a}),l("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),l("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),l("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),l("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:Qb.map(y=>l("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[l("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",l("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:l("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),tv=Object.freeze(Object.defineProperty({__proto__:null,action:Gb,default:ev,loader:qb,meta:Vb},Symbol.toStringTag,{value:"Module"}));function nv(e,t,r){const[s,a]=_(()=>new Set),[o,i]=_(()=>new Set),c=ve([]),d=ve([]);return ee(()=>{(t.length!==c.current.length||t.some((g,x)=>g!==c.current[x]))&&(c.current=t,a(g=>{const x=new Set;return t.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[t]),ee(()=>{(r.length!==d.current.length||r.some((g,x)=>g!==d.current[x]))&&(d.current=r,i(g=>{const x=new Set;return r.forEach(v=>{g.has(v)&&x.add(v)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:o,setExpandedUncommitted:a,setExpandedBranch:i,toggleFile:(y,g,x)=>{x(v=>{const b=new Set(v);return b.has(y)?b.delete(y):b.add(y),b})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function rv(e,t,r){const[s,a]=_(null),[o,i]=_(null),c=Oe();ee(()=>{var m,p;((m=c.data)==null?void 0:m.oldContent)!==void 0&&((p=c.data)==null?void 0:p.newContent)!==void 0&&i({oldContent:c.data.oldContent,newContent:c.data.newContent,fileName:c.data.fileName})},[c.data]);const d=m=>{a({type:"file",path:m}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",m),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),c.submit(p,{method:"post"})},h=(m,p)=>{a({type:"entity",path:m,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",m),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),c.submit(f,{method:"post"})},u=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:c.state==="loading"||c.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:h,handleCloseDiff:u}}function sv({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var h;const[o,i]=_(!1),[c,d]=_(!1);return ee(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:l("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[l("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[l("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&l("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((h=s.find(u=>u.sha===e.entitySha))==null?void 0:h.name)||e.entitySha]})]}),l("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:a,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:c&&n(Zc,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:a,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function av({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:c,sortOrder:d,onToggleFile:h,onBranchChange:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([N,{entities:w}])=>{const E=w.filter(C=>i(C.sha)||c(C)).map(C=>C.sha);return E.length>0?[{entityShas:E}]:[]}),v=N=>{const w=N.map(E=>st(E,x));return w.includes("analyzing")||w.includes("queued")?"analyzing":w.includes("out-of-date")?"out-of-date":w.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=re(()=>[...e].sort((N,w)=>{const E=N[1].entities.reduce((P,I)=>{var A;const j=((A=I.metadata)==null?void 0:A.editedAt)||I.updatedAt;return j?P?new Date(j)>new Date(P)?j:P:j:P},null),C=w[1].entities.reduce((P,I)=>{var A;const j=((A=I.metadata)==null?void 0:A.editedAt)||I.updatedAt;return j?P?new Date(j)>new Date(P)?j:P:j:P},null);if(!E&&!C)return 0;if(!E)return 1;if(!C)return-1;const S=new Date(E).getTime(),k=new Date(C).getTime();return d==="desc"?k-S:S-k}),[e,d]);return n("div",{children:e.length>0?l("div",{children:[n(Sa,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([N,{status:w,entities:E,isUncommitted:C}])=>{const S=o.has(N),k=v(E),P=E.reduce((T,R)=>{var J;const $=((J=R.metadata)==null?void 0:J.editedAt)||R.updatedAt;return $?T?new Date($)>new Date(T)?$:T:$:T},null),j=E.filter(T=>T.entityType==="visual"||T.entityType==="library").length===0;let A;return j?A=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):k==="analyzing"?A=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):k==="up-to-date"?A=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):k==="out-of-date"?A=n("button",{onClick:T=>{T.stopPropagation(),E.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!i(R.sha)&&!c(R)).forEach(R=>m(R))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):k==="not-analyzed"&&(A=n("button",{onClick:T=>{T.stopPropagation(),E.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!i(R.sha)&&!c(R)).forEach(R=>m(R))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(ka,{filePath:N,isExpanded:S,onToggle:()=>h(N),fileStatus:w,isUncommitted:C,simulationPreviews:n(Ea,{entities:E,maxPreviews:1}),entityCount:E.length,state:k,lastModified:P,isNotAnalyzable:j,actionButton:A,children:E.sort((T,R)=>{const $=T.entityType==="visual"||T.entityType==="library",J=R.entityType==="visual"||R.entityType==="library";return $&&!J?-1:!$&&J?1:0}).map(T=>n(Aa,{entity:T,isActivelyAnalyzing:i(T.sha),isQueued:c(T),onGenerateSimulation:m},T.sha))},N)})})]}):l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function ov({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:c,sortOrder:d,onToggleFile:h,onShowFileDiff:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=re(()=>{const N=[];return e.forEach(([w,{editedEntities:E}])=>{const C=E.filter(S=>s(S.sha)||a(S)).map(S=>S.sha);C.length>0&&N.push({entityShas:C})}),N},[e,s,a]),v=re(()=>{const N=new Map;return e.forEach(([w,{editedEntities:E}])=>{const C=E.map(I=>st(I,x));let S;C.includes("analyzing")||C.includes("queued")?S="analyzing":C.includes("out-of-date")?S="out-of-date":C.includes("not-analyzed")?S="not-analyzed":S="up-to-date";const k=E.reduce((I,j)=>{var T;const A=((T=j.metadata)==null?void 0:T.editedAt)||j.updatedAt;return A&&(!I||new Date(A)>new Date(I))?A:I},null),P=E.filter(I=>I.entityType==="visual"||I.entityType==="library").length;N.set(w,{state:S,lastModified:k,analyzableCount:P})}),N},[e,x]),b=re(()=>[...e].sort((N,w)=>{const E=v.get(N[0]),C=v.get(w[0]),S=E==null?void 0:E.lastModified,k=C==null?void 0:C.lastModified;if(!S&&!k)return 0;if(!S)return 1;if(!k)return-1;const P=new Date(S).getTime(),I=new Date(k).getTime();return d==="desc"?I-P:P-I}),[e,v,d]);return e.length===0?l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):l("div",{children:[n(Sa,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([N,{status:w,editedEntities:E}])=>{const C=r.has(N),S=v.get(N),{state:k,lastModified:P,analyzableCount:I}=S,j=I===0;let A;return j?A=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):k==="analyzing"?A=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):k==="up-to-date"?A=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):k==="out-of-date"?A=n("button",{onClick:T=>{T.stopPropagation(),E.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!s(R.sha)&&!a(R)).forEach(R=>m(R))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):k==="not-analyzed"&&(A=n("button",{onClick:T=>{T.stopPropagation(),E.filter(R=>(R.entityType==="visual"||R.entityType==="library")&&!s(R.sha)&&!a(R)).forEach(R=>m(R))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(ka,{filePath:N,isExpanded:C,onToggle:()=>h(N),fileStatus:w,simulationPreviews:n(Ea,{entities:E,maxPreviews:1}),entityCount:E.length,state:k,lastModified:P,isNotAnalyzable:j,isUncommitted:!0,actionButton:A,children:E.sort((T,R)=>{const $=T.entityType==="visual"||T.entityType==="library",J=R.entityType==="visual"||R.entityType==="library";return $&&!J?-1:!$&&J?1:0}).map(T=>n(Aa,{entity:T,isActivelyAnalyzing:s(T.sha),isQueued:a(T),onGenerateSimulation:m},T.sha))},N)})})]})}function iv({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:l("nav",{className:"flex gap-8 items-center",children:[l("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Branch Changes",s>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:s})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),l("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const lv=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function cv({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),a=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),c=t.get("entitySha");let d;return a==="branch"?d=lr(s,o,i):d=Rf(s),G({...d,entitySha:c})}return G({error:"Unknown action"},{status:400})}async function dv({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),a=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[c,d,h]=await Promise.all([rn(),yn(),$e()]),u=rl(),m=_f(),p=Mf(),f=jf(),y=a||m,g=s||p;let x=[];return y&&y!==g&&(x=sl(g,y)),G({entities:c||[],gitStatus:u,currentBranch:y,actualCurrentBranch:m,defaultBranch:p,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:d,projectSlug:h,queueState:i})}catch(r){return console.error("Failed to load git data:",r),G({entities:[],gitStatus:[],currentBranch:null,actualCurrentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const uv=He(function(){var Ce,it;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:c,branchDiff:d,currentCommit:h,projectSlug:u,queueState:m}=qe();ft({source:"git-page"});const[p,f]=fn(),[y,g]=_(null),[x,v]=_("desc"),[b,N]=_("branch"),w=p.get("expanded")==="true",E=()=>{v(pe=>pe==="desc"?"asc":"desc")},C=Oe(),S=C.data;ee(()=>{s&&c&&s!==c&&C.state==="idle"&&!S&&C.load(`/api/branch-entity-diff?base=${encodeURIComponent(c)}&compare=${encodeURIComponent(s)}`)},[s,c,C,S]);const k=re(()=>{const pe=kl(r,t);return Array.from(pe.entries()).sort((Ye,Fe)=>Ye[0].localeCompare(Fe[0]))},[r,t]),P=re(()=>{const pe=Hx(d,t,S);return Array.from(pe.entries()).sort((Ye,Fe)=>Ye[0].localeCompare(Fe[0]))},[d,t,S]),I=re(()=>Jx(r,t),[r,t]),j=re(()=>b==="uncommitted"?k:P,[b,k,P]),A=re(()=>j.map(([pe])=>pe),[j]),{expandedUncommitted:T,setExpandedUncommitted:R,toggleFile:$,expandAllUncommitted:J,collapseAllUncommitted:q}=nv(w,A,[]),{diffView:Y,diffContent:U,isLoading:H,handleShowFileDiff:D,handleCloseDiff:M}=rv(c,s),Q=(Ce=h==null?void 0:h.metadata)==null?void 0:Ce.currentRun,W=new Set((Q==null?void 0:Q.currentEntityShas)||[]),F=new Set(m.jobs.flatMap(pe=>pe.entityShas||[])),te=new Set(((it=m.currentlyExecuting)==null?void 0:it.entityShas)||[]),{isAnalyzing:z,handleGenerateSimulation:L,handleGenerateAllSimulations:V,isEntityBeingAnalyzed:B,isEntityPending:X}=jl(Q==null?void 0:Q.currentEntityShas,m),ce=pe=>X(pe)||F.has(pe.sha)||te.has(pe.sha),we=pe=>{pe===(a||s)?p.delete("viewBranch"):p.set("viewBranch",pe),f(p)},ae=pe=>{pe===o?p.delete("compare"):p.set("compare",pe),f(p)},he=()=>{const Ye=j.flatMap(([Fe,gt])=>gt.editedEntities||gt.entities||[]).filter(Fe=>!W.has(Fe.sha)&&!F.has(Fe.sha)&&!te.has(Fe.sha)&&!X(Fe));V(Ye)},ye=k.length,Me=P.length,je=j.flatMap(([pe,Ye])=>Ye.editedEntities||Ye.entities||[]),De=je.filter(pe=>pe.entityType==="visual"||pe.entityType==="library"),Le=De.length>0&&De.every(pe=>W.has(pe.sha)),Ee=De.length>0&&!Le&&De.every(pe=>F.has(pe.sha)||te.has(pe.sha)),ne=z||Le||Ee,xe=Le?"Analyzing...":Ee?"Queued...":z?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),l("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(iv,{activeTab:b,onTabChange:N,uncommittedCount:ye,branchCount:Me})}),s&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===o?l("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):l("div",{className:"flex gap-6 items-center",children:[l("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?l("div",{className:"relative w-50",children:[n("select",{value:s,onChange:pe=>we(pe.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(pe=>n("option",{value:pe,children:pe},pe))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:s})]}),l("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),l("div",{className:"relative w-[200px]",children:[n("select",{value:c,onChange:pe=>ae(pe.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(pe=>pe!==s).map(pe=>n("option",{value:pe,children:pe},pe))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:l("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:j.length})," ","modified ",j.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:je.length})," ",je.length===1?"entity":"entities"]})]}),j.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:J,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Ko,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:q,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Qo,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),l("div",{className:"overflow-hidden",children:[b==="branch"&&s&&n(av,{files:P,currentBranch:s,defaultBranch:o,baseBranch:c,allBranches:i,expandedFiles:T,isEntityBeingAnalyzed:B,isEntityQueued:ce,sortOrder:x,onToggleFile:pe=>$(pe,T,R),onBranchChange:ae,onGenerateSimulation:L,onSortChange:E,onAnalyzeAll:he,analyzeAllDisabled:ne,analyzeAllText:xe}),b==="uncommitted"&&n(ov,{files:k,entityImpactMap:I,expandedFiles:T,isEntityBeingAnalyzed:B,isEntityQueued:ce,projectSlug:u,baseBranch:c,currentBranch:s,sortOrder:x,onToggleFile:pe=>$(pe,T,R),onShowFileDiff:D,onGenerateSimulation:L,onSortChange:E,onAnalyzeAll:he,analyzeAllDisabled:ne,analyzeAllText:xe})]}),Y&&n(sv,{diffView:Y,diffContent:U,isLoading:H,entities:t,onClose:M}),y&&u&&n(It,{projectSlug:u,onClose:()=>g(null)})]})})}),hv=Object.freeze(Object.defineProperty({__proto__:null,action:cv,default:uv,loader:dv,meta:lv},Symbol.toStringTag,{value:"Module"})),lw={entry:{module:"/assets/entry.client-DTvKq3TY.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/index-10oVnAAH.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/root-DUKqhFlb.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/index-10oVnAAH.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/useReportContext-O-jkvSPx.js","/assets/loader-circle-BAXYRVEO.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/book-open-D_nMCFmP.js","/assets/useToast-9FIWuYfK.js","/assets/useLastLogLine-C14nCb1q.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CobE682z.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/chevron-down-BH2h1Ea2.js","/assets/circle-check-DyIKORY6.js","/assets/CopyButton-DmJveP3T.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-C28BiQzt.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-DjACbfdI.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/Spinner-Bb5uFQ5V.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/Terminal-nZNBALox.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/preload-helper-ckwbz45p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-BMvVHNXU.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-register-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-p9hhkjJM.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/Spinner-Bb5uFQ5V.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/agent-transcripts-D9hemwl6.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/terminal-BG4heKCG.js","/assets/search-fKo7v0Zo.js","/assets/chevron-down-BH2h1Ea2.js","/assets/book-open-D_nMCFmP.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-BpKzcsJz.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/LogViewer-ceAyBX-H.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/loader-circle-BAXYRVEO.js","/assets/pause-DTAcYxBt.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha._-CrjR3zZW.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useLastLogLine-C14nCb1q.js","/assets/Spinner-Bb5uFQ5V.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/LoadingDots-BU_OAEMP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-B76aig_2.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-CobE682z.js","/assets/CopyButton-DmJveP3T.js","/assets/LogViewer-ceAyBX-H.js","/assets/useReportContext-O-jkvSPx.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-Bu6c6aDe.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/circle-check-DyIKORY6.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/simulations-B3aOzpCZ.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LoadingDots-BU_OAEMP.js","/assets/EntityTypeIcon-CobE682z.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/loader-circle-BAXYRVEO.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/dev.empty-BiM6z3Do.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/ScenarioViewer-B76aig_2.js","/assets/InteractivePreview-DYFW3lDD.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/LogViewer-ceAyBX-H.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/useLastLogLine-C14nCb1q.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-djPLI-WV.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/circle-check-DyIKORY6.js","/assets/triangle-alert-DtSmdtM4.js","/assets/copy-NDbZjXao.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-Bu6c6aDe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/settings-DfuTtcJP.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/CopyButton-DmJveP3T.js","/assets/copy-NDbZjXao.js","/assets/createLucideIcon-CMT1jU2q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/_index-C96V0n15.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useLastLogLine-C14nCb1q.js","/assets/useToast-9FIWuYfK.js","/assets/useReportContext-O-jkvSPx.js","/assets/LogViewer-ceAyBX-H.js","/assets/EntityTypeIcon-CobE682z.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/circle-check-DyIKORY6.js","/assets/loader-circle-BAXYRVEO.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/editor-B2KwhQph.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useCustomSizes-ByhSyh0W.js","/assets/Terminal-nZNBALox.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/Spinner-Bb5uFQ5V.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C14nCb1q.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/memory-Dg0mvYrI.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/terminal-BG4heKCG.js","/assets/copy-NDbZjXao.js","/assets/CopyButton-DmJveP3T.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/pause-DTAcYxBt.js","/assets/book-open-D_nMCFmP.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/files-DO4CZ16O.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-C76mRRiF.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/chevron-down-BH2h1Ea2.js","/assets/search-fKo7v0Zo.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useToast-9FIWuYfK.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DtSmdtM4.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/labs-Zk7ryIM1.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/git-CFCTYk9I.js",imports:["/assets/chunk-JZWAC4HX-C4pqxYJB.js","/assets/useReportContext-O-jkvSPx.js","/assets/EntityItem-C76mRRiF.js","/assets/LogViewer-ceAyBX-H.js","/assets/fileTableUtils-cPo8LiG3.js","/assets/createLucideIcon-CMT1jU2q.js","/assets/useToast-9FIWuYfK.js","/assets/TruncatedFilePath-C8OKAR5x.js","/assets/SafeScreenshot-BED4B6sP.js","/assets/LibraryFunctionPreview-DLeucoVX.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DtSmdtM4.js","/assets/EntityTypeIcon-CobE682z.js","/assets/EntityTypeBadge-g3saevPb.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-af20abcd.js",version:"af20abcd",sri:void 0},cw="build/client",dw="/",uw={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},hw=!0,mw=!1,pw=[],fw={mode:"lazy",manifestPath:"/__manifest"},gw="/",yw={module:ed},xw={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:Mh},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,module:Ih},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,module:Bh},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,module:Uh},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,module:um},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,module:Mm},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,module:Lm},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,module:zm},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,module:Ym},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,module:Wm},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,module:qm},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,module:Kp},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,module:of},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,module:cf},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,module:uf},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,module:mf},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,module:ff},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,module:xf},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,module:Cf},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,module:Yf},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Wf},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,module:tg},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:ag},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:bg},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,module:Pg},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:jg},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:$g},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Dg},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Fg},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Bg},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,module:Wg},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:t0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:r0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:d0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:f0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:b0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:C0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:k0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:B0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:U0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:G0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:Q0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:ry},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:ay},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:fy},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:xy},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:vy},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:Sy},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Ey},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:jy},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:ex},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:rx},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:dx},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:hx},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:px},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Px},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:jx},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Rx},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:Bx},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:Ux},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:Zx},"routes/editor":{id:"routes/editor",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:xb},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:zb},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Jb},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:tv},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:hv}},bw=!1;export{cu as A,ou as B,Te as C,Td as D,$d as E,nn as F,vd as G,ai as H,oi as I,Cd as J,ii as K,Ed as L,Pd as M,cw as N,dw as O,xd as P,uw as Q,hw as R,yr as S,mw as T,pw as U,fw as V,gw as W,yw as X,xw as Y,bw as Z,lw as _,md as a,hn as b,Xt as c,Et as d,Bn as e,sa as f,aa as g,si as h,ud as i,Ud as j,Wd as k,Dt as l,At as m,di as n,Zd as o,br as p,ut as q,ui as r,hi as s,ru as t,Rt as u,mi as v,gn as w,mn as x,eo as y,hu as z};