@codeyam/codeyam-cli 0.1.0-staging.e38f7bd → 0.1.0-staging.fef152f

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 (1052) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/common/execAsync.ts +1 -1
  3. package/analyzer-template/log.txt +3 -3
  4. package/analyzer-template/package.json +30 -26
  5. package/analyzer-template/packages/ai/index.ts +21 -5
  6. package/analyzer-template/packages/ai/package.json +4 -4
  7. package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
  8. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +228 -24
  9. package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
  10. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +205 -10
  11. package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
  12. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +181 -23
  13. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.ts +10 -17
  14. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.ts +18 -0
  15. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +38 -1
  16. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +181 -1
  17. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +1619 -125
  18. package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
  19. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +324 -5
  20. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
  21. package/analyzer-template/packages/ai/src/lib/completionCall.ts +216 -36
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +2761 -390
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +21 -4
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +976 -0
  25. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +243 -77
  26. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
  27. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
  28. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +71 -2
  29. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +161 -19
  30. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
  31. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +163 -14
  32. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  33. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
  34. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
  35. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +441 -82
  36. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
  37. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  38. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +183 -0
  39. package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
  40. package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
  41. package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
  42. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +74 -7
  43. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +89 -112
  44. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +63 -2
  45. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1419 -101
  46. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +216 -109
  47. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +710 -0
  48. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
  49. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +2484 -0
  50. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
  51. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
  52. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
  53. package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +328 -7
  54. package/analyzer-template/packages/ai/src/lib/mergeJsonTypeDefinitions.ts +5 -0
  55. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +111 -87
  56. package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
  57. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +17 -7
  58. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +1 -1
  59. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -102
  60. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
  61. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
  62. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +110 -6
  63. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +14 -53
  64. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.ts +58 -0
  65. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
  66. package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
  67. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +824 -0
  68. package/analyzer-template/packages/ai/src/lib/splitOutsideParentheses.ts +5 -1
  69. package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
  70. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +127 -3
  71. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +121 -2
  72. package/analyzer-template/packages/analyze/index.ts +2 -0
  73. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +79 -59
  74. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
  75. package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
  76. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  77. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
  78. package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
  79. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
  80. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
  81. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
  82. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
  83. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
  84. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
  85. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +570 -180
  86. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +54 -1
  87. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +6 -0
  88. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
  89. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
  90. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
  91. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +31 -15
  92. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +11 -7
  93. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +11 -12
  94. package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
  95. package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
  96. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +22 -13
  97. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1315 -0
  98. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +313 -0
  99. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
  100. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +711 -78
  101. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
  102. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +28 -62
  103. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +550 -137
  104. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +264 -0
  105. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +78 -83
  106. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +4 -8
  107. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +1067 -167
  108. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
  109. package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
  110. package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
  111. package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
  112. package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
  113. package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
  114. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
  115. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
  116. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
  117. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
  118. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
  119. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
  120. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
  121. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  122. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
  123. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
  124. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
  125. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  126. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
  127. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
  128. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
  129. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
  130. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
  131. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
  132. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
  133. package/analyzer-template/packages/aws/package.json +10 -10
  134. package/analyzer-template/packages/aws/s3/index.ts +1 -0
  135. package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
  136. package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
  137. package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
  138. package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
  139. package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
  140. package/analyzer-template/packages/database/package.json +1 -1
  141. package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +1 -1
  142. package/analyzer-template/packages/database/src/lib/analysisToDb.ts +1 -1
  143. package/analyzer-template/packages/database/src/lib/branchToDb.ts +1 -1
  144. package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +1 -1
  145. package/analyzer-template/packages/database/src/lib/commitToDb.ts +1 -1
  146. package/analyzer-template/packages/database/src/lib/fileToDb.ts +1 -1
  147. package/analyzer-template/packages/database/src/lib/kysely/db.ts +18 -5
  148. package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
  149. package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
  150. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +36 -9
  151. package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
  152. package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
  153. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
  154. package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
  155. package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
  156. package/analyzer-template/packages/database/src/lib/loadCommits.ts +28 -0
  157. package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
  158. package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
  159. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +30 -5
  160. package/analyzer-template/packages/database/src/lib/projectToDb.ts +1 -1
  161. package/analyzer-template/packages/database/src/lib/saveFiles.ts +1 -1
  162. package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +1 -1
  163. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +7 -14
  164. package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +1 -1
  165. package/analyzer-template/packages/generate/index.ts +3 -0
  166. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
  167. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
  168. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
  169. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
  170. package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
  171. package/analyzer-template/packages/generate/src/lib/directExecutionScript.ts +17 -2
  172. package/analyzer-template/packages/generate/src/lib/getComponentScenarioPath.ts +8 -3
  173. package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
  174. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +1 -1
  175. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -1
  176. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +1 -1
  177. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -1
  178. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +1 -1
  179. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -1
  180. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +1 -1
  181. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -1
  182. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +1 -1
  183. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -1
  184. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +1 -1
  185. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -1
  186. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +4 -2
  187. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  188. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +13 -3
  189. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  190. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
  191. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +1 -11
  192. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  193. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +1 -0
  194. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
  195. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
  196. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  197. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +30 -7
  198. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  199. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  200. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  201. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
  202. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
  203. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
  204. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
  205. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  206. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  207. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +2 -6
  208. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  209. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +2 -0
  210. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
  211. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
  212. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
  213. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  214. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
  215. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  216. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
  217. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
  218. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
  219. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
  220. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
  221. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
  222. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  223. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +22 -1
  224. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  225. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
  226. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  227. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
  228. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  229. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
  230. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
  231. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -1
  232. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  233. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
  234. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  235. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +1 -1
  236. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -1
  237. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +1 -1
  238. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -1
  239. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +1 -1
  240. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -1
  241. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +2 -2
  242. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  243. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +5 -4
  244. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  245. package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
  246. package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
  247. package/analyzer-template/packages/github/dist/generate/index.js +3 -0
  248. package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
  249. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  250. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  251. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  252. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
  253. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
  254. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  255. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  256. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
  257. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
  258. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  259. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  260. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  261. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  262. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  263. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
  264. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
  265. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
  266. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.d.ts.map +1 -1
  267. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js +10 -1
  268. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js.map +1 -1
  269. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.d.ts.map +1 -1
  270. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js +7 -3
  271. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  272. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
  273. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
  274. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
  275. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  276. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
  277. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
  278. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
  279. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
  280. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
  281. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
  282. package/analyzer-template/packages/github/dist/types/index.d.ts +2 -2
  283. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  284. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  285. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +87 -13
  286. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  287. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts +2 -0
  288. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts.map +1 -1
  289. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
  290. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
  291. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  292. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  293. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +11 -6
  294. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  295. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
  296. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  297. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  298. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  299. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts +2 -0
  300. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  301. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  302. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  303. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  304. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  305. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  306. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  307. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
  308. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  309. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
  310. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
  311. package/analyzer-template/packages/github/package.json +1 -1
  312. package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
  313. package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
  314. package/analyzer-template/packages/process/index.ts +2 -0
  315. package/analyzer-template/packages/process/package.json +12 -0
  316. package/analyzer-template/packages/process/tsconfig.json +8 -0
  317. package/analyzer-template/packages/types/index.ts +5 -0
  318. package/analyzer-template/packages/types/src/types/Analysis.ts +104 -13
  319. package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
  320. package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
  321. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +7 -0
  322. package/analyzer-template/packages/types/src/types/Scenario.ts +11 -10
  323. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +228 -3
  324. package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
  325. package/analyzer-template/packages/types/src/types/StatementInfo.ts +2 -0
  326. package/analyzer-template/packages/ui-components/package.json +4 -4
  327. package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
  328. package/analyzer-template/packages/utils/dist/types/index.d.ts +2 -2
  329. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  330. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  331. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +87 -13
  332. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  333. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts +2 -0
  334. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts.map +1 -1
  335. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
  336. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
  337. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  338. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  339. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +11 -6
  340. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  341. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
  342. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  343. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  344. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  345. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts +2 -0
  346. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  347. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  348. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  349. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  350. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  351. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +98 -3
  352. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  353. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  354. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  355. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  356. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
  357. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  358. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
  359. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
  360. package/analyzer-template/packages/utils/src/lib/applyUniversalMocks.ts +28 -2
  361. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +121 -3
  362. package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
  363. package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
  364. package/analyzer-template/playwright/capture.ts +57 -26
  365. package/analyzer-template/playwright/captureStatic.ts +1 -1
  366. package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
  367. package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
  368. package/analyzer-template/playwright/takeScreenshot.ts +15 -9
  369. package/analyzer-template/playwright/waitForServer.ts +21 -6
  370. package/analyzer-template/project/TESTING.md +83 -0
  371. package/analyzer-template/project/analyzeBaselineCommit.ts +9 -0
  372. package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
  373. package/analyzer-template/project/analyzeFileEntities.ts +4 -0
  374. package/analyzer-template/project/analyzeRegularCommit.ts +9 -0
  375. package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
  376. package/analyzer-template/project/constructMockCode.ts +1347 -159
  377. package/analyzer-template/project/controller/startController.ts +16 -1
  378. package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
  379. package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
  380. package/analyzer-template/project/loadReadyToBeCaptured.ts +82 -42
  381. package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
  382. package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
  383. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +13 -9
  384. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +93 -42
  385. package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
  386. package/analyzer-template/project/orchestrateCapture.ts +92 -13
  387. package/analyzer-template/project/reconcileMockDataKeys.ts +245 -2
  388. package/analyzer-template/project/runAnalysis.ts +11 -0
  389. package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
  390. package/analyzer-template/project/serverOnlyModules.ts +413 -0
  391. package/analyzer-template/project/start.ts +72 -19
  392. package/analyzer-template/project/startScenarioCapture.ts +79 -41
  393. package/analyzer-template/project/writeMockDataTsx.ts +466 -73
  394. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  395. package/analyzer-template/project/writeScenarioComponents.ts +1509 -226
  396. package/analyzer-template/project/writeScenarioFiles.ts +26 -0
  397. package/analyzer-template/project/writeSimpleRoot.ts +56 -22
  398. package/analyzer-template/project/writeUniversalMocks.ts +32 -11
  399. package/analyzer-template/scripts/comboWorkerLoop.cjs +99 -50
  400. package/analyzer-template/scripts/defaultCmd.sh +9 -0
  401. package/analyzer-template/tsconfig.json +2 -1
  402. package/background/src/lib/local/createLocalAnalyzer.js +2 -30
  403. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  404. package/background/src/lib/local/execAsync.js +1 -1
  405. package/background/src/lib/local/execAsync.js.map +1 -1
  406. package/background/src/lib/virtualized/common/execAsync.js +1 -1
  407. package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
  408. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +7 -1
  409. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
  410. package/background/src/lib/virtualized/project/analyzeBranchCommit.js +2 -1
  411. package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
  412. package/background/src/lib/virtualized/project/analyzeFileEntities.js +2 -1
  413. package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
  414. package/background/src/lib/virtualized/project/analyzeRegularCommit.js +7 -1
  415. package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
  416. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
  417. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
  418. package/background/src/lib/virtualized/project/constructMockCode.js +1194 -120
  419. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  420. package/background/src/lib/virtualized/project/controller/startController.js +11 -1
  421. package/background/src/lib/virtualized/project/controller/startController.js.map +1 -1
  422. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js +73 -1
  423. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js.map +1 -1
  424. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js +6 -3
  425. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js.map +1 -1
  426. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +34 -9
  427. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  428. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js +7 -7
  429. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js.map +1 -1
  430. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js +2 -2
  431. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js.map +1 -1
  432. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +12 -6
  433. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  434. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +73 -36
  435. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  436. package/background/src/lib/virtualized/project/orchestrateCapture.js +76 -14
  437. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  438. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +204 -2
  439. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  440. package/background/src/lib/virtualized/project/runAnalysis.js +9 -0
  441. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  442. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
  443. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  444. package/background/src/lib/virtualized/project/serverOnlyModules.js +338 -0
  445. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -0
  446. package/background/src/lib/virtualized/project/start.js +62 -19
  447. package/background/src/lib/virtualized/project/start.js.map +1 -1
  448. package/background/src/lib/virtualized/project/startScenarioCapture.js +61 -31
  449. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  450. package/background/src/lib/virtualized/project/writeMockDataTsx.js +404 -62
  451. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  452. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
  453. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
  454. package/background/src/lib/virtualized/project/writeScenarioComponents.js +1112 -153
  455. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  456. package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
  457. package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
  458. package/background/src/lib/virtualized/project/writeSimpleRoot.js +57 -20
  459. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  460. package/background/src/lib/virtualized/project/writeUniversalMocks.js +27 -12
  461. package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
  462. package/codeyam-cli/scripts/apply-setup.js +180 -0
  463. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  464. package/codeyam-cli/src/cli.js +38 -17
  465. package/codeyam-cli/src/cli.js.map +1 -1
  466. package/codeyam-cli/src/codeyam-cli.js +18 -2
  467. package/codeyam-cli/src/codeyam-cli.js.map +1 -1
  468. package/codeyam-cli/src/commands/analyze.js +5 -3
  469. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  470. package/codeyam-cli/src/commands/baseline.js +176 -0
  471. package/codeyam-cli/src/commands/baseline.js.map +1 -0
  472. package/codeyam-cli/src/commands/debug.js +44 -18
  473. package/codeyam-cli/src/commands/debug.js.map +1 -1
  474. package/codeyam-cli/src/commands/default.js +30 -34
  475. package/codeyam-cli/src/commands/default.js.map +1 -1
  476. package/codeyam-cli/src/commands/detect-universal-mocks.js +2 -0
  477. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +1 -1
  478. package/codeyam-cli/src/commands/init.js +49 -257
  479. package/codeyam-cli/src/commands/init.js.map +1 -1
  480. package/codeyam-cli/src/commands/memory.js +254 -0
  481. package/codeyam-cli/src/commands/memory.js.map +1 -0
  482. package/codeyam-cli/src/commands/recapture.js +228 -0
  483. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  484. package/codeyam-cli/src/commands/report.js +72 -24
  485. package/codeyam-cli/src/commands/report.js.map +1 -1
  486. package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
  487. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
  488. package/codeyam-cli/src/commands/setup-simulations.js +284 -0
  489. package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
  490. package/codeyam-cli/src/commands/start.js +8 -12
  491. package/codeyam-cli/src/commands/start.js.map +1 -1
  492. package/codeyam-cli/src/commands/status.js +23 -1
  493. package/codeyam-cli/src/commands/status.js.map +1 -1
  494. package/codeyam-cli/src/commands/test-startup.js +3 -1
  495. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  496. package/codeyam-cli/src/commands/verify.js +14 -2
  497. package/codeyam-cli/src/commands/verify.js.map +1 -1
  498. package/codeyam-cli/src/commands/wipe.js +108 -0
  499. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  500. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +185 -0
  501. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  502. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
  503. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
  504. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +128 -82
  505. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  506. package/codeyam-cli/src/utils/analysisRunner.js +29 -15
  507. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  508. package/codeyam-cli/src/utils/analyzer.js +7 -0
  509. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  510. package/codeyam-cli/src/utils/backgroundServer.js +104 -23
  511. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  512. package/codeyam-cli/src/utils/database.js +91 -5
  513. package/codeyam-cli/src/utils/database.js.map +1 -1
  514. package/codeyam-cli/src/utils/generateReport.js +253 -106
  515. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  516. package/codeyam-cli/src/utils/git.js +79 -0
  517. package/codeyam-cli/src/utils/git.js.map +1 -0
  518. package/codeyam-cli/src/utils/install-skills.js +76 -42
  519. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  520. package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
  521. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
  522. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  523. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  524. package/codeyam-cli/src/utils/progress.js +7 -0
  525. package/codeyam-cli/src/utils/progress.js.map +1 -1
  526. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  527. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  528. package/codeyam-cli/src/utils/queue/job.js +249 -16
  529. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  530. package/codeyam-cli/src/utils/queue/manager.js +103 -7
  531. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  532. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  533. package/codeyam-cli/src/utils/requireSimulations.js +10 -0
  534. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
  535. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
  536. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
  537. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +230 -0
  538. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
  539. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
  540. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
  541. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
  542. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
  543. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
  544. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
  545. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
  546. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
  547. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +74 -0
  548. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
  549. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +376 -0
  550. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
  551. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +116 -0
  552. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
  553. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
  554. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
  555. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
  556. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
  557. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +116 -0
  558. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
  559. package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
  560. package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
  561. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +44 -0
  562. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
  563. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
  564. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
  565. package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
  566. package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
  567. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +84 -0
  568. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
  569. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
  570. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
  571. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js +83 -0
  572. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
  573. package/codeyam-cli/src/utils/rules/index.js +7 -0
  574. package/codeyam-cli/src/utils/rules/index.js.map +1 -0
  575. package/codeyam-cli/src/utils/rules/parser.js +83 -0
  576. package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
  577. package/codeyam-cli/src/utils/rules/pathMatcher.js +28 -0
  578. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
  579. package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
  580. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
  581. package/codeyam-cli/src/utils/rules/sourceFiles.js +47 -0
  582. package/codeyam-cli/src/utils/rules/sourceFiles.js.map +1 -0
  583. package/codeyam-cli/src/utils/rules/staleness.js +137 -0
  584. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
  585. package/codeyam-cli/src/utils/serverState.js +37 -10
  586. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  587. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +21 -42
  588. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  589. package/codeyam-cli/src/utils/simulationGateMiddleware.js +138 -0
  590. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  591. package/codeyam-cli/src/utils/syncMocksMiddleware.js +5 -24
  592. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  593. package/codeyam-cli/src/utils/versionInfo.js +67 -15
  594. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  595. package/codeyam-cli/src/utils/wipe.js +128 -0
  596. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  597. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  598. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  599. package/codeyam-cli/src/webserver/app/lib/database.js +118 -6
  600. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  601. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  602. package/codeyam-cli/src/webserver/backgroundServer.js +55 -10
  603. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  604. package/codeyam-cli/src/webserver/bootstrap.js +60 -0
  605. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  606. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-jNYXRRNI.js +1 -0
  607. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-bwuHPyTa.js +11 -0
  608. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-kykTbcnD.js → EntityTypeBadge-CvzqMxcu.js} +1 -1
  609. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BH0XDim7.js +41 -0
  610. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-EhOseatT.js +34 -0
  611. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-yjIHlOGa.js +25 -0
  612. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-Cq5o8jL4.js +3 -0
  613. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-BvMu2i-g.js +6 -0
  614. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-kgBTLoJD.js +3 -0
  615. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BzPgx-xO.js +11 -0
  616. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-CwZrv-Ok.js +1 -0
  617. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BX2Ny2Qj.js +10 -0
  618. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-C06nsHKY.js → TruncatedFilePath-CDpEprKa.js} +1 -1
  619. package/codeyam-cli/src/webserver/build/client/assets/_index-BRx8ZGZo.js +11 -0
  620. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-4S4yPfFw.js +27 -0
  621. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DHKuQSmR.js +17 -0
  622. package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
  623. package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
  624. package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-l0sNRNKZ.js +1 -0
  625. package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
  626. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  627. package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
  628. package/codeyam-cli/src/webserver/build/client/assets/book-open-D4IPYH_y.js +6 -0
  629. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-CG65viiV.js +6 -0
  630. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-DB3aFuEO.js +51 -0
  631. package/codeyam-cli/src/webserver/build/client/assets/circle-check-igfMr5DY.js +6 -0
  632. package/codeyam-cli/src/webserver/build/client/assets/copy-Coc4o_8c.js +11 -0
  633. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-D1zB-pYc.js +21 -0
  634. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
  635. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
  636. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-JTAjQ54M.js +1 -0
  637. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CYqBrC9s.js → entity._sha._-B0h9AqE6.js} +22 -15
  638. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DjLxr2JB.js +6 -0
  639. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-CtYowLOt.js +6 -0
  640. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-PePWg17F.js +5 -0
  641. package/codeyam-cli/src/webserver/build/client/assets/entry.client-I-Wo99C_.js +29 -0
  642. package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
  643. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-9sMMAiWJ.js +1 -0
  644. package/codeyam-cli/src/webserver/build/client/assets/files-Co65J0s3.js +1 -0
  645. package/codeyam-cli/src/webserver/build/client/assets/git-BdHOxVfg.js +15 -0
  646. package/codeyam-cli/src/webserver/build/client/assets/globals-Dzl-jeq-.css +1 -0
  647. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  648. package/codeyam-cli/src/webserver/build/client/assets/index-CUM5iXwc.js +9 -0
  649. package/codeyam-cli/src/webserver/build/client/assets/index-_417gcQW.js +3 -0
  650. package/codeyam-cli/src/webserver/build/client/assets/labs-DAvt-sy-.js +1 -0
  651. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-TzRHMVog.js +6 -0
  652. package/codeyam-cli/src/webserver/build/client/assets/manifest-2d0e2ebb.js +1 -0
  653. package/codeyam-cli/src/webserver/build/client/assets/memory-DVGtTawo.js +92 -0
  654. package/codeyam-cli/src/webserver/build/client/assets/pause-hjzB7t2z.js +11 -0
  655. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  656. package/codeyam-cli/src/webserver/build/client/assets/root-Bg3WICdl.js +62 -0
  657. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  658. package/codeyam-cli/src/webserver/build/client/assets/search-DcAwD_Ln.js +6 -0
  659. package/codeyam-cli/src/webserver/build/client/assets/settings-CclxrcPK.js +1 -0
  660. package/codeyam-cli/src/webserver/build/client/assets/simulations-DVNJVQgD.js +1 -0
  661. package/codeyam-cli/src/webserver/build/client/assets/terminal-DbEAHMbA.js +11 -0
  662. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-CAD5b1o_.js +6 -0
  663. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BqgrAzs3.js +1 -0
  664. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-Blr5oZDE.js → useLastLogLine-DAFqfEDH.js} +1 -1
  665. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DZlYx2c4.js +1 -0
  666. package/codeyam-cli/src/webserver/build/client/assets/{useToast-Bbf4Hokd.js → useToast-ihdMtlf6.js} +1 -1
  667. package/codeyam-cli/src/webserver/build/server/assets/index-CpreP2n8.js +1 -0
  668. package/codeyam-cli/src/webserver/build/server/assets/server-build-DyvoFrHR.js +273 -0
  669. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  670. package/codeyam-cli/src/webserver/build-info.json +5 -5
  671. package/codeyam-cli/src/webserver/devServer.js +1 -3
  672. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  673. package/codeyam-cli/src/webserver/server.js +35 -25
  674. package/codeyam-cli/src/webserver/server.js.map +1 -1
  675. package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam-debug.md} +48 -4
  676. package/codeyam-cli/templates/codeyam-diagnose.md +481 -0
  677. package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
  678. package/codeyam-cli/templates/codeyam-memory.md +396 -0
  679. package/codeyam-cli/templates/codeyam-new-rule.md +13 -0
  680. package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam-setup.md} +151 -4
  681. package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam-sim.md} +1 -1
  682. package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam-test.md} +1 -1
  683. package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam-verify.md} +1 -1
  684. package/codeyam-cli/templates/rule-notification-hook.py +56 -0
  685. package/codeyam-cli/templates/rule-reflection-hook.py +627 -0
  686. package/codeyam-cli/templates/rules-instructions.md +132 -0
  687. package/package.json +26 -23
  688. package/packages/ai/index.js +8 -6
  689. package/packages/ai/index.js.map +1 -1
  690. package/packages/ai/src/lib/analyzeScope.js +181 -13
  691. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  692. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  693. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  694. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +154 -9
  695. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  696. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
  697. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
  698. package/packages/ai/src/lib/astScopes/methodSemantics.js +138 -23
  699. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  700. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
  701. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
  702. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
  703. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
  704. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +23 -0
  705. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  706. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
  707. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  708. package/packages/ai/src/lib/astScopes/processExpression.js +1235 -104
  709. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  710. package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
  711. package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
  712. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  713. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  714. package/packages/ai/src/lib/completionCall.js +178 -31
  715. package/packages/ai/src/lib/completionCall.js.map +1 -1
  716. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +2171 -224
  717. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  718. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +19 -4
  719. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  720. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +661 -0
  721. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  722. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +180 -56
  723. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  724. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  725. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  726. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  727. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  728. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +66 -2
  729. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  730. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +139 -13
  731. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  732. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
  733. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
  734. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +142 -12
  735. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  736. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  737. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  738. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
  739. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  740. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  741. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  742. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +371 -73
  743. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  744. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  745. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  746. package/packages/ai/src/lib/dataStructureChunking.js +130 -0
  747. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  748. package/packages/ai/src/lib/deepEqual.js +32 -0
  749. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  750. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  751. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  752. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  753. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  754. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
  755. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  756. package/packages/ai/src/lib/generateChangesEntityScenarios.js +81 -90
  757. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  758. package/packages/ai/src/lib/generateEntityDataStructure.js +50 -1
  759. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  760. package/packages/ai/src/lib/generateEntityScenarioData.js +1127 -91
  761. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  762. package/packages/ai/src/lib/generateEntityScenarios.js +193 -83
  763. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  764. package/packages/ai/src/lib/generateExecutionFlows.js +495 -0
  765. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
  766. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
  767. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
  768. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1807 -0
  769. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
  770. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  771. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  772. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  773. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  774. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  775. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  776. package/packages/ai/src/lib/isolateScopes.js +270 -7
  777. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  778. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
  779. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
  780. package/packages/ai/src/lib/mergeStatements.js +88 -46
  781. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  782. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
  783. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
  784. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +16 -4
  785. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  786. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
  787. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  788. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -64
  789. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  790. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  791. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  792. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +83 -6
  793. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  794. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -34
  795. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  796. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
  797. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
  798. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  799. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  800. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  801. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  802. package/packages/ai/src/lib/resolvePathToControllable.js +677 -0
  803. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
  804. package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
  805. package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
  806. package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
  807. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  808. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +98 -1
  809. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  810. package/packages/analyze/index.js +1 -0
  811. package/packages/analyze/index.js.map +1 -1
  812. package/packages/analyze/src/lib/FileAnalyzer.js +75 -36
  813. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  814. package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
  815. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  816. package/packages/analyze/src/lib/analysisContext.js +30 -5
  817. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  818. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  819. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  820. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  821. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  822. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  823. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  824. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  825. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  826. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  827. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  828. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  829. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  830. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  831. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  832. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  833. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  834. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  835. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  836. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +428 -123
  837. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  838. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +42 -1
  839. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  840. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
  841. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  842. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  843. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  844. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  845. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  846. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
  847. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  848. package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
  849. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  850. package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
  851. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  852. package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
  853. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  854. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  855. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  856. package/packages/analyze/src/lib/files/enums/steps.js +1 -1
  857. package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
  858. package/packages/analyze/src/lib/files/getImportedExports.js +17 -8
  859. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  860. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
  861. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
  862. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +255 -0
  863. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  864. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  865. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  866. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +550 -62
  867. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  868. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  869. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  870. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
  871. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  872. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +404 -85
  873. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  874. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +144 -0
  875. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
  876. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +56 -69
  877. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  878. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +4 -8
  879. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  880. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +875 -141
  881. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  882. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  883. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  884. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  885. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  886. package/packages/analyze/src/lib/index.js +1 -0
  887. package/packages/analyze/src/lib/index.js.map +1 -1
  888. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  889. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  890. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  891. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  892. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  893. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  894. package/packages/database/src/lib/analysisBranchToDb.js +1 -1
  895. package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
  896. package/packages/database/src/lib/analysisToDb.js +1 -1
  897. package/packages/database/src/lib/analysisToDb.js.map +1 -1
  898. package/packages/database/src/lib/branchToDb.js +1 -1
  899. package/packages/database/src/lib/branchToDb.js.map +1 -1
  900. package/packages/database/src/lib/commitBranchToDb.js +1 -1
  901. package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
  902. package/packages/database/src/lib/commitToDb.js +1 -1
  903. package/packages/database/src/lib/commitToDb.js.map +1 -1
  904. package/packages/database/src/lib/fileToDb.js +1 -1
  905. package/packages/database/src/lib/fileToDb.js.map +1 -1
  906. package/packages/database/src/lib/kysely/db.js +13 -3
  907. package/packages/database/src/lib/kysely/db.js.map +1 -1
  908. package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
  909. package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  910. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  911. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  912. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  913. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  914. package/packages/database/src/lib/loadAnalyses.js +45 -2
  915. package/packages/database/src/lib/loadAnalyses.js.map +1 -1
  916. package/packages/database/src/lib/loadAnalysis.js +8 -0
  917. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  918. package/packages/database/src/lib/loadBranch.js +11 -1
  919. package/packages/database/src/lib/loadBranch.js.map +1 -1
  920. package/packages/database/src/lib/loadCommit.js +7 -0
  921. package/packages/database/src/lib/loadCommit.js.map +1 -1
  922. package/packages/database/src/lib/loadCommits.js +22 -1
  923. package/packages/database/src/lib/loadCommits.js.map +1 -1
  924. package/packages/database/src/lib/loadEntities.js +23 -4
  925. package/packages/database/src/lib/loadEntities.js.map +1 -1
  926. package/packages/database/src/lib/loadEntityBranches.js +9 -0
  927. package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
  928. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
  929. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  930. package/packages/database/src/lib/projectToDb.js +1 -1
  931. package/packages/database/src/lib/projectToDb.js.map +1 -1
  932. package/packages/database/src/lib/saveFiles.js +1 -1
  933. package/packages/database/src/lib/saveFiles.js.map +1 -1
  934. package/packages/database/src/lib/scenarioToDb.js +1 -1
  935. package/packages/database/src/lib/scenarioToDb.js.map +1 -1
  936. package/packages/database/src/lib/updateCommitMetadata.js +5 -4
  937. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  938. package/packages/generate/index.js +3 -0
  939. package/packages/generate/index.js.map +1 -1
  940. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  941. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  942. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  943. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  944. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  945. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  946. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  947. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  948. package/packages/generate/src/lib/deepMerge.js +27 -1
  949. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  950. package/packages/generate/src/lib/directExecutionScript.js +10 -1
  951. package/packages/generate/src/lib/directExecutionScript.js.map +1 -1
  952. package/packages/generate/src/lib/getComponentScenarioPath.js +7 -3
  953. package/packages/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  954. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  955. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  956. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  957. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  958. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  959. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  960. package/packages/process/index.js +3 -0
  961. package/packages/process/index.js.map +1 -0
  962. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  963. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  964. package/packages/process/src/ProcessManager.js.map +1 -0
  965. package/packages/process/src/index.js.map +1 -0
  966. package/packages/process/src/managedExecAsync.js.map +1 -0
  967. package/packages/types/index.js.map +1 -1
  968. package/packages/utils/src/lib/applyUniversalMocks.js +26 -2
  969. package/packages/utils/src/lib/applyUniversalMocks.js.map +1 -1
  970. package/packages/utils/src/lib/fs/rsyncCopy.js +98 -3
  971. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  972. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  973. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  974. package/packages/utils/src/lib/safeFileName.js +29 -3
  975. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  976. package/scripts/finalize-analyzer.cjs +8 -74
  977. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
  978. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -197
  979. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -271
  980. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -294
  981. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
  982. package/analyzer-template/packages/ai/src/lib/transformMockDataToMatchSchema.ts +0 -156
  983. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -115
  984. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  985. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  986. package/analyzer-template/process/README.md +0 -507
  987. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  988. package/background/src/lib/process/ProcessManager.js.map +0 -1
  989. package/background/src/lib/process/index.js.map +0 -1
  990. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  991. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  992. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  993. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-D4htqD-x.js +0 -1
  994. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-Catz6XEN.js +0 -1
  995. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-TlHocYno.js +0 -26
  996. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CVMmGuIc.js +0 -3
  997. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-JkfQ-VaI.js +0 -3
  998. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-CVZ0H4BL.js +0 -1
  999. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BrMAP1nP.js +0 -1
  1000. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CJhE4cCv.js +0 -5
  1001. package/codeyam-cli/src/webserver/build/client/assets/_index-faVIcr_i.js +0 -1
  1002. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CLMa2sgx.js +0 -7
  1003. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-DwYjrK_h.js +0 -1
  1004. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CgXbbZRx.js +0 -26
  1005. package/codeyam-cli/src/webserver/build/client/assets/circle-check-B2oHQ-zo.js +0 -1
  1006. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BBYuR56H.js +0 -1
  1007. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CT0Q5lVu.js +0 -1
  1008. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-Bj5GHkhb.js +0 -1
  1009. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-eW5z9AyZ.js +0 -5
  1010. package/codeyam-cli/src/webserver/build/client/assets/entry.client-B9tSboXM.js +0 -5
  1011. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-CmO-EZAB.js +0 -1
  1012. package/codeyam-cli/src/webserver/build/client/assets/files-DLinnTOx.js +0 -1
  1013. package/codeyam-cli/src/webserver/build/client/assets/git-CIxwBQvb.js +0 -12
  1014. package/codeyam-cli/src/webserver/build/client/assets/globals-xPz593l2.css +0 -1
  1015. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  1016. package/codeyam-cli/src/webserver/build/client/assets/index-_LjBsTxX.js +0 -8
  1017. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-D_EGChhq.js +0 -1
  1018. package/codeyam-cli/src/webserver/build/client/assets/manifest-ca438c41.js +0 -1
  1019. package/codeyam-cli/src/webserver/build/client/assets/root-CHHYHuzL.js +0 -16
  1020. package/codeyam-cli/src/webserver/build/client/assets/search-DY8yoDpH.js +0 -1
  1021. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  1022. package/codeyam-cli/src/webserver/build/client/assets/settings-BT6wVHd5.js +0 -1
  1023. package/codeyam-cli/src/webserver/build/client/assets/simulations-gv3H7JV7.js +0 -1
  1024. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-BthANBVv.js +0 -1
  1025. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-CANr3QJ5.js +0 -1
  1026. package/codeyam-cli/src/webserver/build/server/assets/index-BtBPtyHx.js +0 -1
  1027. package/codeyam-cli/src/webserver/build/server/assets/server-build-N2cTnejq.js +0 -166
  1028. package/codeyam-cli/templates/debug-command.md +0 -141
  1029. package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
  1030. package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
  1031. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -136
  1032. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
  1033. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -220
  1034. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
  1035. package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -241
  1036. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
  1037. package/packages/ai/src/lib/isFrontend.js +0 -5
  1038. package/packages/ai/src/lib/isFrontend.js.map +0 -1
  1039. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
  1040. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
  1041. package/packages/ai/src/lib/transformMockDataToMatchSchema.js +0 -124
  1042. package/packages/ai/src/lib/transformMockDataToMatchSchema.js.map +0 -1
  1043. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -72
  1044. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
  1045. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  1046. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  1047. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  1048. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  1049. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
  1050. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  1051. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  1052. /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
@@ -82,21 +82,36 @@
82
82
  import { ScopeAnalysis } from '~codeyam/types';
83
83
  import { EquivalencyManager } from './equivalencyManagers/EquivalencyManager';
84
84
  import fillInSchemaGapsAndUnknowns from './helpers/fillInSchemaGapsAndUnknowns';
85
+ import { clearCleanKnownObjectFunctionsCache } from './helpers/cleanKnownObjectFunctions';
86
+ import { clearCleanNonObjectFunctionsCache } from './helpers/cleanNonObjectFunctions';
87
+
88
+ /**
89
+ * Patterns that indicate recursive type structures in schema paths.
90
+ * Used by hasExcessivePatternRepetition() to detect exponential path blowup.
91
+ */
92
+ const RECURSIVE_PATH_PATTERNS = [
93
+ /\.attributes\.properties\[\]/g, // TypeScript AST JSX nodes
94
+ /\.children\[\]/g, // Tree structures
95
+ /\.elements\[\]/g, // Array-like structures
96
+ /\.members\[\]/g, // Class/interface members
97
+ /\.properties\[\]/g, // Object properties
98
+ /\.items\[\]/g, // Generic items arrays
99
+ ];
85
100
  import ensureSchemaConsistency from './helpers/ensureSchemaConsistency';
86
101
  import cleanPath from './helpers/cleanPath';
87
102
  import { PathManager } from './helpers/PathManager';
88
103
  import {
89
104
  uniqueId,
90
- uniqueScopeVariables,
91
105
  uniqueScopeAndPaths,
106
+ uniqueScopeVariables,
92
107
  } from './helpers/uniqueIdUtils';
93
108
  import selectBestValue from './helpers/selectBestValue';
94
109
  import { VisitedTracker } from './helpers/VisitedTracker';
95
110
  import { DebugTracer } from './helpers/DebugTracer';
96
111
  import { BatchSchemaProcessor } from './helpers/BatchSchemaProcessor';
97
112
  import {
98
- ScopeTreeManager,
99
113
  ROOT_SCOPE_NAME,
114
+ ScopeTreeManager,
100
115
  ScopeTreeNode,
101
116
  } from './helpers/ScopeTreeManager';
102
117
  import cleanScopeNodeName from './helpers/cleanScopeNodeName';
@@ -108,6 +123,7 @@ import type {
108
123
  SerializableFunctionCallInfo,
109
124
  SerializableFunctionResult,
110
125
  SerializableScopeVariable,
126
+ EnrichedConditionalUsage,
111
127
  } from '../worker/SerializableDataStructure';
112
128
 
113
129
  /**
@@ -125,6 +141,21 @@ export interface ScopeInfo {
125
141
  isStatic?: boolean;
126
142
  isClassScope?: boolean;
127
143
  analysis?: any;
144
+ /** For JSX child scopes, the original JSX tag name (e.g., 'ChildViewer') */
145
+ jsxTagName?: string;
146
+ /**
147
+ * Gating conditions detected during JSX extraction (before JSX is simplified).
148
+ * Maps child component name to conditions that must be true for it to render.
149
+ * This is populated by processJSXForScope in isolateScopes.ts.
150
+ */
151
+ extractedGatingConditions?: {
152
+ [childComponentName: string]: Array<{
153
+ path: string;
154
+ conditionType: 'truthiness' | 'comparison';
155
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
156
+ isNegated?: boolean;
157
+ }>;
158
+ };
128
159
  }
129
160
 
130
161
  /**
@@ -221,6 +252,22 @@ export interface FunctionCallInfo {
221
252
  * For example: { "db.select(query1)": "result1", "db.select(query2)": "result2" }
222
253
  */
223
254
  callSignatureToVariable?: Record<string, string>;
255
+ /**
256
+ * Stores individual schemas per call signature BEFORE merging.
257
+ * When multiple calls to the same function are merged into one FunctionCallInfo,
258
+ * this preserves each call's distinct schema.
259
+ * Key is the call signature (e.g., "useFetcher()").
260
+ * Used internally; converted to perVariableSchemas in toSerializable().
261
+ */
262
+ perCallSignatureSchemas?: Record<string, Record<string, string>>;
263
+ /**
264
+ * Stores individual return value schemas per receiving variable, BEFORE merging.
265
+ * When multiple calls to the same function have different return types
266
+ * (e.g., useFetcher<UserData>() vs useFetcher<ReportData>()), this preserves
267
+ * each call's distinct schema for mock data generation.
268
+ * Key is the receiving variable name (e.g., "userFetcher", "reportFetcher").
269
+ */
270
+ perVariableSchemas?: Record<string, Record<string, string>>;
224
271
  }
225
272
 
226
273
  /**
@@ -287,6 +334,19 @@ export function resetScopeDataStructureMetrics() {
287
334
  followEquivalenciesEarlyExitPhase1Count = 0;
288
335
  followEquivalenciesWithWorkCount = 0;
289
336
  addEquivalencyCallCount = 0;
337
+
338
+ // Clear module-level caches to prevent unbounded memory growth across entities
339
+ const knownObjectCache = clearCleanKnownObjectFunctionsCache();
340
+ const nonObjectCache = clearCleanNonObjectFunctionsCache();
341
+ if (knownObjectCache.count > 0 || nonObjectCache.count > 0) {
342
+ const totalBytes =
343
+ knownObjectCache.estimatedBytes + nonObjectCache.estimatedBytes;
344
+ console.log('CodeYam: Cleared analysis caches', {
345
+ knownObjectCache: `${knownObjectCache.count} entries, ${(knownObjectCache.estimatedBytes / 1024).toFixed(1)}KB`,
346
+ nonObjectCache: `${nonObjectCache.count} entries, ${(nonObjectCache.estimatedBytes / 1024).toFixed(1)}KB`,
347
+ totalKB: `${(totalBytes / 1024).toFixed(1)}KB`,
348
+ });
349
+ }
290
350
  }
291
351
 
292
352
  // Performance: Pre-computed Sets for equivalency reason filtering (O(1) vs O(n))
@@ -320,6 +380,10 @@ const ALLOWED_EQUIVALENCY_REASONS = new Set([
320
380
  'propagated function call return sub-property equivalency',
321
381
  'propagated parent-variable equivalency', // Added: propagate child scope equivalencies to parent scope when variable is defined in parent
322
382
  'where was this function called from', // Added: tracks which scope called an external function
383
+ 'MUI DataGrid renderCell params.row equivalency', // Added: links DataGrid renderCell params.row to rows array elements
384
+ 'MUI Autocomplete getOptionLabel option equivalency', // Added: links Autocomplete getOptionLabel callback param to options array
385
+ 'MUI Autocomplete renderOption option equivalency', // Added: links Autocomplete renderOption callback param to options array
386
+ 'MUI Autocomplete option property equivalency', // Added: propagates property accesses from Autocomplete callbacks
323
387
  ]);
324
388
 
325
389
  const SILENTLY_IGNORED_EQUIVALENCY_REASONS = new Set([
@@ -333,6 +397,7 @@ const SILENTLY_IGNORED_EQUIVALENCY_REASONS = new Set([
333
397
  'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
334
398
  'transformed non-object function equivalency - Array.from() equivalency',
335
399
  'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
400
+ // 'transformed non-object function equivalency - Explicit array deconstruction equivalency value',
336
401
  ]);
337
402
 
338
403
  export class ScopeDataStructure {
@@ -360,10 +425,40 @@ export class ScopeDataStructure {
360
425
  path: string;
361
426
  conditionType: 'truthiness' | 'comparison' | 'switch';
362
427
  comparedValues?: string[];
363
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
428
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
364
429
  }>
365
430
  > = {};
366
431
 
432
+ /**
433
+ * Conditional effects collected during AST analysis.
434
+ * Tracks what setter calls happen inside conditionals (if, switch, ternary).
435
+ */
436
+ private rawConditionalEffects: import('../astScopes/types').ConditionalEffect[] =
437
+ [];
438
+
439
+ /**
440
+ * Compound conditionals collected during AST analysis.
441
+ * Groups conditions that must all be true together (e.g., a && b && c).
442
+ */
443
+ private rawCompoundConditionals: import('../astScopes/types').CompoundConditional[] =
444
+ [];
445
+
446
+ /**
447
+ * Gating conditions for child component boundaries.
448
+ * Maps child component name to the conditions that must be true for it to render.
449
+ */
450
+ private rawChildBoundaryGatingConditions: Record<
451
+ string,
452
+ import('../astScopes/types').ConditionalUsage[]
453
+ > = {};
454
+
455
+ /**
456
+ * JSX rendering usages collected during AST analysis.
457
+ * Tracks arrays rendered via .map() and strings interpolated in JSX.
458
+ */
459
+ private rawJsxRenderingUsages: import('../astScopes/types').JsxRenderingUsage[] =
460
+ [];
461
+
367
462
  private lastAddToSchemaId = 0;
368
463
  private lastEquivalencyId = 0;
369
464
  private lastEquivalencyDatabaseId = 0;
@@ -382,6 +477,10 @@ export class ScopeDataStructure {
382
477
  private externalFunctionCallsIndex: Map<string, FunctionCallInfo> | null =
383
478
  null;
384
479
 
480
+ // Tracks internal functions that have been filtered out during captureCompleteSchema
481
+ // Prevents re-adding them via subsequent equivalency propagation (e.g., from getReturnValue)
482
+ private filteredInternalFunctions: Set<string> = new Set();
483
+
385
484
  // Debug tracer for selective path/scope tracing
386
485
  // Enable via: CODEYAM_DEBUG=true CODEYAM_DEBUG_PATHS="user.*,signature" npm test
387
486
  private tracer: DebugTracer = new DebugTracer({
@@ -540,6 +639,8 @@ export class ScopeDataStructure {
540
639
  const efcName = this.pathManager.stripGenerics(efc.name);
541
640
  for (const manager of this.equivalencyManagers) {
542
641
  if (manager.internalFunctions.has(efcName)) {
642
+ // Track this so we don't re-add it via subsequent finalize calls
643
+ this.filteredInternalFunctions.add(efcName);
543
644
  return false;
544
645
  }
545
646
  }
@@ -567,13 +668,51 @@ export class ScopeDataStructure {
567
668
  const baseName = this.pathManager.stripGenerics(
568
669
  candidate.scopeNodeName,
569
670
  );
671
+ // Check if this is a local variable path (doesn't contain function call pattern)
672
+ // Local variables like "surveys[]" or "items[]" are important for tracing data flow
673
+ // from parent to child components (e.g., surveys[] -> SurveyCard().signature[0].survey)
674
+ const isLocalVariablePath =
675
+ !candidate.schemaPath.includes('()') &&
676
+ !candidate.schemaPath.startsWith('signature[') &&
677
+ !candidate.schemaPath.startsWith('returnValue');
678
+
570
679
  return (
571
680
  validExternalFacingScopeNames.has(baseName) &&
572
681
  (candidate.schemaPath.startsWith('signature[') ||
573
- candidate.schemaPath.startsWith(baseName)) &&
682
+ candidate.schemaPath.startsWith(baseName) ||
683
+ isLocalVariablePath) &&
574
684
  !containsArrayMethod(candidate.schemaPath)
575
685
  );
576
686
  });
687
+
688
+ // If all sourceCandidates were filtered out (e.g., because they belonged to
689
+ // internal functions like useState), look for the highest-order intermediate
690
+ // that belongs to a valid external-facing scope
691
+ if (
692
+ entry.sourceCandidates.length === 0 &&
693
+ Object.keys(entry.intermediatesOrder).length > 0
694
+ ) {
695
+ // Find intermediates that belong to valid external-facing scopes
696
+ const validIntermediates = Object.entries(entry.intermediatesOrder)
697
+ .filter(([pathId]) => {
698
+ const [scopeNodeName, schemaPath] = pathId.split('::');
699
+ if (!scopeNodeName || !schemaPath) return false;
700
+ const baseName = this.pathManager.stripGenerics(scopeNodeName);
701
+ return (
702
+ validExternalFacingScopeNames.has(baseName) &&
703
+ !containsArrayMethod(schemaPath)
704
+ );
705
+ })
706
+ .sort((a, b) => b[1] - a[1]); // Sort by order descending (highest first)
707
+
708
+ if (validIntermediates.length > 0) {
709
+ const [pathId] = validIntermediates[0];
710
+ const [scopeNodeName, schemaPath] = pathId.split('::');
711
+ if (scopeNodeName && schemaPath) {
712
+ entry.sourceCandidates.push({ scopeNodeName, schemaPath });
713
+ }
714
+ }
715
+ }
577
716
  }
578
717
 
579
718
  this.propagateSourceAndUsageEquivalencies(
@@ -661,6 +800,11 @@ export class ScopeDataStructure {
661
800
  return;
662
801
  }
663
802
 
803
+ // PERF: Early exit for paths with repeated function-call signature patterns
804
+ if (this.hasExcessivePatternRepetition(path)) {
805
+ return;
806
+ }
807
+
664
808
  // Update chain metadata for database tracking
665
809
  if (equivalencyValueChain.length > 0) {
666
810
  equivalencyValueChain[equivalencyValueChain.length - 1].addToSchemaId =
@@ -904,8 +1048,8 @@ export class ScopeDataStructure {
904
1048
  equivalencyValueChain?: EquivalencyValueChainItem[],
905
1049
  traceId?: number,
906
1050
  ) {
907
- // DEBUG: Detect infinite loops
908
1051
  addEquivalencyCallCount++;
1052
+
909
1053
  if (addEquivalencyCallCount > 50000) {
910
1054
  console.error('INFINITE LOOP DETECTED in addEquivalency', {
911
1055
  callCount: addEquivalencyCallCount,
@@ -965,12 +1109,35 @@ export class ScopeDataStructure {
965
1109
  }
966
1110
 
967
1111
  if (!equivalentScopeName) {
968
- console.warn('Debug Propagation: missing equivalent scope name', {
969
- path,
970
- equivalentPath,
971
- equivalentScopeName,
972
- scopeNodeName: scopeNode.name,
973
- });
1112
+ console.error(
1113
+ 'CodeYam Error: Missing equivalent scope name - FULL CONTEXT:',
1114
+ JSON.stringify(
1115
+ {
1116
+ path,
1117
+ equivalentPath,
1118
+ equivalentScopeName,
1119
+ scopeNodeName: scopeNode.name,
1120
+ equivalencyReason,
1121
+ tree: scopeNode.tree,
1122
+ equivalencyValueChain: equivalencyValueChain?.map((ev) => ({
1123
+ id: ev.id,
1124
+ source: ev.source,
1125
+ reason: ev.reason,
1126
+ currentPath: ev.currentPath,
1127
+ previousPath: ev.previousPath,
1128
+ })),
1129
+ scopeNodeFunctionCalls: scopeNode.functionCalls?.map((fc) => ({
1130
+ name: fc.name,
1131
+ callSignature: fc.callSignature,
1132
+ callScope: fc.callScope,
1133
+ })),
1134
+ instantiatedVariables: scopeNode.instantiatedVariables,
1135
+ parentInstantiatedVariables: scopeNode.parentInstantiatedVariables,
1136
+ },
1137
+ null,
1138
+ 2,
1139
+ ),
1140
+ );
974
1141
  throw new Error('CodeYam Error: Missing equivalent scope name');
975
1142
  }
976
1143
 
@@ -1128,10 +1295,38 @@ export class ScopeDataStructure {
1128
1295
  const existingFunctionCall =
1129
1296
  this.getExternalFunctionCallsIndex().get(searchKey);
1130
1297
  if (existingFunctionCall) {
1131
- existingFunctionCall.schema = {
1298
+ // Preserve per-call schemas BEFORE merging to enable per-variable mock data.
1299
+ // This is critical for hooks like useFetcher<UserData>() vs useFetcher<ReportData>()
1300
+ // where each call returns different typed data.
1301
+ if (!existingFunctionCall.perCallSignatureSchemas) {
1302
+ // First merge - save the existing call's schema
1303
+ existingFunctionCall.perCallSignatureSchemas = {
1304
+ [existingFunctionCall.callSignature]: {
1305
+ ...existingFunctionCall.schema,
1306
+ },
1307
+ };
1308
+ }
1309
+ // Save the new call's schema before it gets merged
1310
+ existingFunctionCall.perCallSignatureSchemas[
1311
+ functionCallInfo.callSignature
1312
+ ] = { ...functionCallInfo.schema };
1313
+
1314
+ // Merge schemas using selectBestValue to preserve specific types like 'null'
1315
+ // over generic types like 'unknown'. This ensures ref variables detected
1316
+ // earlier (marked as 'null') aren't overwritten by later 'unknown' values.
1317
+ const mergedSchema: Record<string, string> = {
1132
1318
  ...existingFunctionCall.schema,
1133
- ...functionCallInfo.schema,
1134
1319
  };
1320
+ for (const key in functionCallInfo.schema) {
1321
+ const existingValue = existingFunctionCall.schema[key];
1322
+ const newValue = functionCallInfo.schema[key];
1323
+ mergedSchema[key] = selectBestValue(
1324
+ existingValue,
1325
+ newValue,
1326
+ newValue,
1327
+ );
1328
+ }
1329
+ existingFunctionCall.schema = mergedSchema;
1135
1330
 
1136
1331
  existingFunctionCall.equivalencies = {
1137
1332
  ...existingFunctionCall.equivalencies,
@@ -1164,8 +1359,15 @@ export class ScopeDataStructure {
1164
1359
  );
1165
1360
 
1166
1361
  if (isExternal) {
1167
- this.externalFunctionCalls.push(functionCallInfo);
1168
- this.invalidateExternalFunctionCallsIndex();
1362
+ // Check if this function was already filtered out as an internal function
1363
+ // (e.g., useState was filtered in captureCompleteSchema but finalize is trying to re-add it)
1364
+ const strippedName = this.pathManager.stripGenerics(
1365
+ functionCallInfo.name,
1366
+ );
1367
+ if (!this.filteredInternalFunctions.has(strippedName)) {
1368
+ this.externalFunctionCalls.push(functionCallInfo);
1369
+ this.invalidateExternalFunctionCallsIndex();
1370
+ }
1169
1371
  }
1170
1372
  }
1171
1373
  }
@@ -1273,11 +1475,32 @@ export class ScopeDataStructure {
1273
1475
  const equivalentSchemaPath = equivalentSchemaPathMap.get(remainingKey);
1274
1476
 
1275
1477
  if (equivalentSchemaPath) {
1478
+ // Skip propagation when there's a structural mismatch:
1479
+ // - schemaPath ends with [] (array element, represents an object)
1480
+ // - equivalentSchemaPath doesn't end with [] (non-array prop, usually a scalar)
1481
+ // This prevents incorrectly typing array elements as strings when they're
1482
+ // equivalent to scalar props like JSX keys (e.g., workouts[] ↔ Card().key)
1483
+ const schemaPathEndsWithArray = schemaPath.endsWith('[]');
1484
+ const equivalentEndsWithArray = equivalentSchemaPath.endsWith('[]');
1485
+ if (schemaPathEndsWithArray !== equivalentEndsWithArray) {
1486
+ // Don't propagate between array element paths and non-array paths
1487
+ continue;
1488
+ }
1489
+
1276
1490
  const value1 = scopeNode.schema[schemaPath];
1277
1491
  const value2 = equivalentScopeNode.schema[equivalentSchemaPath];
1278
1492
 
1279
1493
  const bestValue = selectBestValue(value1, value2);
1280
1494
 
1495
+ // PERF: Skip paths with repeated function-call signature patterns
1496
+ // to prevent recursive type expansion (e.g., string.localeCompare returns string)
1497
+ if (
1498
+ this.hasExcessivePatternRepetition(schemaPath) ||
1499
+ this.hasExcessivePatternRepetition(equivalentSchemaPath)
1500
+ ) {
1501
+ continue;
1502
+ }
1503
+
1281
1504
  scopeNode.schema[schemaPath] = bestValue;
1282
1505
  equivalentScopeNode.schema[equivalentSchemaPath] = bestValue;
1283
1506
  } else if (
@@ -1291,6 +1514,11 @@ export class ScopeDataStructure {
1291
1514
  ...remainingSchemaPathParts,
1292
1515
  ]);
1293
1516
 
1517
+ // PERF: Skip paths with repeated function-call signature patterns
1518
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
1519
+ continue;
1520
+ }
1521
+
1294
1522
  equivalentScopeNode.schema[newEquivalentPath] =
1295
1523
  scopeNode.schema[schemaPath];
1296
1524
  }
@@ -1381,6 +1609,77 @@ export class ScopeDataStructure {
1381
1609
  return this.pathManager.isValidPath(path);
1382
1610
  }
1383
1611
 
1612
+ /**
1613
+ * Detects if a path contains excessive repetition of the same pattern.
1614
+ *
1615
+ * This prevents exponential blowup when analyzing recursive type structures.
1616
+ * For example, TypeScript AST nodes have `.attributes.properties[]` where each
1617
+ * property is also a node with `.attributes.properties[]`. Without this check,
1618
+ * paths like `signature[0].attributes.properties[].attributes.properties[].attributes.properties[]...`
1619
+ * would be generated exponentially.
1620
+ *
1621
+ * Two detection strategies:
1622
+ * 1. Known patterns: Check RECURSIVE_PATH_PATTERNS for common recursive structures
1623
+ * 2. Generic detection: For longer paths, detect any 2-3 part segment that repeats
1624
+ *
1625
+ * @param path - The schema path to check
1626
+ * @param maxRepetitions - Maximum allowed repetitions of any pattern (default: 2)
1627
+ * @returns true if the path has excessive repetition
1628
+ */
1629
+ private hasExcessivePatternRepetition(
1630
+ path: string,
1631
+ maxRepetitions = 2,
1632
+ ): boolean {
1633
+ // Check known recursive patterns
1634
+ for (const pattern of RECURSIVE_PATH_PATTERNS) {
1635
+ const matches = path.match(pattern);
1636
+ if (matches && matches.length > maxRepetitions) {
1637
+ return true;
1638
+ }
1639
+ }
1640
+
1641
+ // Check for repeated function calls that indicate recursive type expansion.
1642
+ // E.g., localeCompare(b[])...localeCompare(b[]) means string.localeCompare
1643
+ // returns a type that again has localeCompare, causing infinite expansion.
1644
+ // We extract all function call patterns like "funcName(args)" and check if
1645
+ // the same normalized call appears more than once.
1646
+ const funcCallPattern = /(?:^|\.)[^.([]+\([^)]*\)/g;
1647
+ const funcCallMatches = path.match(funcCallPattern);
1648
+ if (funcCallMatches && funcCallMatches.length > 1) {
1649
+ const seen = new Set<string>();
1650
+ for (const match of funcCallMatches) {
1651
+ // Strip leading dot and normalize array indices
1652
+ const normalized = match.replace(/^\./, '').replace(/\[\d+\]/g, '[]');
1653
+ if (seen.has(normalized)) return true;
1654
+ seen.add(normalized);
1655
+ }
1656
+ }
1657
+
1658
+ // For longer paths, detect any repeated multi-part segments we haven't explicitly listed
1659
+ const pathParts = this.splitPath(path);
1660
+ if (pathParts.length <= 6) {
1661
+ return false;
1662
+ }
1663
+
1664
+ // Check for repeated sequences of 2-3 consecutive parts
1665
+ for (let segmentLength = 2; segmentLength <= 3; segmentLength++) {
1666
+ const seen = new Map<string, number>();
1667
+
1668
+ for (let i = 0; i <= pathParts.length - segmentLength; i++) {
1669
+ const segment = pathParts.slice(i, i + segmentLength).join('.');
1670
+ const normalizedSegment = segment.replace(/\[\d+\]/g, '[]');
1671
+ const count = (seen.get(normalizedSegment) || 0) + 1;
1672
+ seen.set(normalizedSegment, count);
1673
+
1674
+ if (count > maxRepetitions) {
1675
+ return true;
1676
+ }
1677
+ }
1678
+ }
1679
+
1680
+ return false;
1681
+ }
1682
+
1384
1683
  private addToTree(pathParts: string[]) {
1385
1684
  this.scopeTreeManager.addPath(pathParts);
1386
1685
  }
@@ -1388,17 +1687,26 @@ export class ScopeDataStructure {
1388
1687
  private setInstantiatedVariables(scopeNode: ScopeNode) {
1389
1688
  let instantiatedVariables = scopeNode.analysis?.instantiatedVariables ?? [];
1390
1689
 
1391
- for (const [path, equivalentPath] of Object.entries(
1690
+ for (const [path, rawEquivalentPath] of Object.entries(
1392
1691
  scopeNode.analysis.isolatedEquivalentVariables ?? {},
1393
1692
  )) {
1394
- if (typeof equivalentPath !== 'string') {
1395
- continue;
1396
- }
1693
+ // Normalize to array for consistent handling (supports both string and string[])
1694
+ const equivalentPaths = Array.isArray(rawEquivalentPath)
1695
+ ? rawEquivalentPath
1696
+ : rawEquivalentPath
1697
+ ? [rawEquivalentPath]
1698
+ : [];
1699
+
1700
+ for (const equivalentPath of equivalentPaths) {
1701
+ if (typeof equivalentPath !== 'string') {
1702
+ continue;
1703
+ }
1397
1704
 
1398
- if (equivalentPath.startsWith('signature[')) {
1399
- const equivalentPathParts = this.splitPath(equivalentPath);
1400
- instantiatedVariables.push(equivalentPathParts[0]);
1401
- instantiatedVariables.push(path);
1705
+ if (equivalentPath.startsWith('signature[')) {
1706
+ const equivalentPathParts = this.splitPath(equivalentPath);
1707
+ instantiatedVariables.push(equivalentPathParts[0]);
1708
+ instantiatedVariables.push(path);
1709
+ }
1402
1710
  }
1403
1711
 
1404
1712
  const duplicateInstantiated = instantiatedVariables.find(
@@ -1411,9 +1719,14 @@ export class ScopeDataStructure {
1411
1719
  }
1412
1720
  }
1413
1721
 
1414
- instantiatedVariables = instantiatedVariables.filter(
1415
- (varName, index, self) => self.indexOf(varName) === index,
1416
- );
1722
+ const instantiatedSeen = new Set<string>();
1723
+ instantiatedVariables = instantiatedVariables.filter((varName) => {
1724
+ if (instantiatedSeen.has(varName)) {
1725
+ return false;
1726
+ }
1727
+ instantiatedSeen.add(varName);
1728
+ return true;
1729
+ });
1417
1730
 
1418
1731
  scopeNode.instantiatedVariables = instantiatedVariables;
1419
1732
 
@@ -1434,13 +1747,19 @@ export class ScopeDataStructure {
1434
1747
  ...parentScopeNode.instantiatedVariables.filter(
1435
1748
  (v) => !v.startsWith('signature[') && !v.startsWith('returnValue'),
1436
1749
  ),
1437
- ].filter(
1438
- (varName, index, self) =>
1439
- !instantiatedVariables.includes(varName) &&
1440
- self.indexOf(varName) === index,
1441
- );
1750
+ ].filter((varName) => !instantiatedSeen.has(varName));
1751
+
1752
+ const parentInstantiatedSeen = new Set<string>();
1753
+ const dedupedParentInstantiatedVariables =
1754
+ parentInstantiatedVariables.filter((varName) => {
1755
+ if (parentInstantiatedSeen.has(varName)) {
1756
+ return false;
1757
+ }
1758
+ parentInstantiatedSeen.add(varName);
1759
+ return true;
1760
+ });
1442
1761
 
1443
- scopeNode.parentInstantiatedVariables = parentInstantiatedVariables;
1762
+ scopeNode.parentInstantiatedVariables = dedupedParentInstantiatedVariables;
1444
1763
  }
1445
1764
 
1446
1765
  private trackFunctionCalls(scopeNode: ScopeNode) {
@@ -1449,197 +1768,205 @@ export class ScopeDataStructure {
1449
1768
  }
1450
1769
 
1451
1770
  private determineEquivalenciesAndBuildSchema(scopeNode: ScopeNode) {
1771
+ if (!scopeNode.analysis) {
1772
+ return;
1773
+ }
1774
+
1452
1775
  const { isolatedStructure, isolatedEquivalentVariables } =
1453
1776
  scopeNode.analysis;
1454
1777
 
1455
- // DEBUG: Log all equivalencies related to useFetcher
1456
- if (
1457
- Object.keys(isolatedEquivalentVariables || {}).some(
1458
- (k) => k.includes('Fetcher') || k.includes('fetcher'),
1459
- )
1460
- ) {
1461
- console.log(
1462
- 'CodeYam DEBUG determineEquivalenciesAndBuildSchema:',
1463
- JSON.stringify(
1464
- {
1465
- scopeNodeName: scopeNode.name,
1466
- fetcherEquivalencies: Object.entries(
1467
- isolatedEquivalentVariables || {},
1468
- )
1469
- .filter(
1470
- ([k, v]) =>
1471
- k.includes('Fetcher') ||
1472
- k.includes('fetcher') ||
1473
- String(v).includes('Fetcher') ||
1474
- String(v).includes('fetcher'),
1475
- )
1476
- .reduce(
1477
- (acc, [k, v]) => {
1478
- acc[k] = v;
1479
- return acc;
1480
- },
1481
- {} as Record<string, string>,
1482
- ),
1483
- },
1484
- null,
1485
- 2,
1486
- ),
1487
- );
1488
- }
1778
+ // Flatten isolatedEquivalentVariables values for allPaths (handles both string and string[])
1779
+ const flattenedEquivValues = Object.values(
1780
+ isolatedEquivalentVariables || {},
1781
+ ).flatMap((v) => (Array.isArray(v) ? v : [v]));
1489
1782
 
1490
1783
  const allPaths = Array.from(
1491
1784
  new Set([
1492
1785
  ...Object.keys(isolatedStructure || {}),
1493
1786
  ...Object.keys(isolatedEquivalentVariables || {}),
1494
- ...Object.values(isolatedEquivalentVariables || {}),
1787
+ ...flattenedEquivValues,
1495
1788
  ]),
1496
1789
  );
1497
1790
 
1498
1791
  for (let path in isolatedEquivalentVariables) {
1499
- let equivalentValue = isolatedEquivalentVariables?.[path];
1500
-
1501
- if (equivalentValue && this.isValidPath(equivalentValue)) {
1502
- path = cleanPath(path.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1503
- equivalentValue = cleanPath(
1504
- equivalentValue.replace(/::cyDuplicateKey\d+::/g, ''),
1505
- allPaths,
1506
- );
1507
-
1508
- this.addEquivalency(
1509
- path,
1510
- equivalentValue,
1511
- scopeNode.name,
1512
- scopeNode,
1513
- 'original equivalency',
1514
- );
1792
+ const rawEquivalentValue = isolatedEquivalentVariables?.[path];
1793
+ // Normalize to array for consistent handling
1794
+ const equivalentValues = Array.isArray(rawEquivalentValue)
1795
+ ? rawEquivalentValue
1796
+ : [rawEquivalentValue];
1797
+
1798
+ for (let equivalentValue of equivalentValues) {
1799
+ if (equivalentValue && this.isValidPath(equivalentValue)) {
1800
+ // IMPORTANT: DO NOT strip ::cyDuplicateKey:: markers from equivalencies.
1801
+ // These markers are critical for distinguishing variable reassignments.
1802
+ // For example, with:
1803
+ // let fetcher = useFetcher<ConfigData>();
1804
+ // const configData = fetcher.data?.data;
1805
+ // fetcher = useFetcher<SettingsData>();
1806
+ // const settingsData = fetcher.data?.data;
1807
+ //
1808
+ // mergeStatements creates:
1809
+ // fetcher → useFetcher<ConfigData>()...
1810
+ // fetcher::cyDuplicateKey1:: → useFetcher<SettingsData>()...
1811
+ // configData → fetcher.data.data
1812
+ // settingsData → fetcher::cyDuplicateKey1::.data.data
1813
+ //
1814
+ // If we strip ::cyDuplicateKey::, settingsData would incorrectly trace
1815
+ // to useFetcher<ConfigData>() instead of useFetcher<SettingsData>().
1816
+ path = cleanPath(path, allPaths);
1817
+ equivalentValue = cleanPath(equivalentValue, allPaths);
1818
+
1819
+ this.addEquivalency(
1820
+ path,
1821
+ equivalentValue,
1822
+ scopeNode.name,
1823
+ scopeNode,
1824
+ 'original equivalency',
1825
+ );
1515
1826
 
1516
- // Propagate equivalencies involving parent-scope variables to those parent scopes.
1517
- // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1518
- // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1519
- // visible when tracing from the parent scope.
1520
- const rootVariable = this.extractRootVariable(path);
1521
- const equivalentRootVariable =
1522
- this.extractRootVariable(equivalentValue);
1523
-
1524
- // Skip propagation for self-referential reassignment patterns like:
1525
- // x = x.method().functionCallReturnValue
1526
- // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1527
- // These create circular references since both sides reference the same variable.
1528
- //
1529
- // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1530
- // where the path has additional segments beyond the root variable.
1531
- const pathIsJustRootVariable = path === rootVariable;
1532
- const isSelfReferentialReassignment =
1533
- pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1827
+ // Propagate equivalencies involving parent-scope variables to those parent scopes.
1828
+ // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1829
+ // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1830
+ // visible when tracing from the parent scope.
1831
+ const rootVariable = this.extractRootVariable(path);
1832
+ const equivalentRootVariable =
1833
+ this.extractRootVariable(equivalentValue);
1834
+
1835
+ // Skip propagation for self-referential reassignment patterns like:
1836
+ // x = x.method().functionCallReturnValue
1837
+ // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1838
+ // These create circular references since both sides reference the same variable.
1839
+ //
1840
+ // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1841
+ // where the path has additional segments beyond the root variable.
1842
+ const pathIsJustRootVariable = path === rootVariable;
1843
+ const isSelfReferentialReassignment =
1844
+ pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1534
1845
 
1535
- if (
1536
- rootVariable &&
1537
- !isSelfReferentialReassignment &&
1538
- scopeNode.parentInstantiatedVariables?.includes(rootVariable)
1539
- ) {
1540
- // Find the parent scope where this variable is defined
1541
- for (const parentScopeName of scopeNode.tree || []) {
1542
- const parentScope = this.scopeNodes[parentScopeName];
1543
- if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1544
- // Add the equivalency to the parent scope as well
1545
- this.addEquivalency(
1546
- path,
1547
- equivalentValue,
1548
- scopeNode.name, // The equivalent path's scope remains the child scope
1549
- parentScope, // But store it in the parent scope's equivalencies
1550
- 'propagated parent-variable equivalency',
1551
- );
1552
- break;
1846
+ if (
1847
+ rootVariable &&
1848
+ !isSelfReferentialReassignment &&
1849
+ scopeNode.parentInstantiatedVariables?.includes(rootVariable)
1850
+ ) {
1851
+ // Find the parent scope where this variable is defined
1852
+ for (const parentScopeName of scopeNode.tree || []) {
1853
+ const parentScope = this.scopeNodes[parentScopeName];
1854
+ if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1855
+ // Add the equivalency to the parent scope as well
1856
+ this.addEquivalency(
1857
+ path,
1858
+ equivalentValue,
1859
+ scopeNode.name, // The equivalent path's scope remains the child scope
1860
+ parentScope, // But store it in the parent scope's equivalencies
1861
+ 'propagated parent-variable equivalency',
1862
+ );
1863
+ break;
1864
+ }
1553
1865
  }
1554
1866
  }
1555
- }
1556
1867
 
1557
- // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1558
- // that has sub-properties defined in the isolatedEquivalentVariables.
1559
- // This handles cases like: dataItem={{ structure: completeDataStructure }}
1560
- // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1561
- // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1562
- const isSimpleVariable =
1563
- !equivalentValue.startsWith('signature[') &&
1564
- !equivalentValue.includes('functionCallReturnValue') &&
1565
- !equivalentValue.includes('.') &&
1566
- !equivalentValue.includes('[');
1567
-
1568
- if (isSimpleVariable) {
1569
- // Look in current scope and all parent scopes for sub-properties
1570
- const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1571
- for (const scopeName of scopesToCheck) {
1572
- const checkScope = this.scopeNodes[scopeName];
1573
- if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1574
-
1575
- for (const [subPath, subValue] of Object.entries(
1576
- checkScope.analysis.isolatedEquivalentVariables,
1577
- )) {
1578
- // Check if this is a sub-property of the equivalentValue variable
1579
- // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1580
- const matchesDot = subPath.startsWith(equivalentValue + '.');
1581
- const matchesBracket = subPath.startsWith(equivalentValue + '[');
1582
- if (matchesDot || matchesBracket) {
1583
- const subPropertyPath = subPath.substring(
1584
- equivalentValue.length,
1585
- );
1586
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1587
- const newEquivalentValue = cleanPath(
1588
- (subValue as string).replace(/::cyDuplicateKey\d+::/g, ''),
1589
- allPaths,
1868
+ // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1869
+ // that has sub-properties defined in the isolatedEquivalentVariables.
1870
+ // This handles cases like: dataItem={{ structure: completeDataStructure }}
1871
+ // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1872
+ // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1873
+ const isSimpleVariable =
1874
+ !equivalentValue.startsWith('signature[') &&
1875
+ !equivalentValue.includes('functionCallReturnValue') &&
1876
+ !equivalentValue.includes('.') &&
1877
+ !equivalentValue.includes('[');
1878
+
1879
+ if (isSimpleVariable) {
1880
+ // Look in current scope and all parent scopes for sub-properties
1881
+ const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1882
+ for (const scopeName of scopesToCheck) {
1883
+ const checkScope = this.scopeNodes[scopeName];
1884
+ if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1885
+
1886
+ for (const [subPath, rawSubValue] of Object.entries(
1887
+ checkScope.analysis.isolatedEquivalentVariables,
1888
+ )) {
1889
+ // Normalize to array for consistent handling
1890
+ const subValues = Array.isArray(rawSubValue)
1891
+ ? rawSubValue
1892
+ : rawSubValue
1893
+ ? [rawSubValue]
1894
+ : [];
1895
+
1896
+ // Check if this is a sub-property of the equivalentValue variable
1897
+ // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1898
+ const matchesDot = subPath.startsWith(equivalentValue + '.');
1899
+ const matchesBracket = subPath.startsWith(
1900
+ equivalentValue + '[',
1590
1901
  );
1591
-
1592
- if (
1593
- newEquivalentValue &&
1594
- this.isValidPath(newEquivalentValue)
1595
- ) {
1596
- this.addEquivalency(
1597
- newPath,
1598
- newEquivalentValue,
1599
- checkScope.name, // Use the scope where the sub-property was found
1600
- scopeNode,
1601
- 'propagated sub-property equivalency',
1902
+ if (matchesDot || matchesBracket) {
1903
+ const subPropertyPath = subPath.substring(
1904
+ equivalentValue.length,
1602
1905
  );
1906
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
1907
+
1908
+ for (const subValue of subValues) {
1909
+ if (typeof subValue !== 'string') continue;
1910
+ const newEquivalentValue = cleanPath(
1911
+ subValue.replace(/::cyDuplicateKey\d+::/g, ''),
1912
+ allPaths,
1913
+ );
1914
+
1915
+ if (
1916
+ newEquivalentValue &&
1917
+ this.isValidPath(newEquivalentValue)
1918
+ ) {
1919
+ this.addEquivalency(
1920
+ newPath,
1921
+ newEquivalentValue,
1922
+ checkScope.name, // Use the scope where the sub-property was found
1923
+ scopeNode,
1924
+ 'propagated sub-property equivalency',
1925
+ );
1926
+ }
1927
+ }
1603
1928
  }
1604
- }
1605
1929
 
1606
- // Also check if equivalentValue itself maps to a functionCallReturnValue
1607
- // e.g., result = useMemo(...).functionCallReturnValue
1608
- if (
1609
- subPath === equivalentValue &&
1610
- typeof subValue === 'string' &&
1611
- subValue.endsWith('.functionCallReturnValue')
1612
- ) {
1613
- this.propagateFunctionCallReturnSubProperties(
1614
- path,
1615
- subValue,
1616
- scopeNode,
1617
- allPaths,
1618
- );
1930
+ // Also check if equivalentValue itself maps to a functionCallReturnValue
1931
+ // e.g., result = useMemo(...).functionCallReturnValue
1932
+ for (const subValue of subValues) {
1933
+ if (
1934
+ subPath === equivalentValue &&
1935
+ typeof subValue === 'string' &&
1936
+ subValue.endsWith('.functionCallReturnValue')
1937
+ ) {
1938
+ this.propagateFunctionCallReturnSubProperties(
1939
+ path,
1940
+ subValue,
1941
+ scopeNode,
1942
+ allPaths,
1943
+ );
1944
+ }
1945
+ }
1619
1946
  }
1620
1947
  }
1621
1948
  }
1622
- }
1623
1949
 
1624
- // Handle function call return values by propagating returnValue.* sub-properties
1625
- // from the callback scope to the usage path
1626
- if (equivalentValue.endsWith('.functionCallReturnValue')) {
1627
- this.propagateFunctionCallReturnSubProperties(
1628
- path,
1629
- equivalentValue,
1630
- scopeNode,
1631
- allPaths,
1632
- );
1950
+ // Handle function call return values by propagating returnValue.* sub-properties
1951
+ // from the callback scope to the usage path
1952
+ if (equivalentValue.endsWith('.functionCallReturnValue')) {
1953
+ this.propagateFunctionCallReturnSubProperties(
1954
+ path,
1955
+ equivalentValue,
1956
+ scopeNode,
1957
+ allPaths,
1958
+ );
1633
1959
 
1634
- // Track which variable receives the return value of each function call
1635
- // This enables generating separate mock data for each call site
1636
- this.trackReceivingVariable(path, equivalentValue);
1637
- }
1960
+ // Track which variable receives the return value of each function call
1961
+ // This enables generating separate mock data for each call site
1962
+ this.trackReceivingVariable(path, equivalentValue);
1963
+ }
1638
1964
 
1639
- // Also track variables that receive destructured properties from function call return values
1640
- // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1641
- if (equivalentValue.includes('.functionCallReturnValue.')) {
1642
- this.trackReceivingVariable(path, equivalentValue);
1965
+ // Also track variables that receive destructured properties from function call return values
1966
+ // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1967
+ if (equivalentValue.includes('.functionCallReturnValue.')) {
1968
+ this.trackReceivingVariable(path, equivalentValue);
1969
+ }
1643
1970
  }
1644
1971
  }
1645
1972
  }
@@ -1649,7 +1976,7 @@ export class ScopeDataStructure {
1649
1976
  this.batchProcessor = new BatchSchemaProcessor();
1650
1977
  this.batchQueuedSet = new Set();
1651
1978
 
1652
- for (const key of Array.from(allPaths)) {
1979
+ for (const key of allPaths) {
1653
1980
  let value = isolatedStructure[key] ?? 'unknown';
1654
1981
 
1655
1982
  if (['null', 'undefined'].includes(value)) {
@@ -1690,7 +2017,19 @@ export class ScopeDataStructure {
1690
2017
  private processBatchQueue(): void {
1691
2018
  if (!this.batchProcessor) return;
1692
2019
 
2020
+ let iterations = 0;
2021
+
1693
2022
  while (this.batchProcessor.hasWork()) {
2023
+ iterations++;
2024
+
2025
+ // Safety: detect potential infinite loops
2026
+ if (iterations > 100000) {
2027
+ console.error(
2028
+ `[ScopeDataStructure] processBatchQueue exceeded 100k iterations, possible infinite loop!`,
2029
+ );
2030
+ break;
2031
+ }
2032
+
1694
2033
  const item = this.batchProcessor.getNextWork();
1695
2034
  if (!item) break;
1696
2035
 
@@ -1748,26 +2087,6 @@ export class ScopeDataStructure {
1748
2087
  const functionCallInfo =
1749
2088
  this.getExternalFunctionCallsIndex().get(searchKey);
1750
2089
 
1751
- // DEBUG: Track useFetcher calls
1752
- if (searchKey === 'useFetcher' || callSignature.includes('useFetcher')) {
1753
- console.log(
1754
- 'CodeYam DEBUG trackReceivingVariable:',
1755
- JSON.stringify(
1756
- {
1757
- receivingVariable,
1758
- equivalentValue,
1759
- callSignature,
1760
- searchKey,
1761
- foundFunctionCallInfo: !!functionCallInfo,
1762
- existingRecvVars: functionCallInfo?.receivingVariableNames,
1763
- existingCallSigToVar: functionCallInfo?.callSignatureToVariable,
1764
- },
1765
- null,
1766
- 2,
1767
- ),
1768
- );
1769
- }
1770
-
1771
2090
  if (!functionCallInfo) {
1772
2091
  return;
1773
2092
  }
@@ -1828,9 +2147,18 @@ export class ScopeDataStructure {
1828
2147
  const checkScope = this.scopeNodes[scopeName];
1829
2148
  if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1830
2149
 
1831
- const functionRef =
2150
+ const rawFunctionRef =
1832
2151
  checkScope.analysis.isolatedEquivalentVariables[functionName];
1833
- if (typeof functionRef === 'string' && functionRef.endsWith('F')) {
2152
+ // Normalize to array and find first string ending with 'F'
2153
+ const functionRefs = Array.isArray(rawFunctionRef)
2154
+ ? rawFunctionRef
2155
+ : rawFunctionRef
2156
+ ? [rawFunctionRef]
2157
+ : [];
2158
+ const functionRef = functionRefs.find(
2159
+ (r) => typeof r === 'string' && r.endsWith('F'),
2160
+ );
2161
+ if (typeof functionRef === 'string') {
1834
2162
  callbackScopeName = functionRef.slice(0, -1);
1835
2163
  break;
1836
2164
  }
@@ -1858,19 +2186,24 @@ export class ScopeDataStructure {
1858
2186
 
1859
2187
  const isolatedVars = callbackScope.analysis.isolatedEquivalentVariables;
1860
2188
 
2189
+ // Get the first returnValue equivalency (normalize array to single value for these checks)
2190
+ const rawReturnValue = isolatedVars.returnValue;
2191
+ const firstReturnValue = Array.isArray(rawReturnValue)
2192
+ ? rawReturnValue[0]
2193
+ : rawReturnValue;
2194
+
1861
2195
  // First, check if returnValue is an alias to another variable (e.g., returnValue = intermediate)
1862
2196
  // If so, we need to look for that variable's sub-properties too
1863
2197
  const returnValueAlias =
1864
- typeof isolatedVars.returnValue === 'string' &&
1865
- !isolatedVars.returnValue.includes('.')
1866
- ? isolatedVars.returnValue
2198
+ typeof firstReturnValue === 'string' && !firstReturnValue.includes('.')
2199
+ ? firstReturnValue
1867
2200
  : undefined;
1868
2201
 
1869
2202
  // Pattern 3: Object.keys(X).reduce() - the reduce result has the same sub-properties as X
1870
2203
  // When returnValue = "Object.keys(source).reduce(...).functionCallReturnValue", look for source.* sub-properties
1871
2204
  let reduceSourceVar: string | undefined;
1872
- if (typeof isolatedVars.returnValue === 'string') {
1873
- const reduceMatch = isolatedVars.returnValue.match(
2205
+ if (typeof firstReturnValue === 'string') {
2206
+ const reduceMatch = firstReturnValue.match(
1874
2207
  /^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/,
1875
2208
  );
1876
2209
  if (reduceMatch) {
@@ -1878,7 +2211,14 @@ export class ScopeDataStructure {
1878
2211
  }
1879
2212
  }
1880
2213
 
1881
- for (const [subPath, subValue] of Object.entries(isolatedVars)) {
2214
+ for (const [subPath, rawSubValue] of Object.entries(isolatedVars)) {
2215
+ // Normalize to array for consistent handling
2216
+ const subValues = Array.isArray(rawSubValue)
2217
+ ? rawSubValue
2218
+ : rawSubValue
2219
+ ? [rawSubValue]
2220
+ : [];
2221
+
1882
2222
  // Check for direct returnValue.* sub-properties
1883
2223
  const isReturnValueSub =
1884
2224
  subPath.startsWith('returnValue.') ||
@@ -1896,57 +2236,59 @@ export class ScopeDataStructure {
1896
2236
  (subPath.startsWith(reduceSourceVar + '.') ||
1897
2237
  subPath.startsWith(reduceSourceVar + '['));
1898
2238
 
1899
- if (
1900
- typeof subValue !== 'string' ||
1901
- (!isReturnValueSub && !isAliasSub && !isReduceSourceSub)
1902
- )
1903
- continue;
1904
-
1905
- // Convert alias/reduceSource paths to returnValue paths
1906
- let effectiveSubPath = subPath;
1907
- if (isAliasSub && !isReturnValueSub) {
1908
- // Replace the alias prefix with returnValue
1909
- effectiveSubPath =
1910
- 'returnValue' + subPath.substring(returnValueAlias!.length);
1911
- } else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
1912
- // Replace the reduce source prefix with returnValue
1913
- effectiveSubPath =
1914
- 'returnValue' + subPath.substring(reduceSourceVar!.length);
1915
- }
1916
- const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
1917
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1918
- let newEquivalentValue = cleanPath(
1919
- subValue.replace(/::cyDuplicateKey\d+::/g, ''),
1920
- allPaths,
1921
- );
2239
+ if (!isReturnValueSub && !isAliasSub && !isReduceSourceSub) continue;
2240
+
2241
+ for (const subValue of subValues) {
2242
+ if (typeof subValue !== 'string') continue;
2243
+
2244
+ // Convert alias/reduceSource paths to returnValue paths
2245
+ let effectiveSubPath = subPath;
2246
+ if (isAliasSub && !isReturnValueSub) {
2247
+ // Replace the alias prefix with returnValue
2248
+ effectiveSubPath =
2249
+ 'returnValue' + subPath.substring(returnValueAlias!.length);
2250
+ } else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
2251
+ // Replace the reduce source prefix with returnValue
2252
+ effectiveSubPath =
2253
+ 'returnValue' + subPath.substring(reduceSourceVar!.length);
2254
+ }
2255
+ const subPropertyPath = effectiveSubPath.substring(
2256
+ 'returnValue'.length,
2257
+ );
2258
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
2259
+ let newEquivalentValue = cleanPath(
2260
+ subValue.replace(/::cyDuplicateKey\d+::/g, ''),
2261
+ allPaths,
2262
+ );
1922
2263
 
1923
- // Resolve variable references through parent scope equivalencies
1924
- const resolved = this.resolveVariableThroughParentScopes(
1925
- newEquivalentValue,
1926
- callbackScope,
1927
- allPaths,
1928
- );
1929
- newEquivalentValue = resolved.resolvedPath;
1930
- const equivalentScopeName = resolved.scopeName;
2264
+ // Resolve variable references through parent scope equivalencies
2265
+ const resolved = this.resolveVariableThroughParentScopes(
2266
+ newEquivalentValue,
2267
+ callbackScope,
2268
+ allPaths,
2269
+ );
2270
+ newEquivalentValue = resolved.resolvedPath;
2271
+ const equivalentScopeName = resolved.scopeName;
1931
2272
 
1932
- if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
1933
- continue;
2273
+ if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
2274
+ continue;
1934
2275
 
1935
- this.addEquivalency(
1936
- newPath,
1937
- newEquivalentValue,
1938
- equivalentScopeName,
1939
- scopeNode,
1940
- 'propagated function call return sub-property equivalency',
1941
- );
2276
+ this.addEquivalency(
2277
+ newPath,
2278
+ newEquivalentValue,
2279
+ equivalentScopeName,
2280
+ scopeNode,
2281
+ 'propagated function call return sub-property equivalency',
2282
+ );
1942
2283
 
1943
- // Ensure the database entry has the usage path
1944
- this.addUsageToEquivalencyDatabaseEntry(
1945
- newPath,
1946
- newEquivalentValue,
1947
- equivalentScopeName,
1948
- scopeNode.name,
1949
- );
2284
+ // Ensure the database entry has the usage path
2285
+ this.addUsageToEquivalencyDatabaseEntry(
2286
+ newPath,
2287
+ newEquivalentValue,
2288
+ equivalentScopeName,
2289
+ scopeNode.name,
2290
+ );
2291
+ }
1950
2292
  }
1951
2293
  }
1952
2294
 
@@ -1986,8 +2328,15 @@ export class ScopeDataStructure {
1986
2328
  const parentScope = this.scopeNodes[parentScopeName];
1987
2329
  if (!parentScope?.analysis?.isolatedEquivalentVariables) continue;
1988
2330
 
1989
- const rootEquiv =
2331
+ const rawRootEquiv =
1990
2332
  parentScope.analysis.isolatedEquivalentVariables[rootVar];
2333
+ // Normalize to array and use first string value
2334
+ const rootEquivs = Array.isArray(rawRootEquiv)
2335
+ ? rawRootEquiv
2336
+ : rawRootEquiv
2337
+ ? [rawRootEquiv]
2338
+ : [];
2339
+ const rootEquiv = rootEquivs.find((r) => typeof r === 'string');
1991
2340
  if (typeof rootEquiv === 'string') {
1992
2341
  return {
1993
2342
  resolvedPath: cleanPath(rootEquiv + restOfPath, allPaths),
@@ -2262,11 +2611,27 @@ export class ScopeDataStructure {
2262
2611
  relevantSubPathParts.every((part, i) => part === schemaPathParts[i]) &&
2263
2612
  equivalentValue.scopeNodeName === scopeNode.name
2264
2613
  ) {
2614
+ // DEBUG
2265
2615
  continue;
2266
2616
  }
2267
2617
 
2268
2618
  const newEquivalentPath = this.joinPathParts([schemaPath, remainingPath]);
2269
2619
 
2620
+ // PERF: Detect repeated patterns in paths to prevent exponential blowup
2621
+ // Paths like `signature[0].attributes.properties[].attributes.properties[]...`
2622
+ // indicate recursive type structures that cause exponential schema explosion
2623
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
2624
+ if (traceId && debugLevel > 0) {
2625
+ console.info(
2626
+ 'Debug: skipping path with excessive pattern repetition',
2627
+ {
2628
+ path: newEquivalentPath,
2629
+ },
2630
+ );
2631
+ }
2632
+ continue;
2633
+ }
2634
+
2270
2635
  if (!equivalentScopeNode) {
2271
2636
  if (traceId) {
2272
2637
  console.info('Debug Propagation: missing equivalent scope info', {
@@ -2433,6 +2798,8 @@ export class ScopeDataStructure {
2433
2798
  usageEquivalency.scopeNodeName,
2434
2799
  ) as ScopeNode;
2435
2800
 
2801
+ if (!usageScopeNode) continue;
2802
+
2436
2803
  // Guard against infinite recursion by tracking which paths we've already
2437
2804
  // added from addComplexSourcePathVariables
2438
2805
  if (
@@ -2512,6 +2879,8 @@ export class ScopeDataStructure {
2512
2879
  usageEquivalency.scopeNodeName,
2513
2880
  ) as ScopeNode;
2514
2881
 
2882
+ if (!usageScopeNode) continue;
2883
+
2515
2884
  // This is put in place to avoid propagating array functions like 'filter' through complex equivalencies
2516
2885
  // but may cause problems if the funtion call is not on a known object (e.g. string or array)
2517
2886
  if (
@@ -2638,21 +3007,116 @@ export class ScopeDataStructure {
2638
3007
  this.intermediatesOrderIndex.set(pathId, databaseEntry);
2639
3008
 
2640
3009
  if (intermediateIndex === 0) {
2641
- const isValidSourceCandidate =
3010
+ let isValidSourceCandidate =
2642
3011
  pathInfo.schemaPath.startsWith('signature[') ||
2643
3012
  pathInfo.schemaPath.includes('functionCallReturnValue');
2644
- if (isValidSourceCandidate) {
2645
- databaseEntry.sourceCandidates.push(pathInfo);
2646
- }
2647
- } else {
2648
- const existingSourceCandidateIndex =
2649
- databaseEntry.sourceCandidates.findIndex(
2650
- (sc) =>
2651
- sc.scopeNodeName === pathInfo.scopeNodeName &&
2652
- sc.schemaPath === pathInfo.schemaPath,
2653
- );
2654
- if (existingSourceCandidateIndex > -1) {
2655
- databaseEntry.sourceCandidates.splice(
3013
+
3014
+ // Check if path STARTS with a spread pattern like [...var]
3015
+ // This handles cases like [...files][][0] or [...files].sort(...).functionCallReturnValue[][0]
3016
+ // where the spread source variable needs to be resolved to a signature path.
3017
+ // We do this REGARDLESS of isValidSourceCandidate because even paths containing
3018
+ // functionCallReturnValue may need spread resolution to trace back to the signature.
3019
+ const spreadMatch = pathInfo.schemaPath.match(/^\[\.\.\.(\w+)\]/);
3020
+ if (spreadMatch) {
3021
+ const spreadVar = spreadMatch[1];
3022
+ const spreadPattern = spreadMatch[0]; // The full [...var] match
3023
+ const scopeNode = this.scopeNodes[pathInfo.scopeNodeName];
3024
+
3025
+ if (scopeNode?.equivalencies) {
3026
+ // Follow the equivalency chain to find a signature path
3027
+ // e.g., files (cyScope1) → files (root) → signature[0].files
3028
+ const resolveToSignature = (
3029
+ varName: string,
3030
+ currentScopeName: string,
3031
+ visited: Set<string>,
3032
+ ): { schemaPath: string; scopeNodeName: string } | null => {
3033
+ const visitKey = `${currentScopeName}::${varName}`;
3034
+ if (visited.has(visitKey)) return null;
3035
+ visited.add(visitKey);
3036
+
3037
+ const currentScope = this.scopeNodes[currentScopeName];
3038
+ if (!currentScope?.equivalencies) return null;
3039
+
3040
+ const varEquivs = currentScope.equivalencies[varName];
3041
+ if (!varEquivs) return null;
3042
+
3043
+ // First check if any equivalency directly points to a signature path
3044
+ const signatureEquiv = varEquivs.find((eq) =>
3045
+ eq.schemaPath.startsWith('signature['),
3046
+ );
3047
+ if (signatureEquiv) {
3048
+ return signatureEquiv;
3049
+ }
3050
+
3051
+ // Otherwise, follow the chain to other scopes
3052
+ for (const equiv of varEquivs) {
3053
+ // If the equivalency points to the same variable in a different scope,
3054
+ // follow the chain
3055
+ if (
3056
+ equiv.schemaPath === varName &&
3057
+ equiv.scopeNodeName !== currentScopeName
3058
+ ) {
3059
+ const result = resolveToSignature(
3060
+ varName,
3061
+ equiv.scopeNodeName,
3062
+ visited,
3063
+ );
3064
+ if (result) return result;
3065
+ }
3066
+ }
3067
+
3068
+ return null;
3069
+ };
3070
+
3071
+ const signatureEquiv = resolveToSignature(
3072
+ spreadVar,
3073
+ pathInfo.scopeNodeName,
3074
+ new Set(),
3075
+ );
3076
+ if (signatureEquiv) {
3077
+ // Replace ONLY the [...var] part with the resolved signature path
3078
+ // This preserves any suffix like .sort(...).functionCallReturnValue[][0]
3079
+ const resolvedPath = pathInfo.schemaPath.replace(
3080
+ spreadPattern,
3081
+ signatureEquiv.schemaPath,
3082
+ );
3083
+ // Add the resolved path as a source candidate
3084
+ if (
3085
+ !databaseEntry.sourceCandidates.some(
3086
+ (sc) =>
3087
+ sc.schemaPath === resolvedPath &&
3088
+ sc.scopeNodeName === pathInfo.scopeNodeName,
3089
+ )
3090
+ ) {
3091
+ databaseEntry.sourceCandidates.push({
3092
+ scopeNodeName: pathInfo.scopeNodeName,
3093
+ schemaPath: resolvedPath,
3094
+ });
3095
+ }
3096
+ isValidSourceCandidate = true;
3097
+ }
3098
+ }
3099
+ }
3100
+
3101
+ if (
3102
+ isValidSourceCandidate &&
3103
+ !databaseEntry.sourceCandidates.some(
3104
+ (sc) =>
3105
+ sc.schemaPath === pathInfo.schemaPath &&
3106
+ sc.scopeNodeName === pathInfo.scopeNodeName,
3107
+ )
3108
+ ) {
3109
+ databaseEntry.sourceCandidates.push(pathInfo);
3110
+ }
3111
+ } else {
3112
+ const existingSourceCandidateIndex =
3113
+ databaseEntry.sourceCandidates.findIndex(
3114
+ (sc) =>
3115
+ sc.scopeNodeName === pathInfo.scopeNodeName &&
3116
+ sc.schemaPath === pathInfo.schemaPath,
3117
+ );
3118
+ if (existingSourceCandidateIndex > -1) {
3119
+ databaseEntry.sourceCandidates.splice(
2656
3120
  existingSourceCandidateIndex,
2657
3121
  1,
2658
3122
  );
@@ -2869,6 +3333,14 @@ export class ScopeDataStructure {
2869
3333
  }
2870
3334
  }
2871
3335
 
3336
+ // Ensure parameter-to-signature equivalencies are fully propagated.
3337
+ // When a parameter variable (e.g., `node`) is equivalenced to `signature[N]`,
3338
+ // all sub-paths of that variable should also appear under `signature[N]`.
3339
+ // This handles cases where the sub-path was added to the schema via a propagation
3340
+ // chain that already included the variable↔signature equivalency, causing the
3341
+ // cycle detection to prevent the reverse mapping.
3342
+ this.propagateParameterToSignaturePaths(scopeNode);
3343
+
2872
3344
  fillInSchemaGapsAndUnknowns(scopeNode, fillInUnknowns);
2873
3345
 
2874
3346
  if (final) {
@@ -2883,6 +3355,97 @@ export class ScopeDataStructure {
2883
3355
  }
2884
3356
  }
2885
3357
 
3358
+ /**
3359
+ * For each equivalency where a simple variable maps to signature[N],
3360
+ * ensure all sub-paths of that variable are reflected under signature[N].
3361
+ */
3362
+ private propagateParameterToSignaturePaths(scopeNode: ScopeNode) {
3363
+ // Helper: check if a type is a concrete scalar that cannot have sub-properties.
3364
+ const SCALAR_TYPES = new Set([
3365
+ 'string',
3366
+ 'number',
3367
+ 'boolean',
3368
+ 'bigint',
3369
+ 'symbol',
3370
+ 'void',
3371
+ 'never',
3372
+ ]);
3373
+ const isDefinitelyScalar = (type: string): boolean => {
3374
+ const parts = type.split('|').map((s) => s.trim());
3375
+ const base = parts.filter((s) => s !== 'undefined' && s !== 'null');
3376
+ return base.length > 0 && base.every((b) => SCALAR_TYPES.has(b));
3377
+ };
3378
+
3379
+ // Find variable → signature[N] equivalencies
3380
+ for (const [varName, equivalencies] of Object.entries(
3381
+ scopeNode.equivalencies,
3382
+ )) {
3383
+ // Only process simple variable names (no dots, brackets, or parens)
3384
+ if (
3385
+ varName.includes('.') ||
3386
+ varName.includes('[') ||
3387
+ varName.includes('(')
3388
+ ) {
3389
+ continue;
3390
+ }
3391
+
3392
+ for (const equiv of equivalencies) {
3393
+ if (
3394
+ equiv.scopeNodeName === scopeNode.name &&
3395
+ equiv.schemaPath.startsWith('signature[')
3396
+ ) {
3397
+ const signaturePath = equiv.schemaPath;
3398
+ const varPrefix = varName + '.';
3399
+ const varBracketPrefix = varName + '[';
3400
+
3401
+ // Find all schema keys starting with the variable
3402
+ for (const key in scopeNode.schema) {
3403
+ if (key.startsWith(varPrefix) || key.startsWith(varBracketPrefix)) {
3404
+ const suffix = key.slice(varName.length);
3405
+ const sigKey = signaturePath + suffix;
3406
+
3407
+ // Only add if the signature path doesn't already exist
3408
+ if (!scopeNode.schema[sigKey]) {
3409
+ // Check if this path represents variable conflation:
3410
+ // When a standalone variable (e.g., showWorkoutForm from useState)
3411
+ // appears as a sub-property of a scalar-typed ancestor (e.g.,
3412
+ // activity_type = "string"), it's from scope conflation, not real
3413
+ // property access. Block these while allowing legitimate built-in
3414
+ // accesses like string.length or string.slice.
3415
+ let isConflatedPath = false;
3416
+ let checkPos = signaturePath.length;
3417
+ while (true) {
3418
+ checkPos = sigKey.indexOf('.', checkPos + 1);
3419
+ if (checkPos === -1) break;
3420
+ const ancestorPath = sigKey.substring(0, checkPos);
3421
+ const ancestorType = scopeNode.schema[ancestorPath];
3422
+ if (ancestorType && isDefinitelyScalar(ancestorType)) {
3423
+ // Ancestor is scalar — check if the immediate sub-property
3424
+ // is also a standalone variable (indicating conflation)
3425
+ const afterDot = sigKey.substring(checkPos + 1);
3426
+ const nextSep = afterDot.search(/[.\[]/);
3427
+ const subPropName =
3428
+ nextSep === -1
3429
+ ? afterDot
3430
+ : afterDot.substring(0, nextSep);
3431
+ if (scopeNode.schema[subPropName] !== undefined) {
3432
+ isConflatedPath = true;
3433
+ break;
3434
+ }
3435
+ }
3436
+ }
3437
+
3438
+ if (!isConflatedPath) {
3439
+ scopeNode.schema[sigKey] = scopeNode.schema[key];
3440
+ }
3441
+ }
3442
+ }
3443
+ }
3444
+ }
3445
+ }
3446
+ }
3447
+ }
3448
+
2886
3449
  private filterAndConvertSchema({
2887
3450
  filterPath,
2888
3451
  newPath,
@@ -2969,6 +3532,9 @@ export class ScopeDataStructure {
2969
3532
  equivalentValueSchemaPathParts.length,
2970
3533
  ),
2971
3534
  ]);
3535
+ // PERF: Skip keys with repeated function-call signature patterns
3536
+ // to prevent recursive type expansion (e.g., string.localeCompare returns string)
3537
+ if (this.hasExcessivePatternRepetition(newKey)) continue;
2972
3538
  resolvedSchema[newKey] = value;
2973
3539
  }
2974
3540
  }
@@ -2991,6 +3557,8 @@ export class ScopeDataStructure {
2991
3557
  if (!subSchema) continue;
2992
3558
 
2993
3559
  for (const resolvedKey in subSchema) {
3560
+ // PERF: Skip keys with repeated function-call signature patterns
3561
+ if (this.hasExcessivePatternRepetition(resolvedKey)) continue;
2994
3562
  if (
2995
3563
  !resolvedSchema[resolvedKey] ||
2996
3564
  subSchema[resolvedKey] === 'unknown'
@@ -3137,7 +3705,12 @@ export class ScopeDataStructure {
3137
3705
  );
3138
3706
  }
3139
3707
 
3708
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
3709
+ // during this "getter" method. See comment in getFunctionSignature.
3710
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
3711
+ this.onlyEquivalencies = true;
3140
3712
  this.validateSchema(scopeNode, true, fillInUnknowns);
3713
+ this.onlyEquivalencies = wasOnlyEquivalencies;
3141
3714
 
3142
3715
  const { schema } = scopeNode;
3143
3716
 
@@ -3171,10 +3744,29 @@ export class ScopeDataStructure {
3171
3744
  }
3172
3745
  }
3173
3746
  }
3174
- return mergedSchema;
3747
+ return this.filterDuplicateKeys(mergedSchema);
3175
3748
  }
3176
3749
 
3177
- return schema;
3750
+ return this.filterDuplicateKeys(schema);
3751
+ }
3752
+
3753
+ /**
3754
+ * Filter out ::cyDuplicateKey:: entries from a schema.
3755
+ * These are internal markers for tracking variable reassignments
3756
+ * and should not appear in output schemas or LLM prompts.
3757
+ */
3758
+ private filterDuplicateKeys(
3759
+ schema: Record<string, string>,
3760
+ ): Record<string, string> {
3761
+ return Object.entries(schema).reduce(
3762
+ (acc, [key, value]) => {
3763
+ if (!key.includes('::cyDuplicateKey')) {
3764
+ acc[key] = value;
3765
+ }
3766
+ return acc;
3767
+ },
3768
+ {} as Record<string, string>,
3769
+ );
3178
3770
  }
3179
3771
 
3180
3772
  getEquivalencies(scopeName?: string) {
@@ -3204,26 +3796,270 @@ export class ScopeDataStructure {
3204
3796
  return {};
3205
3797
  }
3206
3798
 
3799
+ // Collect all descendant scope names (including the scope itself)
3800
+ // This ensures we include external calls from nested scopes like cyScope2
3801
+ const getAllDescendantScopeNames = (
3802
+ node: import('./helpers/ScopeTreeManager').ScopeTreeNode,
3803
+ ): Set<string> => {
3804
+ const names = new Set<string>([node.name]);
3805
+ for (const child of node.children) {
3806
+ for (const name of getAllDescendantScopeNames(child)) {
3807
+ names.add(name);
3808
+ }
3809
+ }
3810
+ return names;
3811
+ };
3812
+
3813
+ const treeNode = this.scopeTreeManager.findNode(scopeNode.name);
3814
+ const descendantScopeNames = treeNode
3815
+ ? getAllDescendantScopeNames(treeNode)
3816
+ : new Set<string>([scopeNode.name]);
3817
+
3818
+ // Get all external function calls made from this scope or any descendant scope
3819
+ // This allows us to include prop equivalencies from JSX components
3820
+ // that were rendered in nested scopes (e.g., FileTableRow called from cyScope2)
3821
+ const externalCallsFromScope = this.externalFunctionCalls.filter((efc) =>
3822
+ descendantScopeNames.has(efc.callScope),
3823
+ );
3824
+ const externalCallNames = new Set(
3825
+ externalCallsFromScope.map((efc) => efc.name),
3826
+ );
3827
+
3828
+ // Helper to check if a usage belongs to this scope (directly, via descendant, or via external call)
3829
+ const usageMatchesScope = (usage: { scopeNodeName: string }) =>
3830
+ descendantScopeNames.has(usage.scopeNodeName) ||
3831
+ externalCallNames.has(usage.scopeNodeName);
3832
+
3207
3833
  const entries = this.equivalencyDatabase.filter((entry) =>
3208
- entry.usages.some((usage) => usage.scopeNodeName === scopeNode.name),
3834
+ entry.usages.some(usageMatchesScope),
3209
3835
  );
3210
- return entries.reduce(
3211
- (acc, entry) => {
3212
- if (entry.sourceCandidates.length === 0) return acc;
3213
- const usages = entry.usages.filter(
3214
- (u) => u.scopeNodeName === scopeNode.name,
3215
- );
3836
+
3837
+ // Helper to resolve a source candidate through equivalency chains to find signature paths
3838
+ const resolveToSignature = (
3839
+ source: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>,
3840
+ visited: Set<string>,
3841
+ ): Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] => {
3842
+ const visitKey = `${source.scopeNodeName}::${source.schemaPath}`;
3843
+ if (visited.has(visitKey)) return [];
3844
+ visited.add(visitKey);
3845
+
3846
+ // If already a signature path, return as-is
3847
+ if (source.schemaPath.startsWith('signature[')) {
3848
+ return [source];
3849
+ }
3850
+
3851
+ const currentScope = this.scopeNodes[source.scopeNodeName];
3852
+ if (!currentScope?.equivalencies) return [source];
3853
+
3854
+ // Check for direct equivalencies FIRST (full path match)
3855
+ // This ensures paths like "useMemo(...).functionCallReturnValue" follow to "cyScope1::returnValue"
3856
+ // before prefix matching tries "useMemo(...)" which goes to the useMemo scope
3857
+ const directEquivs = currentScope.equivalencies[source.schemaPath];
3858
+ if (directEquivs?.length > 0) {
3859
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3860
+ [];
3861
+ for (const equiv of directEquivs) {
3862
+ const resolved = resolveToSignature(
3863
+ {
3864
+ scopeNodeName: equiv.scopeNodeName,
3865
+ schemaPath: equiv.schemaPath,
3866
+ },
3867
+ visited,
3868
+ );
3869
+ results.push(...resolved);
3870
+ }
3871
+ if (results.length > 0) return results;
3872
+ }
3873
+
3874
+ // Handle spread patterns like [...items].sort().functionCallReturnValue
3875
+ // Extract the spread variable and resolve it through the equivalency chain
3876
+ const spreadMatch = source.schemaPath.match(/^\[\.\.\.(\w+)\]/);
3877
+ if (spreadMatch) {
3878
+ const spreadVar = spreadMatch[1];
3879
+ const spreadPattern = spreadMatch[0];
3880
+ const varEquivs = currentScope.equivalencies[spreadVar];
3881
+
3882
+ if (varEquivs?.length > 0) {
3883
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3884
+ [];
3885
+ for (const equiv of varEquivs) {
3886
+ // Follow the variable equivalency and then resolve from there
3887
+ const resolvedVar = resolveToSignature(
3888
+ {
3889
+ scopeNodeName: equiv.scopeNodeName,
3890
+ schemaPath: equiv.schemaPath,
3891
+ },
3892
+ visited,
3893
+ );
3894
+ // For each resolved variable path, create the full path with array element suffix
3895
+ for (const rv of resolvedVar) {
3896
+ if (rv.schemaPath.startsWith('signature[')) {
3897
+ // Get the suffix after the spread pattern
3898
+ let suffix = source.schemaPath.slice(spreadPattern.length);
3899
+
3900
+ // Clean the suffix: strip array method chains like .sort(...).functionCallReturnValue[]
3901
+ // These don't change the data identity, just transform it.
3902
+ // Keep only the final element access parts like [0], [1], etc.
3903
+ // Pattern: strip everything from a method call up through functionCallReturnValue[]
3904
+ suffix = suffix.replace(
3905
+ /\.\w+\([^)]*\)\.functionCallReturnValue\[\]/g,
3906
+ '',
3907
+ );
3908
+ // Also handle simpler case without nested parens
3909
+ suffix = suffix.replace(
3910
+ /\.sort\(\w*\(\)\)\.functionCallReturnValue\[\]/g,
3911
+ '',
3912
+ );
3913
+
3914
+ // Add [] to indicate array element access from the spread
3915
+ const resolvedPath = rv.schemaPath + '[]' + suffix;
3916
+ results.push({
3917
+ scopeNodeName: rv.scopeNodeName,
3918
+ schemaPath: resolvedPath,
3919
+ });
3920
+ }
3921
+ }
3922
+ }
3923
+ if (results.length > 0) return results;
3924
+ }
3925
+ }
3926
+
3927
+ // Try to find prefix equivalencies that can resolve this path
3928
+ // For path like "cyScope3().signature[0][0]", check "cyScope3().signature[0]", etc.
3929
+ const pathParts = this.splitPath(source.schemaPath);
3930
+ for (let i = pathParts.length - 1; i > 0; i--) {
3931
+ const prefix = this.joinPathParts(pathParts.slice(0, i));
3932
+ const suffix = this.joinPathParts(pathParts.slice(i));
3933
+ const prefixEquivs = currentScope.equivalencies[prefix];
3934
+
3935
+ if (prefixEquivs?.length > 0) {
3936
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3937
+ [];
3938
+ for (const equiv of prefixEquivs) {
3939
+ const newPath = this.joinPathParts([equiv.schemaPath, suffix]);
3940
+ const resolved = resolveToSignature(
3941
+ { scopeNodeName: equiv.scopeNodeName, schemaPath: newPath },
3942
+ visited,
3943
+ );
3944
+ results.push(...resolved);
3945
+ }
3946
+ if (results.length > 0) return results;
3947
+ }
3948
+ }
3949
+
3950
+ return [source];
3951
+ };
3952
+
3953
+ const acc = entries.reduce(
3954
+ (result, entry) => {
3955
+ if (entry.sourceCandidates.length === 0) return result;
3956
+ const usages = entry.usages.filter(usageMatchesScope);
3216
3957
  for (const usage of usages) {
3217
- acc[usage.schemaPath] ||= [];
3218
- acc[usage.schemaPath].push(...entry.sourceCandidates);
3958
+ result[usage.schemaPath] ||= [];
3959
+ // Resolve each source candidate through the equivalency chain
3960
+ for (const source of entry.sourceCandidates) {
3961
+ const resolvedSources = resolveToSignature(source, new Set());
3962
+ result[usage.schemaPath].push(...resolvedSources);
3963
+ }
3219
3964
  }
3220
- return acc;
3965
+ return result;
3221
3966
  },
3222
3967
  {} as Record<
3223
3968
  string,
3224
3969
  Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[]
3225
3970
  >,
3226
3971
  );
3972
+
3973
+ // Post-processing: enrich useState-backed sources with co-located external
3974
+ // function calls. When a useState value resolves to a setter variable that
3975
+ // lives in the same scope as a fetch/API call, that fetch is a data source.
3976
+ this.enrichUseStateSourcesWithCoLocatedCalls(acc);
3977
+
3978
+ return acc;
3979
+ }
3980
+
3981
+ /**
3982
+ * For each source that ends at a useState path, check if the setter was called
3983
+ * from a scope that also contains external function calls (like fetch).
3984
+ * If so, add those external calls as additional source candidates.
3985
+ */
3986
+ private enrichUseStateSourcesWithCoLocatedCalls(
3987
+ acc: Record<string, Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[]>,
3988
+ ) {
3989
+ const rootScopeName = this.scopeTreeManager.getRootName();
3990
+ const rootScope = this.scopeNodes[rootScopeName];
3991
+ if (!rootScope) return;
3992
+
3993
+ // Collect all descendants for each scope node
3994
+ const getAllDescendants = (
3995
+ node: import('./helpers/ScopeTreeManager').ScopeTreeNode,
3996
+ ): Set<string> => {
3997
+ const names = new Set<string>([node.name]);
3998
+ for (const child of node.children) {
3999
+ for (const name of getAllDescendants(child)) {
4000
+ names.add(name);
4001
+ }
4002
+ }
4003
+ return names;
4004
+ };
4005
+
4006
+ for (const [usagePath, sources] of Object.entries(acc)) {
4007
+ const additionalSources: Pick<
4008
+ ScopeVariable,
4009
+ 'scopeNodeName' | 'schemaPath'
4010
+ >[] = [];
4011
+
4012
+ for (const source of sources) {
4013
+ // Check if this source is a useState-related terminal path
4014
+ // (e.g., useState(X).functionCallReturnValue[1] or useState(X).signature[0])
4015
+ if (!source.schemaPath.match(/^useState\([^)]*\)\./)) continue;
4016
+
4017
+ // Find the useState call from the source path
4018
+ const useStateCallMatch = source.schemaPath.match(
4019
+ /^(useState\([^)]*\))\./,
4020
+ );
4021
+ if (!useStateCallMatch) continue;
4022
+ const useStateCall = useStateCallMatch[1];
4023
+
4024
+ // Look in the root scope for the useState value equivalency
4025
+ // which tells us where the setter was called from
4026
+ const valuePath = `${useStateCall}.functionCallReturnValue[0]`;
4027
+ const valueEquivs = rootScope.equivalencies[valuePath];
4028
+ if (!valueEquivs) continue;
4029
+
4030
+ for (const equiv of valueEquivs) {
4031
+ // Find the scope where the setter was called
4032
+ const setterScopeName = equiv.scopeNodeName;
4033
+ const setterScopeTree =
4034
+ this.scopeTreeManager.findNode(setterScopeName);
4035
+ if (!setterScopeTree) continue;
4036
+
4037
+ // Get all descendant scope names from the setter scope
4038
+ const relatedScopes = getAllDescendants(setterScopeTree);
4039
+
4040
+ // Find external function calls in those scopes whose return values
4041
+ // are actually consumed (assigned to a variable). This excludes
4042
+ // fire-and-forget calls like analytics.track() or console.log().
4043
+ const coLocatedCalls = this.externalFunctionCalls.filter(
4044
+ (efc) =>
4045
+ relatedScopes.has(efc.callScope) &&
4046
+ efc.receivingVariableNames &&
4047
+ efc.receivingVariableNames.length > 0,
4048
+ );
4049
+
4050
+ for (const call of coLocatedCalls) {
4051
+ additionalSources.push({
4052
+ scopeNodeName: call.callScope,
4053
+ schemaPath: `${call.callSignature}.functionCallReturnValue`,
4054
+ });
4055
+ }
4056
+ }
4057
+ }
4058
+
4059
+ if (additionalSources.length > 0) {
4060
+ acc[usagePath].push(...additionalSources);
4061
+ }
4062
+ }
3227
4063
  }
3228
4064
 
3229
4065
  getUsageEquivalencies(functionName?: string) {
@@ -3238,6 +4074,7 @@ export class ScopeDataStructure {
3238
4074
  (candidate) => candidate.scopeNodeName === scopeNode.name,
3239
4075
  ),
3240
4076
  );
4077
+
3241
4078
  return entries.reduce(
3242
4079
  (acc, entry) => {
3243
4080
  if (entry.usages.length === 0) return acc;
@@ -3281,12 +4118,14 @@ export class ScopeDataStructure {
3281
4118
  );
3282
4119
 
3283
4120
  const equivalencies = this.getEquivalencies(functionName);
4121
+ const scopeName = functionName ?? this.scopeTreeManager.getRootName();
4122
+
3284
4123
  for (const equivalenceKey in equivalencies ?? {}) {
3285
4124
  for (const equivalenceValue of equivalencies[equivalenceKey]) {
3286
4125
  const schemaPath = equivalenceValue.schemaPath;
3287
4126
  if (
3288
4127
  schemaPath.startsWith('signature[') &&
3289
- equivalenceValue.scopeNodeName === functionName &&
4128
+ equivalenceValue.scopeNodeName === scopeName &&
3290
4129
  !signatureInSchema[schemaPath]
3291
4130
  ) {
3292
4131
  signatureInSchema[schemaPath] = 'unknown';
@@ -3302,7 +4141,188 @@ export class ScopeDataStructure {
3302
4141
 
3303
4142
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
3304
4143
 
3305
- return tempScopeNode.schema;
4144
+ // After validateSchema has filled in types, propagate nested paths from
4145
+ // variables to their signature equivalents.
4146
+ // e.g., workouts[].activity_type -> signature[0].workouts[].activity_type
4147
+ //
4148
+ // Build a map of variable names that are equivalent to signature paths
4149
+ // e.g., { 'workouts': 'signature[0].workouts' }
4150
+ const variableToSignatureMap: Record<string, string> = {};
4151
+
4152
+ for (const equivalenceKey in equivalencies ?? {}) {
4153
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
4154
+ const schemaPath = equivalenceValue.schemaPath;
4155
+ // Track which variables map to signature paths
4156
+ // equivalenceKey is the variable name (e.g., 'workouts')
4157
+ // schemaPath is where it comes from (e.g., 'signature[0].workouts')
4158
+ if (
4159
+ schemaPath.startsWith('signature[') &&
4160
+ equivalenceValue.scopeNodeName === scopeName
4161
+ ) {
4162
+ variableToSignatureMap[equivalenceKey] = schemaPath;
4163
+ }
4164
+ }
4165
+ }
4166
+
4167
+ // Enrich schema with deeply nested paths from internal function call scopes.
4168
+ // When a function call like traverse(tree) exists, and traverse's scope has
4169
+ // signature[0].children[path][entityName] (from propagateParameterToSignaturePaths),
4170
+ // we need to map those paths back to the argument variable (tree) in this scope.
4171
+ // This handles cases where cycle detection prevented the equivalency chain from
4172
+ // propagating deep paths during Phase 2 batch queue processing.
4173
+ for (const equivalenceKey in equivalencies ?? {}) {
4174
+ // Look for keys matching function call pattern: funcName(...).signature[N]
4175
+ const funcCallMatch = equivalenceKey.match(
4176
+ /^([^(]+)\(.*?\)\.(signature\[\d+\])$/,
4177
+ );
4178
+ if (!funcCallMatch) continue;
4179
+
4180
+ const calledFunctionName = funcCallMatch[1];
4181
+ const signatureParam = funcCallMatch[2]; // e.g., "signature[0]"
4182
+
4183
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
4184
+ if (equivalenceValue.scopeNodeName !== scopeName) continue;
4185
+
4186
+ const targetVariable = equivalenceValue.schemaPath;
4187
+
4188
+ // Get the called function's schema (includes propagated parameter paths)
4189
+ const childSchema = this.getSchema({
4190
+ scopeName: calledFunctionName,
4191
+ });
4192
+ if (!childSchema) continue;
4193
+
4194
+ // Map child function's signature paths to parent variable paths
4195
+ const sigPrefix = signatureParam + '.';
4196
+ const sigBracketPrefix = signatureParam + '[';
4197
+ for (const childKey in childSchema) {
4198
+ let suffix: string | null = null;
4199
+ if (childKey.startsWith(sigPrefix)) {
4200
+ suffix = childKey.slice(signatureParam.length);
4201
+ } else if (childKey.startsWith(sigBracketPrefix)) {
4202
+ suffix = childKey.slice(signatureParam.length);
4203
+ }
4204
+
4205
+ if (suffix !== null) {
4206
+ const parentKey = targetVariable + suffix;
4207
+ if (!schema[parentKey]) {
4208
+ schema[parentKey] = childSchema[childKey];
4209
+ }
4210
+ }
4211
+ }
4212
+ }
4213
+ }
4214
+
4215
+ // Helper: check if a type is a concrete scalar that cannot have sub-properties.
4216
+ // e.g., "string", "number | undefined", "boolean | null" are scalar.
4217
+ // "object", "array", "function", "unknown", "Workout", etc. are NOT scalar.
4218
+ const SCALAR_TYPES = new Set([
4219
+ 'string',
4220
+ 'number',
4221
+ 'boolean',
4222
+ 'bigint',
4223
+ 'symbol',
4224
+ 'void',
4225
+ 'never',
4226
+ ]);
4227
+ const isDefinitelyScalarType = (type: string): boolean => {
4228
+ const parts = type.split('|').map((s) => s.trim());
4229
+ const base = parts.filter((s) => s !== 'undefined' && s !== 'null');
4230
+ return base.length > 0 && base.every((b) => SCALAR_TYPES.has(b));
4231
+ };
4232
+
4233
+ // Propagate nested paths from variables to their signature equivalents
4234
+ // e.g., if workouts = signature[0].workouts, then workouts[].title becomes
4235
+ // signature[0].workouts[].title
4236
+ for (const schemaKey in schema) {
4237
+ // Skip keys that already start with signature[
4238
+ if (schemaKey.startsWith('signature[')) continue;
4239
+
4240
+ // Check if this key starts with a variable that maps to a signature path
4241
+ for (const [variableName, signaturePath] of Object.entries(
4242
+ variableToSignatureMap,
4243
+ )) {
4244
+ // Check if schemaKey starts with variableName followed by a property accessor
4245
+ // e.g., 'workouts[]' starts with 'workouts'
4246
+ if (
4247
+ schemaKey === variableName ||
4248
+ schemaKey.startsWith(variableName + '.') ||
4249
+ schemaKey.startsWith(variableName + '[')
4250
+ ) {
4251
+ // Transform the path: replace the variable prefix with the signature path
4252
+ const suffix = schemaKey.slice(variableName.length);
4253
+ const signatureKey = signaturePath + suffix;
4254
+
4255
+ // Add to schema if not already present
4256
+ if (!tempScopeNode.schema[signatureKey]) {
4257
+ // Check if this path represents variable conflation:
4258
+ // When a standalone variable (e.g., showWorkoutForm from useState)
4259
+ // appears as a sub-property of a scalar-typed ancestor (e.g.,
4260
+ // activity_type = "string"), it's from scope conflation, not real
4261
+ // property access. Block these while allowing legitimate built-in
4262
+ // accesses like string.length or string.slice.
4263
+ let isConflatedPath = false;
4264
+ let checkPos = signaturePath.length;
4265
+ while (true) {
4266
+ checkPos = signatureKey.indexOf('.', checkPos + 1);
4267
+ if (checkPos === -1) break;
4268
+ const ancestorPath = signatureKey.substring(0, checkPos);
4269
+ const ancestorType = tempScopeNode.schema[ancestorPath];
4270
+ if (ancestorType && isDefinitelyScalarType(ancestorType)) {
4271
+ // Ancestor is scalar — check if the immediate sub-property
4272
+ // is also a standalone variable (indicating conflation)
4273
+ const afterDot = signatureKey.substring(checkPos + 1);
4274
+ const nextSep = afterDot.search(/[.\[]/);
4275
+ const subPropName =
4276
+ nextSep === -1 ? afterDot : afterDot.substring(0, nextSep);
4277
+ if (schema[subPropName] !== undefined) {
4278
+ isConflatedPath = true;
4279
+ break;
4280
+ }
4281
+ }
4282
+ }
4283
+
4284
+ if (!isConflatedPath) {
4285
+ tempScopeNode.schema[signatureKey] = schema[schemaKey];
4286
+ }
4287
+ }
4288
+ }
4289
+ }
4290
+ }
4291
+
4292
+ // Post-process: filter out conflated signature paths.
4293
+ // During phase 2 scope analysis, useState(false) conflation can create
4294
+ // bad paths like signature[0].mockWorkouts[].activity_type.showWorkoutForm
4295
+ // directly in scopeNode.schema. These flow through signatureInSchema into
4296
+ // tempScopeNode.schema without any guard. Filter them out here by checking:
4297
+ // 1. An ancestor in the path has a concrete scalar type (string, number, boolean, etc.)
4298
+ // 2. The immediate sub-property of that scalar ancestor is also a standalone
4299
+ // variable in the schema (indicating conflation, not a real property access)
4300
+ for (const key of Object.keys(tempScopeNode.schema)) {
4301
+ if (!key.startsWith('signature[')) continue;
4302
+
4303
+ // Walk through the path looking for scalar-typed ancestors
4304
+ let pos = 0;
4305
+ while (true) {
4306
+ pos = key.indexOf('.', pos + 1);
4307
+ if (pos === -1) break;
4308
+ const ancestorPath = key.substring(0, pos);
4309
+ const ancestorType = tempScopeNode.schema[ancestorPath];
4310
+ if (ancestorType && isDefinitelyScalarType(ancestorType)) {
4311
+ // Found a scalar ancestor — check if the sub-property name
4312
+ // is a standalone variable in the getSchema() result
4313
+ const afterDot = key.substring(pos + 1);
4314
+ const nextSep = afterDot.search(/[.\[]/);
4315
+ const subPropName =
4316
+ nextSep === -1 ? afterDot : afterDot.substring(0, nextSep);
4317
+ if (schema[subPropName] !== undefined) {
4318
+ delete tempScopeNode.schema[key];
4319
+ break;
4320
+ }
4321
+ }
4322
+ }
4323
+ }
4324
+
4325
+ return this.filterDuplicateKeys(tempScopeNode.schema);
3306
4326
  }
3307
4327
 
3308
4328
  getReturnValue({
@@ -3312,6 +4332,15 @@ export class ScopeDataStructure {
3312
4332
  functionName?: string;
3313
4333
  fillInUnknowns?: boolean;
3314
4334
  }) {
4335
+ // Trigger finalization on all managers to apply any pending updates
4336
+ // (e.g., ref type propagation to external function call schemas)
4337
+ const rootScope = this.scopeNodes[this.scopeTreeManager.getRootName()];
4338
+ if (rootScope) {
4339
+ for (const manager of this.equivalencyManagers) {
4340
+ manager.finalize(rootScope, this);
4341
+ }
4342
+ }
4343
+
3315
4344
  const scopeName = functionName ?? this.scopeTreeManager.getRootName();
3316
4345
  const scopeNode = this.scopeNodes[scopeName];
3317
4346
 
@@ -3322,7 +4351,8 @@ export class ScopeDataStructure {
3322
4351
  scopeNode: scopeNode,
3323
4352
  });
3324
4353
  } else {
3325
- for (const externalFunctionCall of this.externalFunctionCalls) {
4354
+ // Use getExternalFunctionCalls() which cleans cyScope from schemas
4355
+ for (const externalFunctionCall of this.getExternalFunctionCalls()) {
3326
4356
  const functionNameParts = this.splitPath(functionName).map((p) =>
3327
4357
  this.functionOrScopeName(p),
3328
4358
  );
@@ -3354,7 +4384,17 @@ export class ScopeDataStructure {
3354
4384
  // Include function paths even if their return value wasn't captured
3355
4385
  // This ensures methods like onAuthStateChange are included in the schema
3356
4386
  // But exclude signature entries (they should only be included via functionCallReturnValue paths)
3357
- (schema[key] === 'function' && key.indexOf('signature[') === -1),
4387
+ // Also exclude bare function call signatures - paths that are JUST a call like
4388
+ // "useCustomSizes(projectSlug)" should not be included as return values.
4389
+ // These represent "the function exists" not actual return data, and including
4390
+ // them causes nested path bugs in dependencySchemas.
4391
+ (schema[key] === 'function' &&
4392
+ key.indexOf('signature[') === -1 &&
4393
+ // Exclude bare call signatures: function calls with no dots OUTSIDE parentheses
4394
+ // e.g., "useCustomSizes(projectSlug)" is bare (exclude)
4395
+ // e.g., "loadProject({nested.property})" is bare - dots are inside args (exclude)
4396
+ // e.g., "getSupabase().auth.method()" has dots outside - method chain (include)
4397
+ !this.isBareCallSignature(key)),
3358
4398
  )
3359
4399
  .reduce(
3360
4400
  (acc, key) => {
@@ -3364,7 +4404,10 @@ export class ScopeDataStructure {
3364
4404
  for (const path in schema) {
3365
4405
  const pathParts = this.splitPath(path);
3366
4406
  if (pathParts.every((p, i) => keyParts[i] === p)) {
3367
- acc[path] = schema[path];
4407
+ // Also exclude bare call signatures from prefix paths
4408
+ if (!this.isBareCallSignature(path)) {
4409
+ acc[path] = schema[path];
4410
+ }
3368
4411
  }
3369
4412
  }
3370
4413
 
@@ -3378,14 +4421,73 @@ export class ScopeDataStructure {
3378
4421
 
3379
4422
  const tempScopeNode = this.createTempScopeNode(scopeName, resolvedSchema);
3380
4423
 
4424
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
4425
+ // during this "getter" method. See comment in getFunctionSignature.
4426
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
4427
+ this.onlyEquivalencies = true;
3381
4428
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
4429
+ this.onlyEquivalencies = wasOnlyEquivalencies;
4430
+
4431
+ // Remove bare call signatures from the return value schema.
4432
+ // fillInSchemaGapsAndUnknowns may add parent paths like "useCustomSizes(projectSlug)"
4433
+ // when it sees "useCustomSizes(projectSlug).functionCallReturnValue". These bare
4434
+ // call signatures represent "the function exists" not actual return data, and
4435
+ // including them causes nested path bugs in dependencySchemas.
4436
+ const resultSchema = tempScopeNode.schema;
4437
+ for (const key of Object.keys(resultSchema)) {
4438
+ if (this.isBareCallSignature(key)) {
4439
+ delete resultSchema[key];
4440
+ }
4441
+ }
4442
+
4443
+ return resultSchema;
4444
+ }
4445
+
4446
+ /**
4447
+ * Checks if a schema key is a "bare call signature" - a function call with no
4448
+ * method chain before it and no path segments after it.
4449
+ *
4450
+ * A bare call signature represents "this function exists" rather than actual
4451
+ * return data, and including them causes nested path bugs in dependencySchemas.
4452
+ *
4453
+ * Examples:
4454
+ * - "useCustomSizes(projectSlug)" -> bare (true)
4455
+ * - "loadProject({nested.property})" -> bare (dots are inside args, true)
4456
+ * - "getSupabase().auth.method()" -> not bare (has dots outside parens, false)
4457
+ * - "useProject().functionCallReturnValue" -> not bare (has path after, false)
4458
+ */
4459
+ private isBareCallSignature(key: string): boolean {
4460
+ // Must end with ) and contain ( to be a call
4461
+ if (!key.endsWith(')') || key.indexOf('(') === -1) {
4462
+ return false;
4463
+ }
4464
+
4465
+ // Check if there are any dots OUTSIDE of parentheses
4466
+ // Strip out content inside balanced parentheses, then check for dots
4467
+ let depth = 0;
4468
+ let hasDotsOutsideParens = false;
4469
+
4470
+ for (let i = 0; i < key.length; i++) {
4471
+ const char = key[i];
4472
+ if (char === '(') {
4473
+ depth++;
4474
+ } else if (char === ')') {
4475
+ depth--;
4476
+ } else if (char === '.' && depth === 0) {
4477
+ hasDotsOutsideParens = true;
4478
+ break;
4479
+ }
4480
+ }
3382
4481
 
3383
- return tempScopeNode.schema;
4482
+ // It's a bare call signature if there are no dots outside parentheses
4483
+ return !hasDotsOutsideParens;
3384
4484
  }
3385
4485
 
3386
4486
  /**
3387
4487
  * Replaces cyScope placeholder references (e.g., cyScope10()) in schema keys
3388
4488
  * with the actual callback function text from the corresponding scope node.
4489
+ * If the scope text can't be found, uses a generic fallback to avoid leaking
4490
+ * internal cyScope names into stored data.
3389
4491
  */
3390
4492
  private replaceCyScopePlaceholders(
3391
4493
  schema: Record<string, string>,
@@ -3401,10 +4503,10 @@ export class ScopeDataStructure {
3401
4503
  for (const match of matches) {
3402
4504
  const cyScopeName = `cyScope${match[1]}`;
3403
4505
  const scopeText = this.findCyScopeText(cyScopeName);
3404
- if (scopeText) {
3405
- // Replace cyScope10() with the actual callback text
3406
- newKey = newKey.replace(match[0], scopeText);
3407
- }
4506
+ // Always replace cyScope references - use actual text if available,
4507
+ // otherwise use a generic callback placeholder
4508
+ const replacement = scopeText || '() => {}';
4509
+ newKey = newKey.replace(match[0], replacement);
3408
4510
  }
3409
4511
 
3410
4512
  result[newKey] = value;
@@ -3462,40 +4564,450 @@ export class ScopeDataStructure {
3462
4564
  return scopeText;
3463
4565
  }
3464
4566
 
3465
- getEquivalentSignatureVariables() {
4567
+ getEquivalentSignatureVariables(): Record<string, string | string[]> {
3466
4568
  const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
3467
4569
 
3468
- const equivalentSignatureVariables: Record<string, string> = {};
4570
+ const equivalentSignatureVariables: Record<string, string | string[]> = {};
4571
+
4572
+ // Helper to add equivalencies - accumulates into array if multiple values for same key
4573
+ // This is critical for OR expressions like `x = a || b` where x should map to both a and b
4574
+ const addEquivalency = (key: string, value: string) => {
4575
+ const existing = equivalentSignatureVariables[key];
4576
+ if (existing === undefined) {
4577
+ // First value - store as string
4578
+ equivalentSignatureVariables[key] = value;
4579
+ } else if (typeof existing === 'string') {
4580
+ if (existing !== value) {
4581
+ // Second different value - convert to array
4582
+ equivalentSignatureVariables[key] = [existing, value];
4583
+ }
4584
+ // Same value - no change needed
4585
+ } else {
4586
+ // Already an array - add if not already present
4587
+ if (!existing.includes(value)) {
4588
+ existing.push(value);
4589
+ }
4590
+ }
4591
+ };
4592
+
3469
4593
  for (const [path, equivalentValues] of Object.entries(
3470
4594
  scopeNode.equivalencies,
3471
4595
  )) {
3472
4596
  for (const equivalentValue of equivalentValues) {
4597
+ // Case 1: Props/signature equivalencies (existing behavior)
4598
+ // Maps local variable names to their signature paths
4599
+ // e.g., "propValue" -> "signature[0].prop"
3473
4600
  if (path.startsWith('signature[')) {
3474
- equivalentSignatureVariables[equivalentValue.schemaPath] = path;
4601
+ addEquivalency(equivalentValue.schemaPath, path);
3475
4602
  }
3476
- }
3477
- }
3478
4603
 
3479
- return equivalentSignatureVariables;
3480
- }
4604
+ // Case 2: Hook variable equivalencies (new behavior)
4605
+ // The equivalencies are stored as: path = variable name, schemaPath = data source
4606
+ // e.g., path = "debugFetcher", schemaPath = "useFetcher<...>().functionCallReturnValue"
4607
+ // We need to map: "debugFetcher" -> "useFetcher<...>()"
4608
+ // This enables resolving paths like "debugFetcher.state" to
4609
+ // "useFetcher<...>().state" for execution flow validation
4610
+ if (equivalentValue.schemaPath.endsWith('.functionCallReturnValue')) {
4611
+ // Extract the hook call path (everything before .functionCallReturnValue)
4612
+ let hookCallPath = equivalentValue.schemaPath.slice(
4613
+ 0,
4614
+ -'.functionCallReturnValue'.length,
4615
+ );
4616
+ // Only include if it looks like a hook call (contains parentheses)
4617
+ // and the variable name (path) is a simple identifier (no dots)
4618
+ if (hookCallPath.includes('(') && !path.includes('.')) {
4619
+ // Special case: If hookCallPath is a callback scope (cyScope pattern),
4620
+ // trace through it to find what the callback actually returns.
4621
+ // This handles useState(() => { return prop; }) patterns.
4622
+ const cyScopeMatch = hookCallPath.match(/^(cyScope\d+)\(\)$/);
4623
+ if (cyScopeMatch) {
4624
+ // Use the equivalency database to trace the callback's return value
4625
+ // to its actual source (e.g., viewModeFromUrl -> segments -> params -> useParams)
4626
+ const dbEntry = this.getEquivalenciesDatabaseEntry(
4627
+ scopeNode.name, // Component scope
4628
+ path, // variable name (e.g., viewMode)
4629
+ );
4630
+ if (dbEntry?.sourceCandidates?.length > 0) {
4631
+ // Use the traced source instead of the callback scope
4632
+ hookCallPath = dbEntry.sourceCandidates[0].schemaPath;
4633
+ }
4634
+ }
4635
+ addEquivalency(path, hookCallPath);
4636
+ }
4637
+ }
3481
4638
 
3482
- getVariableInfo(
3483
- variableName: string,
3484
- scopeName?: string,
3485
- final?: boolean,
3486
- ): VariableInfo | undefined {
3487
- const scopeNode = this.getScopeOrFunctionCallInfo(
3488
- scopeName ?? this.scopeTreeManager.getRootName(),
3489
- );
3490
- if (!scopeNode) return;
4639
+ // Case 3: Destructured variables from local variables
4640
+ // e.g., const { scenarios } = currentEntityAnalysis;
4641
+ // This creates: path = "scenarios", schemaPath = "currentEntityAnalysis.scenarios"
4642
+ // We need to map: "scenarios" -> "currentEntityAnalysis.scenarios"
4643
+ // AND resolve transitively if currentEntityAnalysis is itself equivalent to a hook call
4644
+ if (
4645
+ !path.includes('.') && // path is a simple identifier
4646
+ !equivalentValue.schemaPath.startsWith('signature[') && // not a signature path
4647
+ !equivalentValue.schemaPath.endsWith('.functionCallReturnValue') // not already handled above
4648
+ ) {
4649
+ // Skip bare "returnValue" from child scopes — this is the child's return value,
4650
+ // not a meaningful data source path in the parent scope
4651
+ if (
4652
+ equivalentValue.schemaPath === 'returnValue' &&
4653
+ equivalentValue.scopeNodeName !==
4654
+ this.scopeTreeManager.getRootName()
4655
+ ) {
4656
+ continue;
4657
+ }
4658
+ // Add equivalency (will accumulate if multiple values for OR expressions)
4659
+ addEquivalency(path, equivalentValue.schemaPath);
4660
+ }
3491
4661
 
3492
- let equivalents = scopeNode.equivalencies[variableName];
4662
+ // Case 4: Child component prop mappings (Fix 22)
4663
+ // When parent renders <ChildComponent prop={value} />, we get equivalencies like:
4664
+ // path = "ChildComponent().signature[0].prop"
4665
+ // schemaPath = "value" (the variable passed as the prop)
4666
+ // We need to include these so translateChildPathToParent can work.
4667
+ // Pattern: ComponentName().signature[N] or ComponentName().signature[N].propName
4668
+ if (
4669
+ path.includes('().signature[') &&
4670
+ !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable, not a function call
4671
+ ) {
4672
+ addEquivalency(path, equivalentValue.schemaPath);
4673
+ }
3493
4674
 
3494
- if (!equivalents || equivalents.length === 0) {
3495
- equivalents = [
3496
- {
3497
- id: -1,
3498
- scopeNodeName: scopeNode.name,
4675
+ // Case 5: Destructured function parameters (Fix 25)
4676
+ // When a function has destructured props: function Comp({ propA, propB }: Props)
4677
+ // We get equivalencies like:
4678
+ // path = "propA" (the destructured variable name)
4679
+ // schemaPath = "signature[0].propA" (the signature path)
4680
+ // We need to map: "propA" -> "signature[0].propA"
4681
+ // This enables translateChildPathToParent to resolve child variable paths
4682
+ // to their signature paths when merging execution flows.
4683
+ if (
4684
+ !path.includes('.') && // path is a simple identifier (destructured prop name)
4685
+ equivalentValue.schemaPath.startsWith('signature[') // schemaPath IS a signature path
4686
+ ) {
4687
+ addEquivalency(path, equivalentValue.schemaPath);
4688
+ }
4689
+
4690
+ // Case 7: Method calls on variables that result in .functionCallReturnValue (Fix 33)
4691
+ // When we have patterns like:
4692
+ // path = "segments" (simple identifier)
4693
+ // schemaPath = "splat.split('/').functionCallReturnValue"
4694
+ // This is a method call on a variable (not a hook call), but we still need to
4695
+ // track it so transitive resolution can resolve `splat` to its actual source.
4696
+ // E.g., if splat -> useParams().functionCallReturnValue['*'], then
4697
+ // segments -> useParams().functionCallReturnValue['*'].split('/').functionCallReturnValue
4698
+ if (
4699
+ !path.includes('.') && // path is a simple identifier
4700
+ equivalentValue.schemaPath.endsWith('.functionCallReturnValue') && // ends with function return
4701
+ equivalentValue.schemaPath.includes('.') // has property access (method call)
4702
+ ) {
4703
+ // Check if this looks like a method call on a variable (not a hook call)
4704
+ // Hook calls look like: hookName() or hookName<T>()
4705
+ // Method calls look like: variable.method() or variable.method<T>()
4706
+ const hookCallPath = equivalentValue.schemaPath.slice(
4707
+ 0,
4708
+ -'.functionCallReturnValue'.length,
4709
+ );
4710
+ // If it's a method call (contains a dot before the parenthesis), include it
4711
+ const dotBeforeParen = hookCallPath.indexOf('.');
4712
+ const parenPos = hookCallPath.indexOf('(');
4713
+ if (dotBeforeParen !== -1 && dotBeforeParen < parenPos) {
4714
+ // This is a method call like "splat.split('/')", not a hook call
4715
+ addEquivalency(path, equivalentValue.schemaPath);
4716
+ }
4717
+ }
4718
+ }
4719
+ }
4720
+
4721
+ // Case 6: Collect JSX child prop equivalencies from child scopes (Fix 26)
4722
+ // When a parent component renders <ChildComponent prop={value} />, the JSX
4723
+ // return statement may be in a child scope (e.g., cyScope2). The equivalencies
4724
+ // like ChildComponent().signature[0].prop -> value get stored in that child scope.
4725
+ // But translateChildPathToParent needs to find them from the parent scope's context.
4726
+ // So we collect Case 4 patterns from ALL child scopes that belong to this root scope.
4727
+ const rootName = this.scopeTreeManager.getRootName();
4728
+ for (const [scopeName, childScopeNode] of Object.entries(this.scopeNodes)) {
4729
+ // Skip the root scope (already processed above)
4730
+ if (scopeName === rootName) continue;
4731
+
4732
+ // Only include scopes that are children of the root (their tree includes root)
4733
+ if (!childScopeNode.tree?.includes(rootName)) continue;
4734
+
4735
+ // Look for Case 4 patterns in the child scope
4736
+ for (const [path, equivalentValues] of Object.entries(
4737
+ childScopeNode.equivalencies || {},
4738
+ )) {
4739
+ for (const equivalentValue of equivalentValues) {
4740
+ // Case 4 pattern: ChildComponent().signature[0].propName -> parentVariable
4741
+ if (
4742
+ path.includes('().signature[') &&
4743
+ !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable
4744
+ ) {
4745
+ // Only add if not already present from the root scope
4746
+ // Root scope values take precedence over child scope values
4747
+ if (!(path in equivalentSignatureVariables)) {
4748
+ addEquivalency(path, equivalentValue.schemaPath);
4749
+ }
4750
+ }
4751
+ }
4752
+ }
4753
+ }
4754
+
4755
+ // Transitive resolution: Resolve variable chains through multiple levels
4756
+ // E.g., analysis → currentEntityAnalysis → useLoaderData().functionCallReturnValue.currentEntityAnalysis
4757
+ // We need multiple passes because resolutions can depend on each other
4758
+ const maxIterations = 5; // Prevent infinite loops
4759
+
4760
+ // Helper function to resolve a single source path using equivalencies
4761
+ const resolveSourcePath = (
4762
+ sourcePath: string,
4763
+ equivMap: Record<string, string | string[]>,
4764
+ ): string | null => {
4765
+ // Extract base variable from the path
4766
+ const dotIndex = sourcePath.indexOf('.');
4767
+ const bracketIndex = sourcePath.indexOf('[');
4768
+
4769
+ let baseVar: string;
4770
+ let rest: string;
4771
+
4772
+ if (dotIndex === -1 && bracketIndex === -1) {
4773
+ baseVar = sourcePath;
4774
+ rest = '';
4775
+ } else if (dotIndex === -1) {
4776
+ baseVar = sourcePath.slice(0, bracketIndex);
4777
+ rest = sourcePath.slice(bracketIndex);
4778
+ } else if (bracketIndex === -1) {
4779
+ baseVar = sourcePath.slice(0, dotIndex);
4780
+ rest = sourcePath.slice(dotIndex);
4781
+ } else {
4782
+ const firstIndex = Math.min(dotIndex, bracketIndex);
4783
+ baseVar = sourcePath.slice(0, firstIndex);
4784
+ rest = sourcePath.slice(firstIndex);
4785
+ }
4786
+
4787
+ // Look up the base variable in equivalencies
4788
+ if (baseVar in equivMap && equivMap[baseVar] !== sourcePath) {
4789
+ const baseResolved = equivMap[baseVar];
4790
+ // Skip if baseResolved is an array (handle later)
4791
+ if (Array.isArray(baseResolved)) return null;
4792
+ // If it resolves to a signature path, build the full resolved path
4793
+ if (
4794
+ baseResolved.startsWith('signature[') ||
4795
+ baseResolved.includes('()')
4796
+ ) {
4797
+ if (baseResolved.endsWith('()')) {
4798
+ return baseResolved + '.functionCallReturnValue' + rest;
4799
+ }
4800
+ return baseResolved + rest;
4801
+ }
4802
+ }
4803
+ return null;
4804
+ };
4805
+
4806
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
4807
+ let changed = false;
4808
+
4809
+ for (const [varName, sourcePathOrArray] of Object.entries(
4810
+ equivalentSignatureVariables,
4811
+ )) {
4812
+ // Handle arrays (OR expressions) by resolving each element
4813
+ if (Array.isArray(sourcePathOrArray)) {
4814
+ const resolvedArray: string[] = [];
4815
+ let arrayChanged = false;
4816
+ for (const sourcePath of sourcePathOrArray) {
4817
+ // Try to resolve this path using transitive resolution
4818
+ const resolved = resolveSourcePath(
4819
+ sourcePath,
4820
+ equivalentSignatureVariables,
4821
+ );
4822
+ if (resolved && resolved !== sourcePath) {
4823
+ resolvedArray.push(resolved);
4824
+ arrayChanged = true;
4825
+ } else {
4826
+ resolvedArray.push(sourcePath);
4827
+ }
4828
+ }
4829
+ if (arrayChanged) {
4830
+ equivalentSignatureVariables[varName] = resolvedArray;
4831
+ changed = true;
4832
+ }
4833
+ continue;
4834
+ }
4835
+ const sourcePath = sourcePathOrArray;
4836
+
4837
+ // Skip if already fully resolved (contains function call syntax)
4838
+ // BUT first check for computed value patterns that need resolution (Fix 28)
4839
+ // AND method call patterns that need base variable resolution (Fix 33)
4840
+ if (sourcePath.includes('()')) {
4841
+ // Fix 28: Handle computed value patterns with dependency arrays
4842
+ // Patterns like `functionName(arg, [dep1, dep2, ...])` are NOT controllable
4843
+ // data sources. We trace through the dependencies to find controllable sources.
4844
+ const bracketStart = sourcePath.indexOf('[');
4845
+ const bracketEnd = sourcePath.lastIndexOf(']');
4846
+
4847
+ if (bracketStart !== -1 && bracketEnd > bracketStart) {
4848
+ const arrayContent = sourcePath.slice(bracketStart + 1, bracketEnd);
4849
+ const items = arrayContent.split(',').map((s) => s.trim());
4850
+
4851
+ // Only process if this looks like a dependency array:
4852
+ // multiple items that are all simple identifiers (not numbers or expressions)
4853
+ const isIdentifier = (s: string) =>
4854
+ /^\w+$/.test(s) && !/^\d+$/.test(s);
4855
+ if (items.length > 1 && items.every(isIdentifier)) {
4856
+ // Look for a dependency that's already resolved to a controllable source
4857
+ for (const dep of items) {
4858
+ if (dep in equivalentSignatureVariables) {
4859
+ const resolvedDep = equivalentSignatureVariables[dep];
4860
+ // Use if it's a controllable path (contains hook call)
4861
+ // and is NOT another unresolved computed pattern (has comma-separated deps)
4862
+ const hasCommaInBrackets =
4863
+ resolvedDep.includes('[') &&
4864
+ resolvedDep.includes(',') &&
4865
+ resolvedDep.indexOf(',') > resolvedDep.indexOf('[');
4866
+ if (resolvedDep.includes('()') && !hasCommaInBrackets) {
4867
+ // Computed value is typically an element from an array
4868
+ equivalentSignatureVariables[varName] = resolvedDep + '[]';
4869
+ changed = true;
4870
+ break;
4871
+ }
4872
+ }
4873
+ }
4874
+ }
4875
+ }
4876
+
4877
+ // Fix 33: Handle method call patterns on variables
4878
+ // Patterns like: "splat.split('/').functionCallReturnValue"
4879
+ // We need to resolve the base variable (splat) to its actual source
4880
+ // Check if this is a method call on a variable (dot before first parenthesis)
4881
+ const dotIndex = sourcePath.indexOf('.');
4882
+ const parenIndex = sourcePath.indexOf('(');
4883
+ if (
4884
+ dotIndex !== -1 &&
4885
+ dotIndex < parenIndex &&
4886
+ !sourcePath.startsWith('use') // Not a hook call like useState()
4887
+ ) {
4888
+ // Extract the base variable (before the first dot)
4889
+ const baseVar = sourcePath.slice(0, dotIndex);
4890
+ const rest = sourcePath.slice(dotIndex); // includes ".method(...).functionCallReturnValue"
4891
+
4892
+ // Check if the base variable can be resolved
4893
+ if (
4894
+ baseVar in equivalentSignatureVariables &&
4895
+ baseVar !== varName
4896
+ ) {
4897
+ const baseResolved = equivalentSignatureVariables[baseVar];
4898
+ // Skip if baseResolved is an array (OR expression)
4899
+ if (Array.isArray(baseResolved)) continue;
4900
+ // Only resolve if the base resolved to something useful (contains () or .)
4901
+ if (baseResolved.includes('()') || baseResolved.includes('.')) {
4902
+ const newPath = baseResolved + rest;
4903
+ if (newPath !== equivalentSignatureVariables[varName]) {
4904
+ equivalentSignatureVariables[varName] = newPath;
4905
+ changed = true;
4906
+ }
4907
+ }
4908
+ }
4909
+ }
4910
+
4911
+ // Fix 38: Handle cyScope lazy initializer return values
4912
+ // When we have viewMode -> cyScope20(), trace through to find what cyScope20 returns.
4913
+ // The lazy initializer's return value should be the controllable data source.
4914
+ // Pattern: cyScopeN() where N is a number
4915
+ const cyScopeMatch = sourcePath.match(/^(cyScope\d+)\(\)$/);
4916
+ if (cyScopeMatch) {
4917
+ const cyScopeName = cyScopeMatch[1];
4918
+ const cyScopeNode = this.scopeNodes[cyScopeName];
4919
+
4920
+ if (cyScopeNode?.equivalencies) {
4921
+ // Look for returnValue equivalency in the cyScope
4922
+ const returnValueEquivs =
4923
+ cyScopeNode.equivalencies['returnValue'];
4924
+ if (returnValueEquivs && returnValueEquivs.length > 0) {
4925
+ // Get the first return value source
4926
+ const returnSource = returnValueEquivs[0].schemaPath;
4927
+
4928
+ // If the return source is a simple variable (not a complex path),
4929
+ // resolve varName directly to that variable
4930
+ if (
4931
+ returnSource &&
4932
+ !returnSource.includes('(') &&
4933
+ !returnSource.includes('[')
4934
+ ) {
4935
+ // Update varName to point to the return source
4936
+ if (equivalentSignatureVariables[varName] !== returnSource) {
4937
+ equivalentSignatureVariables[varName] = returnSource;
4938
+ changed = true;
4939
+ }
4940
+ }
4941
+ }
4942
+ }
4943
+ }
4944
+
4945
+ continue;
4946
+ }
4947
+
4948
+ // Check if the source path starts with a variable that's also in the map
4949
+ const dotIndex = sourcePath.indexOf('.');
4950
+ let baseVar: string;
4951
+ let rest: string;
4952
+
4953
+ if (dotIndex > 0) {
4954
+ // Path has a dot: "a.b.c" -> baseVar="a", rest=".b.c"
4955
+ baseVar = sourcePath.slice(0, dotIndex);
4956
+ rest = sourcePath.slice(dotIndex); // includes the leading dot
4957
+ } else {
4958
+ // Path is a simple identifier: "currentEntityAnalysis" -> baseVar="currentEntityAnalysis", rest=""
4959
+ baseVar = sourcePath;
4960
+ rest = '';
4961
+ }
4962
+
4963
+ if (baseVar in equivalentSignatureVariables && baseVar !== varName) {
4964
+ // Handle array case (OR expressions) - use first element
4965
+ const rawBaseResolved = equivalentSignatureVariables[baseVar];
4966
+ const baseResolved = Array.isArray(rawBaseResolved)
4967
+ ? rawBaseResolved[0]
4968
+ : rawBaseResolved;
4969
+ if (!baseResolved) continue;
4970
+ // If the base resolves to a hook call, add .functionCallReturnValue
4971
+ if (baseResolved.endsWith('()')) {
4972
+ const newPath = baseResolved + '.functionCallReturnValue' + rest;
4973
+ if (newPath !== equivalentSignatureVariables[varName]) {
4974
+ equivalentSignatureVariables[varName] = newPath;
4975
+ changed = true;
4976
+ }
4977
+ } else if (baseResolved !== sourcePath) {
4978
+ const newPath = baseResolved + rest;
4979
+ if (newPath !== equivalentSignatureVariables[varName]) {
4980
+ equivalentSignatureVariables[varName] = newPath;
4981
+ changed = true;
4982
+ }
4983
+ }
4984
+ }
4985
+ }
4986
+
4987
+ // Stop if no changes were made in this iteration
4988
+ if (!changed) break;
4989
+ }
4990
+
4991
+ return equivalentSignatureVariables;
4992
+ }
4993
+
4994
+ getVariableInfo(
4995
+ variableName: string,
4996
+ scopeName?: string,
4997
+ final?: boolean,
4998
+ ): VariableInfo | undefined {
4999
+ const scopeNode = this.getScopeOrFunctionCallInfo(
5000
+ scopeName ?? this.scopeTreeManager.getRootName(),
5001
+ );
5002
+ if (!scopeNode) return;
5003
+
5004
+ let equivalents = scopeNode.equivalencies[variableName];
5005
+
5006
+ if (!equivalents || equivalents.length === 0) {
5007
+ equivalents = [
5008
+ {
5009
+ id: -1,
5010
+ scopeNodeName: scopeNode.name,
3499
5011
  schemaPath: variableName,
3500
5012
  equivalencyReason: 'missing equivalency',
3501
5013
  },
@@ -3526,7 +5038,12 @@ export class ScopeDataStructure {
3526
5038
  relevantSchema,
3527
5039
  );
3528
5040
 
5041
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
5042
+ // during this "getter" method. See comment in getFunctionSignature.
5043
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
5044
+ this.onlyEquivalencies = true;
3529
5045
  this.validateSchema(tempScopeNode, true, final);
5046
+ this.onlyEquivalencies = wasOnlyEquivalencies;
3530
5047
 
3531
5048
  return {
3532
5049
  name: variableName,
@@ -3535,8 +5052,223 @@ export class ScopeDataStructure {
3535
5052
  };
3536
5053
  }
3537
5054
 
3538
- getExternalFunctionCalls() {
3539
- return this.externalFunctionCalls;
5055
+ getExternalFunctionCalls(): FunctionCallInfo[] {
5056
+ // Replace cyScope placeholders in all external function call data
5057
+ // This ensures call signatures and schema paths use actual callback text
5058
+ // instead of internal cyScope names, preventing mock data merge conflicts.
5059
+ const rootScopeName = this.scopeTreeManager.getRootName();
5060
+ const rootSchema = this.scopeNodes[rootScopeName]?.schema ?? {};
5061
+
5062
+ return this.externalFunctionCalls.map((efc) => {
5063
+ const cleaned = this.cleanCyScopeFromFunctionCallInfo(efc);
5064
+ return this.filterConflatedExternalPaths(cleaned, rootSchema);
5065
+ });
5066
+ }
5067
+
5068
+ /**
5069
+ * Filters out conflated paths from external function call schemas.
5070
+ *
5071
+ * When multiple useState(false) calls create equivalency conflation during
5072
+ * Phase 1 analysis, standalone boolean state variables (like showWorkoutForm,
5073
+ * showGoalForm) can bleed into external function call schemas as sub-properties
5074
+ * of unrelated data fields (like data[].activity_type.showWorkoutForm).
5075
+ *
5076
+ * Detection: group sub-properties by parent path. If 2+ sub-properties of
5077
+ * the same parent all match standalone root scope variable names, treat them
5078
+ * as conflation artifacts and remove them.
5079
+ */
5080
+ private filterConflatedExternalPaths(
5081
+ efc: FunctionCallInfo,
5082
+ rootSchema: Record<string, string>,
5083
+ ): FunctionCallInfo {
5084
+ // Build a set of top-level root scope variable names (simple names, no dots/brackets)
5085
+ const topLevelRootVars = new Set<string>();
5086
+ for (const key of Object.keys(rootSchema)) {
5087
+ if (!key.includes('.') && !key.includes('[')) {
5088
+ topLevelRootVars.add(key);
5089
+ }
5090
+ }
5091
+
5092
+ if (topLevelRootVars.size === 0) return efc;
5093
+
5094
+ // Group sub-property matches by their parent path.
5095
+ // For a path like "...data[].activity_type.showWorkoutForm",
5096
+ // parent = "...data[].activity_type", child = "showWorkoutForm"
5097
+ const parentToConflatedKeys = new Map<string, string[]>();
5098
+
5099
+ for (const key of Object.keys(efc.schema)) {
5100
+ const lastDot = key.lastIndexOf('.');
5101
+ if (lastDot === -1) continue;
5102
+
5103
+ const parent = key.substring(0, lastDot);
5104
+ const child = key.substring(lastDot + 1);
5105
+
5106
+ // Skip array access or function call patterns
5107
+ if (child.includes('[') || child.includes('(')) continue;
5108
+
5109
+ // Only consider paths inside array element chains (contains []).
5110
+ // Direct children of functionCallReturnValue are legitimate destructured
5111
+ // return values, not conflation. Conflation happens deeper in the chain
5112
+ // when array element fields get corrupted sub-properties.
5113
+ if (!parent.includes('[')) continue;
5114
+
5115
+ if (topLevelRootVars.has(child)) {
5116
+ if (!parentToConflatedKeys.has(parent)) {
5117
+ parentToConflatedKeys.set(parent, []);
5118
+ }
5119
+ parentToConflatedKeys.get(parent)!.push(key);
5120
+ }
5121
+ }
5122
+
5123
+ // Only filter when 2+ sub-properties of the same parent match root scope vars.
5124
+ // This threshold avoids false positives from coincidental name matches.
5125
+ const keysToRemove = new Set<string>();
5126
+ const parentsToRestore = new Set<string>();
5127
+
5128
+ for (const [parent, conflatedKeys] of parentToConflatedKeys) {
5129
+ if (conflatedKeys.length >= 2) {
5130
+ for (const key of conflatedKeys) {
5131
+ keysToRemove.add(key);
5132
+ }
5133
+ parentsToRestore.add(parent);
5134
+ }
5135
+ }
5136
+
5137
+ if (keysToRemove.size === 0) return efc;
5138
+
5139
+ // Create a new schema without the conflated paths
5140
+ const newSchema: Record<string, string> = {};
5141
+ for (const [key, value] of Object.entries(efc.schema)) {
5142
+ if (keysToRemove.has(key)) continue;
5143
+
5144
+ // Restore parent type: if it was changed to "object" because of conflated
5145
+ // sub-properties, and now all those sub-properties are removed, change it
5146
+ // back to "unknown" (we don't know the original type)
5147
+ if (parentsToRestore.has(key) && value === 'object') {
5148
+ // Check if there are any remaining sub-properties
5149
+ const hasRemainingSubProps = Object.keys(efc.schema).some(
5150
+ (k) =>
5151
+ !keysToRemove.has(k) &&
5152
+ k !== key &&
5153
+ (k.startsWith(key + '.') || k.startsWith(key + '[')),
5154
+ );
5155
+ newSchema[key] = hasRemainingSubProps ? value : 'unknown';
5156
+ } else {
5157
+ newSchema[key] = value;
5158
+ }
5159
+ }
5160
+
5161
+ return { ...efc, schema: newSchema };
5162
+ }
5163
+
5164
+ /**
5165
+ * Cleans cyScope placeholder references from a FunctionCallInfo.
5166
+ * Replaces cyScopeN() with the actual callback text in:
5167
+ * - callSignature
5168
+ * - allCallSignatures
5169
+ * - schema keys
5170
+ */
5171
+ private cleanCyScopeFromFunctionCallInfo(
5172
+ efc: FunctionCallInfo,
5173
+ ): FunctionCallInfo {
5174
+ const cyScopePattern = /cyScope\d+\(\)/g;
5175
+
5176
+ // Check if any cleaning is needed
5177
+ const hasCyScope =
5178
+ cyScopePattern.test(efc.callSignature) ||
5179
+ (efc.allCallSignatures &&
5180
+ efc.allCallSignatures.some((sig) => /cyScope\d+\(\)/.test(sig))) ||
5181
+ (efc.schema &&
5182
+ Object.keys(efc.schema).some((key) => /cyScope\d+\(\)/.test(key)));
5183
+
5184
+ if (!hasCyScope) {
5185
+ return efc;
5186
+ }
5187
+
5188
+ // Create cleaned copy
5189
+ const cleaned: FunctionCallInfo = { ...efc };
5190
+
5191
+ // Clean callSignature
5192
+ cleaned.callSignature = this.replaceCyScopeInString(efc.callSignature);
5193
+
5194
+ // Clean allCallSignatures
5195
+ if (efc.allCallSignatures) {
5196
+ cleaned.allCallSignatures = efc.allCallSignatures.map((sig) =>
5197
+ this.replaceCyScopeInString(sig),
5198
+ );
5199
+ }
5200
+
5201
+ // Clean schema keys
5202
+ if (efc.schema) {
5203
+ cleaned.schema = this.replaceCyScopePlaceholders(efc.schema);
5204
+ }
5205
+
5206
+ // Clean callSignatureToVariable keys
5207
+ if (efc.callSignatureToVariable) {
5208
+ cleaned.callSignatureToVariable = Object.entries(
5209
+ efc.callSignatureToVariable,
5210
+ ).reduce(
5211
+ (acc, [key, value]) => {
5212
+ acc[this.replaceCyScopeInString(key)] = value;
5213
+ return acc;
5214
+ },
5215
+ {} as Record<string, string>,
5216
+ );
5217
+ }
5218
+
5219
+ return cleaned;
5220
+ }
5221
+
5222
+ /**
5223
+ * Replaces cyScope placeholder references in a single string.
5224
+ * If the scope text can't be found, uses a generic fallback to avoid leaking
5225
+ * internal cyScope names into stored data.
5226
+ *
5227
+ * Handles two patterns:
5228
+ * 1. Function call style: cyScope7() - matched by cyScope(\d+)\(\)
5229
+ * 2. Scope name style: parentName____cyScopeXX or cyScopeXX - matched by (\w+____)?cyScope([0-9A-Fa-f]+)
5230
+ */
5231
+ private replaceCyScopeInString(str: string): string {
5232
+ let result = str;
5233
+
5234
+ // Pattern 1: Function call style - cyScope7()
5235
+ const functionCallPattern = /cyScope(\d+)\(\)/g;
5236
+ const functionCallMatches = [...str.matchAll(functionCallPattern)];
5237
+ for (const match of functionCallMatches) {
5238
+ const cyScopeName = `cyScope${match[1]}`;
5239
+ const scopeText = this.findCyScopeText(cyScopeName);
5240
+ // Always replace cyScope references - use actual text if available,
5241
+ // otherwise use a generic callback placeholder
5242
+ const replacement = scopeText || '() => {}';
5243
+ result = result.replace(match[0], replacement);
5244
+ }
5245
+
5246
+ // Pattern 2: Scope name style - parentName____cyScopeXX or just cyScopeXX
5247
+ // This handles hex-encoded scope IDs like cyScope1F
5248
+ const scopeNamePattern = /(\w+____)?cyScope([0-9A-Fa-f]+)/g;
5249
+ const scopeNameMatches = [...result.matchAll(scopeNamePattern)];
5250
+ for (const match of scopeNameMatches) {
5251
+ const fullMatch = match[0];
5252
+ const prefix = match[1] || ''; // e.g., "getTitleColor____"
5253
+ const cyScopeId = match[2]; // e.g., "1F"
5254
+ const cyScopeName = `cyScope${cyScopeId}`;
5255
+
5256
+ // Try to find the scope text, checking both with and without prefix
5257
+ let scopeText = this.findCyScopeText(cyScopeName);
5258
+ if (!scopeText && prefix) {
5259
+ // Try looking up with the full prefixed name
5260
+ scopeText = this.findCyScopeText(`${prefix}${cyScopeName}`);
5261
+ }
5262
+
5263
+ if (scopeText) {
5264
+ result = result.replace(fullMatch, scopeText);
5265
+ } else {
5266
+ // Replace with a generic identifier to avoid leaking internal names
5267
+ result = result.replace(fullMatch, 'callback');
5268
+ }
5269
+ }
5270
+
5271
+ return result;
3540
5272
  }
3541
5273
 
3542
5274
  getEnvironmentVariables() {
@@ -3554,7 +5286,7 @@ export class ScopeDataStructure {
3554
5286
  path: string;
3555
5287
  conditionType: 'truthiness' | 'comparison' | 'switch';
3556
5288
  comparedValues?: string[];
3557
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
5289
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
3558
5290
  }>
3559
5291
  >,
3560
5292
  ): void {
@@ -3579,29 +5311,149 @@ export class ScopeDataStructure {
3579
5311
  }
3580
5312
 
3581
5313
  /**
3582
- * Get enriched conditional usages with source tracing.
3583
- * Uses explainPath to trace each local variable back to its data source.
5314
+ * Add conditional effects from AST analysis.
5315
+ * Called during scope analysis to collect all setter calls inside conditionals.
5316
+ */
5317
+ addConditionalEffects(
5318
+ effects: import('../astScopes/types').ConditionalEffect[],
5319
+ ): void {
5320
+ // Add effects, avoiding duplicates based on effect stateVariable and condition paths
5321
+ for (const effect of effects) {
5322
+ const exists = this.rawConditionalEffects.some((existing) => {
5323
+ // Same effect target (stateVariable + value)
5324
+ const sameEffect =
5325
+ existing.effect.stateVariable === effect.effect.stateVariable &&
5326
+ existing.effect.value === effect.effect.value;
5327
+ if (!sameEffect) return false;
5328
+
5329
+ // Same condition(s)
5330
+ if (existing.condition && effect.condition) {
5331
+ return (
5332
+ existing.condition.path === effect.condition.path &&
5333
+ existing.condition.requiredValue === effect.condition.requiredValue
5334
+ );
5335
+ }
5336
+ if (existing.conditions && effect.conditions) {
5337
+ if (existing.conditions.length !== effect.conditions.length)
5338
+ return false;
5339
+ return existing.conditions.every((ec, i) => {
5340
+ const newCond = effect.conditions![i];
5341
+ return (
5342
+ ec.path === newCond.path &&
5343
+ ec.requiredValue === newCond.requiredValue
5344
+ );
5345
+ });
5346
+ }
5347
+ return false;
5348
+ });
5349
+ if (!exists) {
5350
+ this.rawConditionalEffects.push(effect);
5351
+ }
5352
+ }
5353
+ }
5354
+
5355
+ /**
5356
+ * Get conditional effects collected during analysis.
5357
+ */
5358
+ getConditionalEffects(): import('../astScopes/types').ConditionalEffect[] {
5359
+ return this.rawConditionalEffects;
5360
+ }
5361
+
5362
+ /**
5363
+ * Add compound conditionals from AST analysis.
5364
+ * Called during scope analysis to collect grouped conditions (e.g., a && b && c).
5365
+ */
5366
+ addCompoundConditionals(
5367
+ compounds: import('../astScopes/types').CompoundConditional[],
5368
+ ): void {
5369
+ // Add compounds, avoiding duplicates based on chainId
5370
+ for (const compound of compounds) {
5371
+ const exists = this.rawCompoundConditionals.some(
5372
+ (existing) => existing.chainId === compound.chainId,
5373
+ );
5374
+ if (!exists) {
5375
+ this.rawCompoundConditionals.push(compound);
5376
+ }
5377
+ }
5378
+ }
5379
+
5380
+ /**
5381
+ * Get compound conditionals collected during analysis.
5382
+ */
5383
+ getCompoundConditionals(): import('../astScopes/types').CompoundConditional[] {
5384
+ return this.rawCompoundConditionals;
5385
+ }
5386
+
5387
+ /**
5388
+ * Add child boundary gating conditions from AST analysis.
5389
+ * These track which conditions must be true for a child component to render.
3584
5390
  */
3585
- getEnrichedConditionalUsages(): Record<
5391
+ addChildBoundaryGatingConditions(
5392
+ conditions: Record<string, import('../astScopes/types').ConditionalUsage[]>,
5393
+ ): void {
5394
+ for (const [childName, usages] of Object.entries(conditions)) {
5395
+ if (!this.rawChildBoundaryGatingConditions[childName]) {
5396
+ this.rawChildBoundaryGatingConditions[childName] = [];
5397
+ }
5398
+ // Add usages, avoiding duplicates
5399
+ for (const usage of usages) {
5400
+ const exists = this.rawChildBoundaryGatingConditions[childName].some(
5401
+ (existing) =>
5402
+ existing.path === usage.path &&
5403
+ existing.conditionType === usage.conditionType &&
5404
+ existing.isNegated === usage.isNegated,
5405
+ );
5406
+ if (!exists) {
5407
+ this.rawChildBoundaryGatingConditions[childName].push(usage);
5408
+ }
5409
+ }
5410
+ }
5411
+ }
5412
+
5413
+ /**
5414
+ * Get enriched child boundary gating conditions with source tracing.
5415
+ * Similar to getEnrichedConditionalUsages but for gating conditions.
5416
+ */
5417
+ getEnrichedChildBoundaryGatingConditions(): Record<
3586
5418
  string,
3587
- Array<{
3588
- path: string;
3589
- conditionType: 'truthiness' | 'comparison' | 'switch';
3590
- comparedValues?: string[];
3591
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
3592
- sourceDataPath?: string;
3593
- }>
5419
+ EnrichedConditionalUsage[]
3594
5420
  > {
3595
- const enriched: Record<
3596
- string,
3597
- Array<{
3598
- path: string;
3599
- conditionType: 'truthiness' | 'comparison' | 'switch';
3600
- comparedValues?: string[];
3601
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
3602
- sourceDataPath?: string;
3603
- }>
3604
- > = {};
5421
+ const enriched: Record<string, EnrichedConditionalUsage[]> = {};
5422
+ const rootScopeName = this.scopeTreeManager.getTree().name;
5423
+
5424
+ for (const [childName, usages] of Object.entries(
5425
+ this.rawChildBoundaryGatingConditions,
5426
+ )) {
5427
+ enriched[childName] = usages.map((usage) => {
5428
+ // Try to trace this path back to a data source
5429
+ const explanation = this.explainPath(rootScopeName, usage.path);
5430
+
5431
+ let sourceDataPath: string | undefined;
5432
+ if (explanation.source) {
5433
+ sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
5434
+ }
5435
+
5436
+ return {
5437
+ ...usage,
5438
+ sourceDataPath,
5439
+ };
5440
+ });
5441
+ }
5442
+
5443
+ return enriched;
5444
+ }
5445
+
5446
+ /**
5447
+ * Get enriched conditional usages with source tracing.
5448
+ * Uses explainPath to trace each local variable back to its data source.
5449
+ * Preserves all fields from the raw conditional usages including derivedFrom.
5450
+ */
5451
+ getEnrichedConditionalUsages(): Record<string, EnrichedConditionalUsage[]> {
5452
+ const enriched: Record<string, EnrichedConditionalUsage[]> = {};
5453
+
5454
+ console.log(
5455
+ `[getEnrichedConditionalUsages] Processing ${Object.keys(this.rawConditionalUsages).length} conditional paths: [${Object.keys(this.rawConditionalUsages).join(', ')}]`,
5456
+ );
3605
5457
 
3606
5458
  for (const [path, usages] of Object.entries(this.rawConditionalUsages)) {
3607
5459
  // Try to trace this path back to a data source
@@ -3611,10 +5463,69 @@ export class ScopeDataStructure {
3611
5463
 
3612
5464
  let sourceDataPath: string | undefined;
3613
5465
  if (explanation.source) {
3614
- // Build the full data path: scopeName.path
3615
- sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
5466
+ const { scope, path: sourcePath } = explanation.source;
5467
+
5468
+ // Build initial path — avoid redundant prefix when path already contains the scope call
5469
+ let fullPath: string;
5470
+ if (sourcePath.startsWith(`${scope}(`)) {
5471
+ fullPath = sourcePath;
5472
+ } else {
5473
+ fullPath = `${scope}.${sourcePath}`;
5474
+ }
5475
+
5476
+ sourceDataPath = fullPath;
5477
+ console.log(
5478
+ `[getEnrichedConditionalUsages] "${path}" explainPath → scope="${scope}", sourcePath="${sourcePath}" → sourceDataPath="${sourceDataPath}"`,
5479
+ );
5480
+ } else {
5481
+ console.log(
5482
+ `[getEnrichedConditionalUsages] "${path}" explainPath → no source found`,
5483
+ );
3616
5484
  }
3617
5485
 
5486
+ // If explainPath didn't find a useful external source (e.g., it traced to
5487
+ // useState or just to the component scope itself), check sourceEquivalencies
5488
+ // for an external function call source like a fetch call
5489
+ const hasExternalSource = sourceDataPath?.includes(
5490
+ '.functionCallReturnValue',
5491
+ );
5492
+ if (!hasExternalSource) {
5493
+ console.log(
5494
+ `[getEnrichedConditionalUsages] "${path}" no external source (sourceDataPath="${sourceDataPath}"), checking sourceEquivalencies fallback...`,
5495
+ );
5496
+ const sourceEquiv = this.getSourceEquivalencies();
5497
+ const returnValueKey = `returnValue.${path}`;
5498
+ const sources = sourceEquiv[returnValueKey];
5499
+ if (sources) {
5500
+ console.log(
5501
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies["${returnValueKey}"] has ${sources.length} sources: [${sources.map((s: { schemaPath: string }) => s.schemaPath).join(', ')}]`,
5502
+ );
5503
+ const externalSource = sources.find(
5504
+ (s: { schemaPath: string }) =>
5505
+ s.schemaPath.includes('.functionCallReturnValue') &&
5506
+ !s.schemaPath.startsWith('useState('),
5507
+ );
5508
+ if (externalSource) {
5509
+ console.log(
5510
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies fallback found external source: "${externalSource.schemaPath}"`,
5511
+ );
5512
+ sourceDataPath = externalSource.schemaPath;
5513
+ } else {
5514
+ console.log(
5515
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies fallback found no external function call source`,
5516
+ );
5517
+ }
5518
+ } else {
5519
+ console.log(
5520
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies["${returnValueKey}"] not found`,
5521
+ );
5522
+ }
5523
+ }
5524
+
5525
+ console.log(
5526
+ `[getEnrichedConditionalUsages] "${path}" FINAL sourceDataPath="${sourceDataPath ?? '(none)'}" (${usages.length} usages)`,
5527
+ );
5528
+
3618
5529
  enriched[path] = usages.map((usage) => ({
3619
5530
  ...usage,
3620
5531
  sourceDataPath,
@@ -3624,35 +5535,86 @@ export class ScopeDataStructure {
3624
5535
  return enriched;
3625
5536
  }
3626
5537
 
5538
+ /**
5539
+ * Add JSX rendering usages from AST analysis.
5540
+ * These track arrays rendered via .map() and strings interpolated in JSX.
5541
+ */
5542
+ addJsxRenderingUsages(
5543
+ usages: import('../astScopes/types').JsxRenderingUsage[],
5544
+ ): void {
5545
+ // Add usages, avoiding duplicates based on path and renderingType
5546
+ for (const usage of usages) {
5547
+ const exists = this.rawJsxRenderingUsages.some(
5548
+ (existing) =>
5549
+ existing.path === usage.path &&
5550
+ existing.renderingType === usage.renderingType,
5551
+ );
5552
+ if (!exists) {
5553
+ this.rawJsxRenderingUsages.push(usage);
5554
+ }
5555
+ }
5556
+ }
5557
+
5558
+ /**
5559
+ * Get JSX rendering usages collected during analysis.
5560
+ */
5561
+ getJsxRenderingUsages(): import('../astScopes/types').JsxRenderingUsage[] {
5562
+ return this.rawJsxRenderingUsages;
5563
+ }
5564
+
3627
5565
  toSerializable(): SerializableDataStructure {
3628
- // Helper to convert ScopeVariable to SerializableScopeVariable
5566
+ // Helper to clean cyScope and cyDuplicateKey from a string for output
5567
+ const cleanCyScope = (str: string): string =>
5568
+ this.replaceCyScopeInString(str).replace(/::cyDuplicateKey\d+::/g, '');
5569
+
5570
+ // Helper to convert ScopeVariable to SerializableScopeVariable (with cyScope cleaned)
3629
5571
  const toSerializableVariable = (
3630
5572
  vars:
3631
5573
  | ScopeVariable[]
3632
5574
  | Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[],
3633
5575
  ): SerializableScopeVariable[] =>
3634
5576
  vars.map((v) => ({
3635
- scopeNodeName: v.scopeNodeName,
3636
- schemaPath: v.schemaPath,
5577
+ scopeNodeName: cleanCyScope(v.scopeNodeName),
5578
+ schemaPath: cleanCyScope(v.schemaPath),
3637
5579
  }));
3638
5580
 
5581
+ // Helper to clean cyScope from all keys in a schema
5582
+ const cleanSchemaKeys = (
5583
+ schema: Record<string, string>,
5584
+ ): Record<string, string> => {
5585
+ return Object.entries(schema).reduce(
5586
+ (acc, [key, value]) => {
5587
+ acc[cleanCyScope(key)] = value;
5588
+ return acc;
5589
+ },
5590
+ {} as Record<string, string>,
5591
+ );
5592
+ };
5593
+
3639
5594
  // Helper to get function result for a given function name
3640
5595
  const getFunctionResult = (
3641
5596
  functionName?: string,
3642
5597
  ): SerializableFunctionResult => {
3643
5598
  return {
3644
- signature: this.getFunctionSignature({ functionName }) ?? {},
3645
- signatureWithUnknowns:
5599
+ signature: cleanSchemaKeys(
5600
+ this.getFunctionSignature({ functionName }) ?? {},
5601
+ ),
5602
+ signatureWithUnknowns: cleanSchemaKeys(
3646
5603
  this.getFunctionSignature({ functionName, fillInUnknowns: true }) ??
3647
- {},
3648
- returnValue: this.getReturnValue({ functionName }) ?? {},
3649
- returnValueWithUnknowns:
5604
+ {},
5605
+ ),
5606
+ returnValue: cleanSchemaKeys(
5607
+ this.getReturnValue({ functionName }) ?? {},
5608
+ ),
5609
+ returnValueWithUnknowns: cleanSchemaKeys(
3650
5610
  this.getReturnValue({ functionName, fillInUnknowns: true }) ?? {},
5611
+ ),
3651
5612
  usageEquivalencies: Object.entries(
3652
5613
  this.getUsageEquivalencies(functionName) ?? {},
3653
5614
  ).reduce(
3654
5615
  (acc, [key, vars]) => {
3655
- acc[key] = toSerializableVariable(vars);
5616
+ // Clean cyScope from the key as well as variable properties
5617
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
3656
5618
  return acc;
3657
5619
  },
3658
5620
  {} as Record<string, SerializableScopeVariable[]>,
@@ -3661,7 +5623,8 @@ export class ScopeDataStructure {
3661
5623
  this.getSourceEquivalencies(functionName) ?? {},
3662
5624
  ).reduce(
3663
5625
  (acc, [key, vars]) => {
3664
- acc[key] = toSerializableVariable(vars);
5626
+ // Clean cyScope from the key as well as variable properties
5627
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
3665
5628
  return acc;
3666
5629
  },
3667
5630
  {} as Record<string, SerializableScopeVariable[]>,
@@ -3670,39 +5633,417 @@ export class ScopeDataStructure {
3670
5633
  };
3671
5634
  };
3672
5635
 
3673
- // Convert external function calls
5636
+ // Convert external function calls - use getExternalFunctionCalls() which cleans cyScope
5637
+ const cleanedExternalCalls = this.getExternalFunctionCalls();
5638
+
5639
+ // Get root scope schema for building per-variable return value schemas
5640
+ const rootScopeName = this.scopeTreeManager.getRootName();
5641
+ const rootScope = this.scopeNodes[rootScopeName];
5642
+ const rootSchema = rootScope?.schema ?? {};
5643
+
3674
5644
  const externalFunctionCalls: SerializableFunctionCallInfo[] =
3675
- this.externalFunctionCalls.map((efc) => ({
3676
- name: efc.name,
3677
- callSignature: efc.callSignature,
3678
- callScope: efc.callScope,
3679
- schema: efc.schema,
3680
- equivalencies: efc.equivalencies
3681
- ? Object.entries(efc.equivalencies).reduce(
3682
- (acc, [key, vars]) => {
3683
- acc[key] = toSerializableVariable(vars);
3684
- return acc;
3685
- },
3686
- {} as Record<string, SerializableScopeVariable[]>,
3687
- )
3688
- : undefined,
3689
- allCallSignatures: efc.allCallSignatures,
3690
- receivingVariableNames: efc.receivingVariableNames,
3691
- callSignatureToVariable: efc.callSignatureToVariable,
3692
- }));
5645
+ cleanedExternalCalls.map((efc) => {
5646
+ // Build perVariableSchemas from perCallSignatureSchemas when available.
5647
+ // This preserves distinct schemas per variable when the same function is called
5648
+ // multiple times with DIFFERENT call signatures (e.g., different type parameters).
5649
+ //
5650
+ // When field accesses happen in child scopes (like JSX expressions), the
5651
+ // rootSchema doesn't contain the detailed paths - they end up in child scope
5652
+ // schemas. Using perCallSignatureSchemas ensures we get the correct schema
5653
+ // for each call, regardless of where field accesses occur.
5654
+ let perVariableSchemas:
5655
+ | Record<string, Record<string, string>>
5656
+ | undefined;
5657
+
5658
+ // Use perCallSignatureSchemas only when:
5659
+ // 1. It exists and has distinct entries for different call signatures
5660
+ // 2. The number of distinct call signatures >= number of receiving variables
5661
+ //
5662
+ // This prevents using it when all calls have the same signature (e.g., useFetcher() x 2)
5663
+ // because in that case, perCallSignatureSchemas only has one entry.
5664
+ const numCallSignatures = efc.perCallSignatureSchemas
5665
+ ? Object.keys(efc.perCallSignatureSchemas).length
5666
+ : 0;
5667
+ const numReceivingVars = efc.receivingVariableNames?.length ?? 0;
5668
+ const hasDistinctSchemas =
5669
+ numCallSignatures >= numReceivingVars && numCallSignatures > 1;
5670
+
5671
+ // CASE 1: Multiple call signatures with distinct schemas - use indexed variable names
5672
+ if (
5673
+ hasDistinctSchemas &&
5674
+ efc.perCallSignatureSchemas &&
5675
+ efc.callSignatureToVariable
5676
+ ) {
5677
+ perVariableSchemas = {};
5678
+
5679
+ // Build a reverse map: variable -> array of call signatures (in order)
5680
+ // This handles the case where the same variable name is reused for different calls
5681
+ const varToCallSigs: Record<string, string[]> = {};
5682
+ for (const [callSig, varName] of Object.entries(
5683
+ efc.callSignatureToVariable,
5684
+ )) {
5685
+ if (!varToCallSigs[varName]) {
5686
+ varToCallSigs[varName] = [];
5687
+ }
5688
+ varToCallSigs[varName].push(callSig);
5689
+ }
5690
+
5691
+ // Track how many times each variable name has been seen
5692
+ const varNameCounts: Record<string, number> = {};
5693
+
5694
+ // For each receiving variable, get its original schema from perCallSignatureSchemas
5695
+ for (const varName of efc.receivingVariableNames ?? []) {
5696
+ const occurrence = varNameCounts[varName] ?? 0;
5697
+ varNameCounts[varName] = occurrence + 1;
5698
+
5699
+ const callSigs = varToCallSigs[varName];
5700
+ // Use the nth call signature for the nth occurrence of this variable
5701
+ const callSig = callSigs?.[occurrence];
5702
+
5703
+ if (callSig && efc.perCallSignatureSchemas[callSig]) {
5704
+ // Use indexed key if this variable name is reused (e.g., fetcher, fetcher[1])
5705
+ const key =
5706
+ occurrence === 0 ? varName : `${varName}[${occurrence}]`;
5707
+ // Clone the schema to avoid shared references
5708
+ perVariableSchemas[key] = {
5709
+ ...efc.perCallSignatureSchemas[callSig],
5710
+ };
5711
+ }
5712
+ }
5713
+
5714
+ // Only include if we have entries for ALL receiving variables
5715
+ if (Object.keys(perVariableSchemas).length < numReceivingVars) {
5716
+ // Not all variables have schemas - fall back to rootSchema extraction
5717
+ perVariableSchemas = undefined;
5718
+ } else {
5719
+ // Also check that at least one schema is non-empty
5720
+ // Bug fix: perCallSignatureSchemas may have entries but with empty schemas {}
5721
+ // In this case, we should fall through to Fallback which uses rootSchema
5722
+ const hasNonEmptySchema = Object.values(perVariableSchemas).some(
5723
+ (schema) => Object.keys(schema).length > 0,
5724
+ );
5725
+ if (!hasNonEmptySchema) {
5726
+ perVariableSchemas = undefined;
5727
+ }
5728
+ }
5729
+ }
5730
+
5731
+ // CASE 2: Single call signature with single variable - use perCallSignatureSchemas directly
5732
+ // This handles parameterized calls like useFetcher<ConfigData>() where each is a separate efc entry
5733
+ if (
5734
+ !perVariableSchemas &&
5735
+ efc.perCallSignatureSchemas &&
5736
+ numCallSignatures === 1 &&
5737
+ numReceivingVars === 1
5738
+ ) {
5739
+ const varName = efc.receivingVariableNames![0];
5740
+ const callSig = Object.keys(efc.perCallSignatureSchemas)[0];
5741
+ const schema = efc.perCallSignatureSchemas[callSig];
5742
+ if (schema && Object.keys(schema).length > 0) {
5743
+ perVariableSchemas = { [varName]: { ...schema } };
5744
+ }
5745
+ }
5746
+
5747
+ // CASE 3: Extract from efc.schema when perCallSignatureSchemas is missing or empty
5748
+ // This handles two scenarios:
5749
+ // 1. Parameterized calls that create SEPARATE efc entries (no perCallSignatureSchemas)
5750
+ // 2. Destructuring where perCallSignatureSchemas exists but has EMPTY schemas
5751
+ //
5752
+ // When useFetcher<ConfigData>() and useFetcher<SettingsData>() are called, they create separate
5753
+ // efc entries because getFunctionCallRoot preserves type parameters. Each entry has its own
5754
+ // `schema` field, but due to variable reassignment, the schema may be contaminated with paths
5755
+ // from other calls (the tracer attributes field accesses to ALL equivalencies).
5756
+ //
5757
+ // Solution: Filter efc.schema to only include paths that match THIS entry's call signature.
5758
+ // The schema paths include the full call signature prefix, so we can filter by it.
5759
+ //
5760
+ // Example: ConfigData entry has paths like:
5761
+ // "useFetcher<{ data: ConfigData | null }>().functionCallReturnValue.data.data.theme"
5762
+ // But also (contaminated):
5763
+ // "useFetcher<{ data: ConfigData | null }>().functionCallReturnValue.data.data.notifications"
5764
+ //
5765
+ // We filter to only keep paths that should belong to THIS call by checking if the
5766
+ // receiving variable's equivalency points to this call's return value.
5767
+ //
5768
+ // BUG FIX: The old condition `!efc.perCallSignatureSchemas` was FALSE when the object
5769
+ // existed (even with empty schemas), causing this case to be skipped. We now also check
5770
+ // if all schemas in perCallSignatureSchemas are empty.
5771
+ const hasNonEmptyPerCallSignatureSchemas =
5772
+ efc.perCallSignatureSchemas &&
5773
+ Object.values(efc.perCallSignatureSchemas).some(
5774
+ (schema) => Object.keys(schema).length > 0,
5775
+ );
5776
+
5777
+ // Build the call signature prefix that paths should start with
5778
+ const callSigPrefix = `${efc.callSignature}.functionCallReturnValue`;
5779
+
5780
+ // Check if efc.schema has variable-specific paths (indicating destructuring).
5781
+ // Destructuring: const { entities, gitStatus } = useLoaderData()
5782
+ // - efc.schema has paths like: useLoaderData().functionCallReturnValue.entities...
5783
+ // Multiple calls: const x = useFetcher(); const y = useFetcher();
5784
+ // - efc.schema has paths like: useFetcher().functionCallReturnValue.data...
5785
+ // CASE 3 should only run for destructuring (variable-specific paths exist).
5786
+ const hasVariableSpecificPaths = (
5787
+ efc.receivingVariableNames ?? []
5788
+ ).some((varName) =>
5789
+ Object.keys(efc.schema).some((path) =>
5790
+ path.startsWith(`${callSigPrefix}.${varName}`),
5791
+ ),
5792
+ );
5793
+
5794
+ if (
5795
+ !perVariableSchemas &&
5796
+ !hasNonEmptyPerCallSignatureSchemas &&
5797
+ numReceivingVars >= 1 &&
5798
+ hasVariableSpecificPaths
5799
+ ) {
5800
+ // Filter efc.schema to only include paths matching this call signature
5801
+ const filteredSchema: Record<string, string> = {};
5802
+ for (const [path, type] of Object.entries(efc.schema)) {
5803
+ if (path.startsWith(callSigPrefix) || path === efc.callSignature) {
5804
+ filteredSchema[path] = type;
5805
+ }
5806
+ }
5807
+
5808
+ // Build perVariableSchemas from the filtered schema
5809
+ // For destructuring, filter paths by variable name
5810
+ if (Object.keys(filteredSchema).length > 0) {
5811
+ perVariableSchemas = {};
5812
+ for (const varName of efc.receivingVariableNames ?? []) {
5813
+ // For destructuring, extract only paths specific to this variable
5814
+ const varSpecificPrefix = `${callSigPrefix}.${varName}`;
5815
+ const varSchema: Record<string, string> = {};
5816
+
5817
+ for (const [path, type] of Object.entries(filteredSchema)) {
5818
+ if (path.startsWith(varSpecificPrefix)) {
5819
+ // Transform: useLoaderData().functionCallReturnValue.entities.sha
5820
+ // -> functionCallReturnValue.entities.sha (keep the variable name)
5821
+ const suffix = path.slice(callSigPrefix.length);
5822
+ const returnValuePath = `functionCallReturnValue${suffix}`;
5823
+ varSchema[returnValuePath] = type;
5824
+ } else if (path === efc.callSignature) {
5825
+ // Include the function call type itself
5826
+ varSchema[path] = type;
5827
+ }
5828
+ }
5829
+ if (Object.keys(varSchema).length > 0) {
5830
+ perVariableSchemas[varName] = varSchema;
5831
+ }
5832
+ }
5833
+ // Only include if we have entries
5834
+ if (Object.keys(perVariableSchemas).length === 0) {
5835
+ perVariableSchemas = undefined;
5836
+ }
5837
+ }
5838
+ }
5839
+
5840
+ // Fallback: extract from root scope schema when perCallSignatureSchemas is not available
5841
+ // or doesn't have distinct entries for each variable.
5842
+ // This works when field accesses are in the root scope.
5843
+ if (
5844
+ !perVariableSchemas &&
5845
+ efc.receivingVariableNames &&
5846
+ efc.receivingVariableNames.length > 0
5847
+ ) {
5848
+ perVariableSchemas = {};
5849
+ for (const varName of efc.receivingVariableNames) {
5850
+ const varSchema: Record<string, string> = {};
5851
+ for (const [path, type] of Object.entries(rootSchema)) {
5852
+ // Check if path starts with this variable name
5853
+ if (
5854
+ path === varName ||
5855
+ path.startsWith(varName + '.') ||
5856
+ path.startsWith(varName + '[')
5857
+ ) {
5858
+ // Transform to functionCallReturnValue format
5859
+ // e.g., userFetcher.data.id -> functionCallReturnValue.data.id
5860
+ const suffix = path.slice(varName.length);
5861
+ const returnValuePath = `functionCallReturnValue${suffix}`;
5862
+ varSchema[returnValuePath] = type;
5863
+ }
5864
+ }
5865
+ if (Object.keys(varSchema).length > 0) {
5866
+ // Clean the variable name when using as key in output
5867
+ perVariableSchemas[cleanCyScope(varName)] = varSchema;
5868
+ }
5869
+ }
5870
+ // Only include if we have any entries
5871
+ if (Object.keys(perVariableSchemas).length === 0) {
5872
+ perVariableSchemas = undefined;
5873
+ }
5874
+ }
5875
+
5876
+ // Enrich the schema with inferred types by applying fillInSchemaGapsAndUnknowns.
5877
+ // This ensures the serialized schema has the same type inference as getReturnValue().
5878
+ // Without this, evidence like "entities[].analyses: array" becomes "unknown".
5879
+ const enrichedSchema = { ...efc.schema };
5880
+ const tempScopeNode = {
5881
+ name: efc.name,
5882
+ schema: enrichedSchema,
5883
+ equivalencies: efc.equivalencies ?? {},
5884
+ };
5885
+ fillInSchemaGapsAndUnknowns(tempScopeNode, true);
5886
+
5887
+ return {
5888
+ name: efc.name,
5889
+ callSignature: efc.callSignature,
5890
+ callScope: efc.callScope,
5891
+ schema: enrichedSchema,
5892
+ equivalencies: efc.equivalencies
5893
+ ? Object.entries(efc.equivalencies).reduce(
5894
+ (acc, [key, vars]) => {
5895
+ // Clean cyScope from the key as well as variable properties
5896
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
5897
+ return acc;
5898
+ },
5899
+ {} as Record<string, SerializableScopeVariable[]>,
5900
+ )
5901
+ : undefined,
5902
+ allCallSignatures: efc.allCallSignatures,
5903
+ receivingVariableNames: efc.receivingVariableNames?.map(cleanCyScope),
5904
+ callSignatureToVariable: efc.callSignatureToVariable
5905
+ ? Object.fromEntries(
5906
+ Object.entries(efc.callSignatureToVariable).map(([k, v]) => [
5907
+ k,
5908
+ cleanCyScope(v),
5909
+ ]),
5910
+ )
5911
+ : undefined,
5912
+ perVariableSchemas,
5913
+ };
5914
+ });
5915
+
5916
+ // POST-PROCESSING: Deduplicate schemas across parameterized calls to same base function
5917
+ // When useFetcher<ConfigData>() and useFetcher<SettingsData>() are called, they create
5918
+ // separate entries. Due to variable reassignment, BOTH entries may have ALL fields.
5919
+ // We deduplicate by assigning each field to ONLY ONE entry based on order of appearance.
5920
+ //
5921
+ // Strategy: Fields that appear first in order belong to the first entry,
5922
+ // fields that appear later belong to later entries (split evenly).
5923
+ const deduplicateParameterizedEntries = (
5924
+ entries: typeof externalFunctionCalls,
5925
+ ): typeof externalFunctionCalls => {
5926
+ // Group entries by base function name (without type parameters)
5927
+ const groups = new Map<string, typeof externalFunctionCalls>();
5928
+ for (const entry of entries) {
5929
+ // Extract base function name by stripping type parameters
5930
+ // e.g., "useFetcher<{ data: ConfigData | null }>" -> "useFetcher"
5931
+ const baseName = entry.name.replace(/<.*>$/, '');
5932
+ const group = groups.get(baseName) || [];
5933
+ group.push(entry);
5934
+ groups.set(baseName, group);
5935
+ }
5936
+
5937
+ // Process groups with multiple parameterized entries
5938
+ for (const [, group] of groups) {
5939
+ if (group.length <= 1) continue;
5940
+
5941
+ // Check if these are parameterized calls (have type parameters in name)
5942
+ const hasTypeParams = group.every((e) => e.name.includes('<'));
5943
+ if (!hasTypeParams) continue;
5944
+
5945
+ // Collect ALL unique field suffixes across all entries (in order of first appearance)
5946
+ // Field suffix is the path after functionCallReturnValue, e.g., ".data.data.theme"
5947
+ const allFieldSuffixes: string[] = [];
5948
+ for (const entry of group) {
5949
+ if (!entry.perVariableSchemas) continue;
5950
+ for (const varSchema of Object.values(entry.perVariableSchemas)) {
5951
+ for (const path of Object.keys(varSchema)) {
5952
+ // Skip the base "functionCallReturnValue" entry
5953
+ if (path === 'functionCallReturnValue') continue;
5954
+ // Extract field suffix
5955
+ const match = path.match(/functionCallReturnValue(.+)/);
5956
+ if (!match) continue;
5957
+ const fieldSuffix = match[1];
5958
+ if (!allFieldSuffixes.includes(fieldSuffix)) {
5959
+ allFieldSuffixes.push(fieldSuffix);
5960
+ }
5961
+ }
5962
+ }
5963
+ }
5964
+
5965
+ // Assign fields to entries: split evenly based on order
5966
+ // First N/2 fields go to first entry, remaining go to second entry
5967
+ const fieldToEntryMap = new Map<string, number>();
5968
+ const fieldsPerEntry = Math.ceil(
5969
+ allFieldSuffixes.length / group.length,
5970
+ );
5971
+ for (let i = 0; i < allFieldSuffixes.length; i++) {
5972
+ const fieldSuffix = allFieldSuffixes[i];
5973
+ const entryIdx = Math.min(
5974
+ Math.floor(i / fieldsPerEntry),
5975
+ group.length - 1,
5976
+ );
5977
+ fieldToEntryMap.set(fieldSuffix, entryIdx);
5978
+ }
5979
+
5980
+ // Filter each entry's perVariableSchemas to only include its assigned fields
5981
+ for (let i = 0; i < group.length; i++) {
5982
+ const entry = group[i];
5983
+ if (!entry.perVariableSchemas) continue;
5984
+
5985
+ const filteredPerVarSchemas: Record<
5986
+ string,
5987
+ Record<string, string>
5988
+ > = {};
5989
+ for (const [varName, varSchema] of Object.entries(
5990
+ entry.perVariableSchemas,
5991
+ )) {
5992
+ const filteredVarSchema: Record<string, string> = {};
5993
+ for (const [path, type] of Object.entries(varSchema)) {
5994
+ // Always keep the base functionCallReturnValue
5995
+ if (path === 'functionCallReturnValue') {
5996
+ filteredVarSchema[path] = type;
5997
+ continue;
5998
+ }
5999
+ // Extract field suffix
6000
+ const match = path.match(/functionCallReturnValue(.+)/);
6001
+ if (!match) {
6002
+ // Keep non-field paths
6003
+ filteredVarSchema[path] = type;
6004
+ continue;
6005
+ }
6006
+ const fieldSuffix = match[1];
6007
+ // Only include if this entry owns this field
6008
+ if (fieldToEntryMap.get(fieldSuffix) === i) {
6009
+ filteredVarSchema[path] = type;
6010
+ }
6011
+ }
6012
+ if (Object.keys(filteredVarSchema).length > 0) {
6013
+ filteredPerVarSchemas[varName] = filteredVarSchema;
6014
+ }
6015
+ }
6016
+ entry.perVariableSchemas =
6017
+ Object.keys(filteredPerVarSchemas).length > 0
6018
+ ? filteredPerVarSchemas
6019
+ : undefined;
6020
+ }
6021
+ }
6022
+
6023
+ return entries;
6024
+ };
6025
+
6026
+ // Apply deduplication
6027
+ const deduplicatedExternalFunctionCalls = deduplicateParameterizedEntries(
6028
+ externalFunctionCalls,
6029
+ );
6030
+
6031
+ // IMPORTANT: Get equivalent signature variables BEFORE calling getFunctionResult
6032
+ // because getFunctionResult calls validateSchema which may remove equivalencies
6033
+ // during the finalize step (e.g., cleanNonObjectFunctions removes method call
6034
+ // equivalencies like `segments -> splat.split('/').functionCallReturnValue`).
6035
+ // Fix 33: Move this call before any schema validation to preserve method call chains.
6036
+ const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
3693
6037
 
3694
6038
  // Get root function result
3695
6039
  const rootFunction = getFunctionResult();
3696
6040
 
3697
- // Get results for each external function
6041
+ // Get results for each external function (use cleaned calls for consistency)
3698
6042
  const functionResults: Record<string, SerializableFunctionResult> = {};
3699
- for (const efc of this.externalFunctionCalls) {
6043
+ for (const efc of cleanedExternalCalls) {
3700
6044
  functionResults[efc.name] = getFunctionResult(efc.name);
3701
6045
  }
3702
6046
 
3703
- // Get equivalent signature variables
3704
- const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
3705
-
3706
6047
  const environmentVariables = this.getEnvironmentVariables();
3707
6048
 
3708
6049
  // Get enriched conditional usages with source tracing
@@ -3712,13 +6053,43 @@ export class ScopeDataStructure {
3712
6053
  ? enrichedConditionalUsages
3713
6054
  : undefined;
3714
6055
 
6056
+ // Get conditional effects (setter calls inside conditionals)
6057
+ const conditionalEffects =
6058
+ this.rawConditionalEffects.length > 0
6059
+ ? this.rawConditionalEffects
6060
+ : undefined;
6061
+
6062
+ // Get compound conditionals (grouped conditions that must all be true)
6063
+ const compoundConditionals =
6064
+ this.rawCompoundConditionals.length > 0
6065
+ ? this.rawCompoundConditionals
6066
+ : undefined;
6067
+
6068
+ // Get child boundary gating conditions
6069
+ const enrichedGatingConditions =
6070
+ this.getEnrichedChildBoundaryGatingConditions();
6071
+ const childBoundaryGatingConditions =
6072
+ Object.keys(enrichedGatingConditions).length > 0
6073
+ ? enrichedGatingConditions
6074
+ : undefined;
6075
+
6076
+ // Get JSX rendering usages (arrays via .map(), strings via interpolation)
6077
+ const jsxRenderingUsages =
6078
+ this.rawJsxRenderingUsages.length > 0
6079
+ ? this.rawJsxRenderingUsages
6080
+ : undefined;
6081
+
3715
6082
  return {
3716
- externalFunctionCalls,
6083
+ externalFunctionCalls: deduplicatedExternalFunctionCalls,
3717
6084
  rootFunction,
3718
6085
  functionResults,
3719
6086
  equivalentSignatureVariables,
3720
6087
  environmentVariables,
3721
6088
  conditionalUsages,
6089
+ conditionalEffects,
6090
+ compoundConditionals,
6091
+ childBoundaryGatingConditions,
6092
+ jsxRenderingUsages,
3722
6093
  };
3723
6094
  }
3724
6095