@codeyam/codeyam-cli 0.1.0-staging.596f0eb → 0.1.0-staging.62d4615

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 (914) 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 +16 -12
  5. package/analyzer-template/packages/ai/index.ts +20 -5
  6. package/analyzer-template/packages/ai/package.json +3 -3
  7. package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
  8. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +214 -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 +1518 -125
  18. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +318 -5
  19. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
  20. package/analyzer-template/packages/ai/src/lib/completionCall.ts +216 -36
  21. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +2301 -348
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +7 -2
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +976 -0
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +243 -77
  25. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
  26. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
  27. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +71 -2
  28. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +161 -19
  29. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
  30. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +93 -1
  31. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  32. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
  33. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
  34. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +422 -86
  35. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
  36. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +156 -0
  37. package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
  38. package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
  39. package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
  40. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +74 -7
  41. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +89 -112
  42. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +63 -2
  43. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1394 -92
  44. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +216 -109
  45. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +578 -0
  46. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
  47. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +2267 -0
  48. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
  49. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
  50. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
  51. package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +328 -7
  52. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +111 -87
  53. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +17 -7
  54. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +1 -1
  55. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -102
  56. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
  57. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
  58. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +90 -6
  59. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +14 -53
  60. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.ts +58 -0
  61. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
  62. package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
  63. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +824 -0
  64. package/analyzer-template/packages/ai/src/lib/splitOutsideParentheses.ts +5 -1
  65. package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
  66. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +127 -3
  67. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +121 -2
  68. package/analyzer-template/packages/analyze/index.ts +2 -0
  69. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +79 -59
  70. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
  71. package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
  72. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
  73. package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
  74. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
  75. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
  76. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
  77. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
  78. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
  79. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
  80. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +522 -272
  81. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +34 -1
  82. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +6 -0
  83. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
  84. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
  85. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
  86. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +31 -15
  87. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +11 -7
  88. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +11 -12
  89. package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
  90. package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
  91. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +14 -12
  92. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1315 -0
  93. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +313 -0
  94. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
  95. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +625 -52
  96. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
  97. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +28 -62
  98. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +550 -137
  99. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +264 -0
  100. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +78 -83
  101. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +4 -8
  102. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +917 -130
  103. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
  104. package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
  105. package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
  106. package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
  107. package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
  108. package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
  109. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
  110. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
  111. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
  112. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
  113. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
  114. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
  115. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
  116. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  117. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
  118. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
  119. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
  120. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  121. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
  122. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
  123. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
  124. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
  125. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
  126. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
  127. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
  128. package/analyzer-template/packages/aws/package.json +3 -3
  129. package/analyzer-template/packages/aws/s3/index.ts +1 -0
  130. package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
  131. package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
  132. package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
  133. package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
  134. package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
  135. package/analyzer-template/packages/database/package.json +1 -1
  136. package/analyzer-template/packages/database/src/lib/kysely/db.ts +12 -5
  137. package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
  138. package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
  139. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +36 -9
  140. package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
  141. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
  142. package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
  143. package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
  144. package/analyzer-template/packages/database/src/lib/loadCommits.ts +28 -0
  145. package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
  146. package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
  147. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +7 -3
  148. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +7 -14
  149. package/analyzer-template/packages/generate/index.ts +3 -0
  150. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
  151. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
  152. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
  153. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
  154. package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
  155. package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
  156. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -2
  157. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  158. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +10 -3
  159. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  160. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
  161. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +1 -11
  162. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  163. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +1 -0
  164. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
  165. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
  166. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  167. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +30 -7
  168. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  169. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  170. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  171. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
  172. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
  173. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +2 -6
  174. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  175. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +2 -0
  176. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
  177. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
  178. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
  179. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  180. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
  181. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  182. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
  183. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
  184. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
  185. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
  186. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
  187. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
  188. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  189. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +22 -1
  190. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  191. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
  192. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  193. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
  194. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  195. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
  196. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
  197. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -1
  198. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  199. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +7 -4
  200. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  201. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +2 -2
  202. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  203. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +5 -4
  204. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  205. package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
  206. package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
  207. package/analyzer-template/packages/github/dist/generate/index.js +3 -0
  208. package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
  209. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  210. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  211. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  212. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
  213. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
  214. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  215. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  216. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
  217. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
  218. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  219. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  220. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  221. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  222. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  223. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
  224. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
  225. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
  226. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
  227. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
  228. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
  229. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  230. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
  231. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
  232. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
  233. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
  234. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
  235. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
  236. package/analyzer-template/packages/github/dist/types/index.d.ts +2 -2
  237. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  238. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  239. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +87 -13
  240. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  241. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts +2 -0
  242. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts.map +1 -1
  243. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
  244. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
  245. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +3 -0
  246. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  247. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +11 -6
  248. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  249. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
  250. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  251. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  252. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  253. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts +2 -0
  254. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  255. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  256. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  257. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  258. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
  259. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  260. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
  261. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
  262. package/analyzer-template/packages/github/package.json +1 -1
  263. package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
  264. package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
  265. package/analyzer-template/packages/process/index.ts +2 -0
  266. package/analyzer-template/packages/process/package.json +12 -0
  267. package/analyzer-template/packages/process/tsconfig.json +8 -0
  268. package/analyzer-template/packages/types/index.ts +5 -0
  269. package/analyzer-template/packages/types/src/types/Analysis.ts +104 -13
  270. package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
  271. package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
  272. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +1 -0
  273. package/analyzer-template/packages/types/src/types/Scenario.ts +11 -10
  274. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +228 -3
  275. package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
  276. package/analyzer-template/packages/types/src/types/StatementInfo.ts +2 -0
  277. package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
  278. package/analyzer-template/packages/utils/dist/types/index.d.ts +2 -2
  279. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  280. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  281. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +87 -13
  282. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  283. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts +2 -0
  284. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts.map +1 -1
  285. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
  286. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
  287. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +3 -0
  288. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  289. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +11 -6
  290. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  291. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
  292. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  293. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  294. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  295. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts +2 -0
  296. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  297. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  298. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  299. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  300. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
  301. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  302. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
  303. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
  304. package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
  305. package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
  306. package/analyzer-template/playwright/capture.ts +57 -26
  307. package/analyzer-template/playwright/captureStatic.ts +1 -1
  308. package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
  309. package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
  310. package/analyzer-template/playwright/takeScreenshot.ts +9 -7
  311. package/analyzer-template/playwright/waitForServer.ts +21 -6
  312. package/analyzer-template/project/analyzeBaselineCommit.ts +9 -0
  313. package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
  314. package/analyzer-template/project/analyzeFileEntities.ts +4 -0
  315. package/analyzer-template/project/analyzeRegularCommit.ts +9 -0
  316. package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
  317. package/analyzer-template/project/constructMockCode.ts +1268 -167
  318. package/analyzer-template/project/controller/startController.ts +16 -1
  319. package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
  320. package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
  321. package/analyzer-template/project/loadReadyToBeCaptured.ts +65 -41
  322. package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
  323. package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
  324. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +3 -6
  325. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +93 -42
  326. package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
  327. package/analyzer-template/project/orchestrateCapture.ts +81 -9
  328. package/analyzer-template/project/reconcileMockDataKeys.ts +245 -2
  329. package/analyzer-template/project/runAnalysis.ts +11 -0
  330. package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
  331. package/analyzer-template/project/serverOnlyModules.ts +194 -21
  332. package/analyzer-template/project/start.ts +61 -15
  333. package/analyzer-template/project/startScenarioCapture.ts +79 -41
  334. package/analyzer-template/project/writeMockDataTsx.ts +405 -65
  335. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  336. package/analyzer-template/project/writeScenarioComponents.ts +862 -183
  337. package/analyzer-template/project/writeScenarioFiles.ts +26 -0
  338. package/analyzer-template/project/writeSimpleRoot.ts +31 -23
  339. package/analyzer-template/scripts/comboWorkerLoop.cjs +99 -50
  340. package/analyzer-template/scripts/defaultCmd.sh +9 -0
  341. package/analyzer-template/tsconfig.json +2 -1
  342. package/background/src/lib/local/createLocalAnalyzer.js +1 -29
  343. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  344. package/background/src/lib/local/execAsync.js +1 -1
  345. package/background/src/lib/local/execAsync.js.map +1 -1
  346. package/background/src/lib/virtualized/common/execAsync.js +1 -1
  347. package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
  348. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +7 -1
  349. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
  350. package/background/src/lib/virtualized/project/analyzeBranchCommit.js +2 -1
  351. package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
  352. package/background/src/lib/virtualized/project/analyzeFileEntities.js +2 -1
  353. package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
  354. package/background/src/lib/virtualized/project/analyzeRegularCommit.js +7 -1
  355. package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
  356. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
  357. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
  358. package/background/src/lib/virtualized/project/constructMockCode.js +1126 -126
  359. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  360. package/background/src/lib/virtualized/project/controller/startController.js +11 -1
  361. package/background/src/lib/virtualized/project/controller/startController.js.map +1 -1
  362. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js +73 -1
  363. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js.map +1 -1
  364. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js +6 -3
  365. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js.map +1 -1
  366. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +19 -8
  367. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  368. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js +7 -7
  369. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js.map +1 -1
  370. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js +2 -2
  371. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js.map +1 -1
  372. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +3 -2
  373. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  374. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +73 -36
  375. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  376. package/background/src/lib/virtualized/project/orchestrateCapture.js +65 -10
  377. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  378. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +204 -2
  379. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  380. package/background/src/lib/virtualized/project/runAnalysis.js +9 -0
  381. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  382. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
  383. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  384. package/background/src/lib/virtualized/project/serverOnlyModules.js +163 -23
  385. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -1
  386. package/background/src/lib/virtualized/project/start.js +53 -15
  387. package/background/src/lib/virtualized/project/start.js.map +1 -1
  388. package/background/src/lib/virtualized/project/startScenarioCapture.js +61 -31
  389. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  390. package/background/src/lib/virtualized/project/writeMockDataTsx.js +354 -54
  391. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  392. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
  393. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
  394. package/background/src/lib/virtualized/project/writeScenarioComponents.js +624 -127
  395. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  396. package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
  397. package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
  398. package/background/src/lib/virtualized/project/writeSimpleRoot.js +31 -21
  399. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  400. package/codeyam-cli/scripts/apply-setup.js +180 -0
  401. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  402. package/codeyam-cli/src/cli.js +9 -1
  403. package/codeyam-cli/src/cli.js.map +1 -1
  404. package/codeyam-cli/src/commands/analyze.js +1 -1
  405. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  406. package/codeyam-cli/src/commands/baseline.js +174 -0
  407. package/codeyam-cli/src/commands/baseline.js.map +1 -0
  408. package/codeyam-cli/src/commands/debug.js +42 -18
  409. package/codeyam-cli/src/commands/debug.js.map +1 -1
  410. package/codeyam-cli/src/commands/default.js +0 -15
  411. package/codeyam-cli/src/commands/default.js.map +1 -1
  412. package/codeyam-cli/src/commands/memory.js +264 -0
  413. package/codeyam-cli/src/commands/memory.js.map +1 -0
  414. package/codeyam-cli/src/commands/recapture.js +226 -0
  415. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  416. package/codeyam-cli/src/commands/report.js +72 -24
  417. package/codeyam-cli/src/commands/report.js.map +1 -1
  418. package/codeyam-cli/src/commands/start.js +8 -12
  419. package/codeyam-cli/src/commands/start.js.map +1 -1
  420. package/codeyam-cli/src/commands/status.js +23 -1
  421. package/codeyam-cli/src/commands/status.js.map +1 -1
  422. package/codeyam-cli/src/commands/test-startup.js +1 -1
  423. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  424. package/codeyam-cli/src/commands/wipe.js +108 -0
  425. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  426. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
  427. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
  428. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +31 -27
  429. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  430. package/codeyam-cli/src/utils/analysisRunner.js +29 -15
  431. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  432. package/codeyam-cli/src/utils/backgroundServer.js +18 -4
  433. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  434. package/codeyam-cli/src/utils/database.js +91 -5
  435. package/codeyam-cli/src/utils/database.js.map +1 -1
  436. package/codeyam-cli/src/utils/generateReport.js +253 -106
  437. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  438. package/codeyam-cli/src/utils/git.js +79 -0
  439. package/codeyam-cli/src/utils/git.js.map +1 -0
  440. package/codeyam-cli/src/utils/install-skills.js +76 -17
  441. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  442. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  443. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  444. package/codeyam-cli/src/utils/queue/job.js +249 -16
  445. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  446. package/codeyam-cli/src/utils/queue/manager.js +25 -7
  447. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  448. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  449. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
  450. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
  451. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +128 -0
  452. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
  453. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
  454. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
  455. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
  456. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
  457. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
  458. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
  459. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
  460. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
  461. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +75 -0
  462. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
  463. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +285 -0
  464. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
  465. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +83 -0
  466. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
  467. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
  468. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
  469. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
  470. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
  471. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +96 -0
  472. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
  473. package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
  474. package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
  475. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +33 -0
  476. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
  477. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
  478. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
  479. package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
  480. package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
  481. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
  482. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
  483. package/codeyam-cli/src/utils/rules/index.js +6 -0
  484. package/codeyam-cli/src/utils/rules/index.js.map +1 -0
  485. package/codeyam-cli/src/utils/rules/parser.js +78 -0
  486. package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
  487. package/codeyam-cli/src/utils/rules/pathMatcher.js +18 -0
  488. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
  489. package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
  490. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
  491. package/codeyam-cli/src/utils/rules/staleness.js +137 -0
  492. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
  493. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  494. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +7 -5
  495. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  496. package/codeyam-cli/src/utils/versionInfo.js +25 -19
  497. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  498. package/codeyam-cli/src/utils/wipe.js +128 -0
  499. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  500. package/codeyam-cli/src/webserver/app/lib/database.js +104 -3
  501. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  502. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  503. package/codeyam-cli/src/webserver/backgroundServer.js +5 -10
  504. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  505. package/codeyam-cli/src/webserver/bootstrap.js +49 -0
  506. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  507. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-CA3JxPb7.js +1 -0
  508. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-B86KKU7e.js +11 -0
  509. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-efWKDYMr.js → EntityTypeBadge-B5ctlSYt.js} +1 -1
  510. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BqY8gDAW.js +41 -0
  511. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-ClaLpuOo.js +34 -0
  512. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-BDhPilK7.js +25 -0
  513. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-VeqEBv9v.js +3 -0
  514. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-Bs7Nn1Jr.js +6 -0
  515. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-Bm3PmcCz.js +3 -0
  516. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-C6PKeMYR.js +11 -0
  517. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-Gq3Ocjo6.js +1 -0
  518. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BNLaXBHR.js +10 -0
  519. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-COPstp9J.js → TruncatedFilePath-CiwXDxLh.js} +1 -1
  520. package/codeyam-cli/src/webserver/build/client/assets/_index-B3TDXxnk.js +11 -0
  521. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DD1r_QU0.js +27 -0
  522. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DfKzxuoe.js +11 -0
  523. package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
  524. package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
  525. package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
  526. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  527. package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
  528. package/codeyam-cli/src/webserver/build/client/assets/book-open-PttOB2SF.js +6 -0
  529. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-TJp6ofnp.js +6 -0
  530. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-JE9ZIoBl.js +51 -0
  531. package/codeyam-cli/src/webserver/build/client/assets/circle-check-CXhHQYrI.js +6 -0
  532. package/codeyam-cli/src/webserver/build/client/assets/copy-6y9ALfGT.js +11 -0
  533. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-Ca9fAY46.js +21 -0
  534. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
  535. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
  536. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-C5lqplTC.js +1 -0
  537. package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-n38keI1k.js +23 -0
  538. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-CBoafmVs.js +6 -0
  539. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-DGgZjdFg.js +6 -0
  540. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-38yPijoD.js +5 -0
  541. package/codeyam-cli/src/webserver/build/client/assets/entry.client-BSHEfydn.js +29 -0
  542. package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
  543. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-DCPhhSMo.js +1 -0
  544. package/codeyam-cli/src/webserver/build/client/assets/files-Dk8wkAS7.js +1 -0
  545. package/codeyam-cli/src/webserver/build/client/assets/git-DXnyr8uP.js +15 -0
  546. package/codeyam-cli/src/webserver/build/client/assets/globals-Bh6jH0cL.css +1 -0
  547. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  548. package/codeyam-cli/src/webserver/build/client/assets/index-CcsFv748.js +3 -0
  549. package/codeyam-cli/src/webserver/build/client/assets/index-ChN9-fAY.js +9 -0
  550. package/codeyam-cli/src/webserver/build/client/assets/labs-BUvfJMNR.js +1 -0
  551. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-CTqLEAGU.js +6 -0
  552. package/codeyam-cli/src/webserver/build/client/assets/manifest-d4e77269.js +1 -0
  553. package/codeyam-cli/src/webserver/build/client/assets/memory-DCHBwHou.js +76 -0
  554. package/codeyam-cli/src/webserver/build/client/assets/pause-D6vreykR.js +11 -0
  555. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  556. package/codeyam-cli/src/webserver/build/client/assets/root-D6oziHts.js +62 -0
  557. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  558. package/codeyam-cli/src/webserver/build/client/assets/search-B8VUL8nl.js +6 -0
  559. package/codeyam-cli/src/webserver/build/client/assets/settings-B2X7lJgQ.js +1 -0
  560. package/codeyam-cli/src/webserver/build/client/assets/simulations-CPoAg7Zo.js +1 -0
  561. package/codeyam-cli/src/webserver/build/client/assets/terminal-BrCP7uQo.js +11 -0
  562. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-BZz2NjYa.js +6 -0
  563. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-DNwUduNu.js +1 -0
  564. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-3pmpUQB-.js → useLastLogLine-COky1GVF.js} +1 -1
  565. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-CpZgwliL.js +1 -0
  566. package/codeyam-cli/src/webserver/build/client/assets/{useToast-DEyawJ8r.js → useToast-Bv9JFvUO.js} +1 -1
  567. package/codeyam-cli/src/webserver/build/server/assets/index-C0KrUQp-.js +1 -0
  568. package/codeyam-cli/src/webserver/build/server/assets/server-build-C2h1v1XD.js +260 -0
  569. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  570. package/codeyam-cli/src/webserver/build-info.json +5 -5
  571. package/codeyam-cli/src/webserver/devServer.js +1 -3
  572. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  573. package/codeyam-cli/src/webserver/server.js +35 -25
  574. package/codeyam-cli/src/webserver/server.js.map +1 -1
  575. package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
  576. package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam:debug.md} +48 -4
  577. package/codeyam-cli/templates/codeyam:diagnose.md +803 -0
  578. package/codeyam-cli/templates/codeyam:memory.md +404 -0
  579. package/codeyam-cli/templates/codeyam:new-rule.md +13 -0
  580. package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam:setup.md} +139 -4
  581. package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam:sim.md} +1 -1
  582. package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam:test.md} +1 -1
  583. package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam:verify.md} +1 -1
  584. package/codeyam-cli/templates/rule-notification-hook.py +54 -0
  585. package/codeyam-cli/templates/rule-reflection-hook.py +428 -0
  586. package/codeyam-cli/templates/rules-instructions.md +123 -0
  587. package/package.json +22 -19
  588. package/packages/ai/index.js +8 -6
  589. package/packages/ai/index.js.map +1 -1
  590. package/packages/ai/src/lib/analyzeScope.js +167 -13
  591. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  592. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  593. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  594. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +154 -9
  595. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  596. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
  597. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
  598. package/packages/ai/src/lib/astScopes/methodSemantics.js +138 -23
  599. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  600. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
  601. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
  602. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
  603. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
  604. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +23 -0
  605. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  606. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
  607. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  608. package/packages/ai/src/lib/astScopes/processExpression.js +1157 -103
  609. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  610. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  611. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  612. package/packages/ai/src/lib/completionCall.js +178 -31
  613. package/packages/ai/src/lib/completionCall.js.map +1 -1
  614. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1816 -216
  615. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  616. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +7 -2
  617. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  618. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +661 -0
  619. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  620. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +180 -56
  621. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  622. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  623. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  624. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  625. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  626. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +66 -2
  627. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  628. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +139 -13
  629. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  630. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
  631. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
  632. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +83 -1
  633. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  634. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  635. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  636. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
  637. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  638. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  639. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  640. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +355 -77
  641. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  642. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  643. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  644. package/packages/ai/src/lib/dataStructureChunking.js +111 -0
  645. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  646. package/packages/ai/src/lib/deepEqual.js +32 -0
  647. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  648. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  649. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  650. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  651. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  652. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
  653. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  654. package/packages/ai/src/lib/generateChangesEntityScenarios.js +81 -90
  655. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  656. package/packages/ai/src/lib/generateEntityDataStructure.js +50 -1
  657. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  658. package/packages/ai/src/lib/generateEntityScenarioData.js +1109 -85
  659. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  660. package/packages/ai/src/lib/generateEntityScenarios.js +193 -83
  661. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  662. package/packages/ai/src/lib/generateExecutionFlows.js +400 -0
  663. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
  664. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
  665. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
  666. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1646 -0
  667. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
  668. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  669. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  670. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  671. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  672. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  673. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  674. package/packages/ai/src/lib/isolateScopes.js +270 -7
  675. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  676. package/packages/ai/src/lib/mergeStatements.js +88 -46
  677. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  678. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +16 -4
  679. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  680. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
  681. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  682. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -64
  683. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  684. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  685. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  686. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +68 -6
  687. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  688. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -34
  689. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  690. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
  691. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
  692. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  693. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  694. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  695. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  696. package/packages/ai/src/lib/resolvePathToControllable.js +677 -0
  697. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
  698. package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
  699. package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
  700. package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
  701. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  702. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +98 -1
  703. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  704. package/packages/analyze/index.js +1 -0
  705. package/packages/analyze/index.js.map +1 -1
  706. package/packages/analyze/src/lib/FileAnalyzer.js +75 -36
  707. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  708. package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
  709. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  710. package/packages/analyze/src/lib/analysisContext.js +30 -5
  711. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  712. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  713. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  714. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  715. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  716. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  717. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  718. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  719. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  720. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  721. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  722. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  723. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  724. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  725. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  726. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  727. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  728. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +268 -52
  729. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  730. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +24 -1
  731. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  732. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
  733. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  734. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  735. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  736. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  737. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  738. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
  739. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  740. package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
  741. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  742. package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
  743. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  744. package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
  745. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  746. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  747. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  748. package/packages/analyze/src/lib/files/enums/steps.js +1 -1
  749. package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
  750. package/packages/analyze/src/lib/files/getImportedExports.js +11 -7
  751. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  752. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
  753. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
  754. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +255 -0
  755. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  756. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  757. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  758. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +483 -48
  759. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  760. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  761. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  762. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
  763. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  764. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +404 -85
  765. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  766. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +144 -0
  767. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
  768. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +56 -69
  769. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  770. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +4 -8
  771. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  772. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +768 -117
  773. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  774. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  775. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  776. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  777. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  778. package/packages/analyze/src/lib/index.js +1 -0
  779. package/packages/analyze/src/lib/index.js.map +1 -1
  780. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  781. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  782. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  783. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  784. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  785. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  786. package/packages/database/src/lib/kysely/db.js +10 -3
  787. package/packages/database/src/lib/kysely/db.js.map +1 -1
  788. package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
  789. package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  790. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  791. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  792. package/packages/database/src/lib/loadAnalyses.js +45 -2
  793. package/packages/database/src/lib/loadAnalyses.js.map +1 -1
  794. package/packages/database/src/lib/loadAnalysis.js +8 -0
  795. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  796. package/packages/database/src/lib/loadBranch.js +11 -1
  797. package/packages/database/src/lib/loadBranch.js.map +1 -1
  798. package/packages/database/src/lib/loadCommit.js +7 -0
  799. package/packages/database/src/lib/loadCommit.js.map +1 -1
  800. package/packages/database/src/lib/loadCommits.js +22 -1
  801. package/packages/database/src/lib/loadCommits.js.map +1 -1
  802. package/packages/database/src/lib/loadEntities.js +23 -4
  803. package/packages/database/src/lib/loadEntities.js.map +1 -1
  804. package/packages/database/src/lib/loadEntityBranches.js +9 -0
  805. package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
  806. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +7 -4
  807. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  808. package/packages/database/src/lib/updateCommitMetadata.js +5 -4
  809. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  810. package/packages/generate/index.js +3 -0
  811. package/packages/generate/index.js.map +1 -1
  812. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  813. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  814. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  815. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  816. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  817. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  818. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  819. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  820. package/packages/generate/src/lib/deepMerge.js +27 -1
  821. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  822. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  823. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  824. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  825. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  826. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  827. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  828. package/packages/process/index.js +3 -0
  829. package/packages/process/index.js.map +1 -0
  830. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  831. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  832. package/packages/process/src/ProcessManager.js.map +1 -0
  833. package/packages/process/src/index.js.map +1 -0
  834. package/packages/process/src/managedExecAsync.js.map +1 -0
  835. package/packages/types/index.js.map +1 -1
  836. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  837. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  838. package/packages/utils/src/lib/safeFileName.js +29 -3
  839. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  840. package/scripts/finalize-analyzer.cjs +6 -4
  841. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
  842. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -197
  843. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -271
  844. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -294
  845. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
  846. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -115
  847. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  848. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  849. package/analyzer-template/process/README.md +0 -507
  850. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  851. package/background/src/lib/process/ProcessManager.js.map +0 -1
  852. package/background/src/lib/process/index.js.map +0 -1
  853. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  854. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  855. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  856. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-CVbSvOjo.js +0 -1
  857. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-DcwcHyl5.js +0 -1
  858. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-WgwC1GfJ.js +0 -26
  859. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-IEKom9O2.js +0 -3
  860. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-BYnfxbUG.js +0 -3
  861. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-_lBPJCzG.js +0 -1
  862. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-lHVhvsu_.js +0 -1
  863. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-d_TBk4GQ.js +0 -5
  864. package/codeyam-cli/src/webserver/build/client/assets/_index-kGT7VUqj.js +0 -1
  865. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DDGmhu7P.js +0 -7
  866. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-n_HPRfM_.js +0 -1
  867. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CbVoyx1U.js +0 -26
  868. package/codeyam-cli/src/webserver/build/client/assets/circle-check-D1VOYveA.js +0 -1
  869. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-YR8jjAlu.js +0 -1
  870. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-B8vP3V_s.js +0 -1
  871. package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-CN6aLCT1.js +0 -16
  872. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-DA5Jeu2P.js +0 -1
  873. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-BTeitalf.js +0 -5
  874. package/codeyam-cli/src/webserver/build/client/assets/entry.client-du6UEYD-.js +0 -13
  875. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-BpjkhMoi.js +0 -1
  876. package/codeyam-cli/src/webserver/build/client/assets/files-BQGvk4lJ.js +0 -1
  877. package/codeyam-cli/src/webserver/build/client/assets/git-DVdYRT-I.js +0 -12
  878. package/codeyam-cli/src/webserver/build/client/assets/globals-CO-U8Bpo.css +0 -1
  879. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  880. package/codeyam-cli/src/webserver/build/client/assets/index-DCG-vks0.js +0 -1
  881. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-GazdNeLl.js +0 -1
  882. package/codeyam-cli/src/webserver/build/client/assets/manifest-0b694d28.js +0 -1
  883. package/codeyam-cli/src/webserver/build/client/assets/root-D3tQP7hx.js +0 -16
  884. package/codeyam-cli/src/webserver/build/client/assets/search-CIY6XmtE.js +0 -1
  885. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  886. package/codeyam-cli/src/webserver/build/client/assets/settings-CoMDgElu.js +0 -1
  887. package/codeyam-cli/src/webserver/build/client/assets/simulations-agkniXp2.js +0 -1
  888. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-B2VUcygF.js +0 -1
  889. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-EvdK-zXP.js +0 -1
  890. package/codeyam-cli/src/webserver/build/server/assets/index-DGVHQEXD.js +0 -1
  891. package/codeyam-cli/src/webserver/build/server/assets/server-build-CghkTkIL.js +0 -166
  892. package/codeyam-cli/templates/debug-command.md +0 -303
  893. package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
  894. package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
  895. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -136
  896. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
  897. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -220
  898. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
  899. package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -241
  900. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
  901. package/packages/ai/src/lib/isFrontend.js +0 -5
  902. package/packages/ai/src/lib/isFrontend.js.map +0 -1
  903. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
  904. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
  905. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -72
  906. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
  907. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  908. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  909. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  910. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  911. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
  912. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  913. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  914. /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([
@@ -360,10 +424,40 @@ export class ScopeDataStructure {
360
424
  path: string;
361
425
  conditionType: 'truthiness' | 'comparison' | 'switch';
362
426
  comparedValues?: string[];
363
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
427
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
364
428
  }>
365
429
  > = {};
366
430
 
431
+ /**
432
+ * Conditional effects collected during AST analysis.
433
+ * Tracks what setter calls happen inside conditionals (if, switch, ternary).
434
+ */
435
+ private rawConditionalEffects: import('../astScopes/types').ConditionalEffect[] =
436
+ [];
437
+
438
+ /**
439
+ * Compound conditionals collected during AST analysis.
440
+ * Groups conditions that must all be true together (e.g., a && b && c).
441
+ */
442
+ private rawCompoundConditionals: import('../astScopes/types').CompoundConditional[] =
443
+ [];
444
+
445
+ /**
446
+ * Gating conditions for child component boundaries.
447
+ * Maps child component name to the conditions that must be true for it to render.
448
+ */
449
+ private rawChildBoundaryGatingConditions: Record<
450
+ string,
451
+ import('../astScopes/types').ConditionalUsage[]
452
+ > = {};
453
+
454
+ /**
455
+ * JSX rendering usages collected during AST analysis.
456
+ * Tracks arrays rendered via .map() and strings interpolated in JSX.
457
+ */
458
+ private rawJsxRenderingUsages: import('../astScopes/types').JsxRenderingUsage[] =
459
+ [];
460
+
367
461
  private lastAddToSchemaId = 0;
368
462
  private lastEquivalencyId = 0;
369
463
  private lastEquivalencyDatabaseId = 0;
@@ -382,6 +476,10 @@ export class ScopeDataStructure {
382
476
  private externalFunctionCallsIndex: Map<string, FunctionCallInfo> | null =
383
477
  null;
384
478
 
479
+ // Tracks internal functions that have been filtered out during captureCompleteSchema
480
+ // Prevents re-adding them via subsequent equivalency propagation (e.g., from getReturnValue)
481
+ private filteredInternalFunctions: Set<string> = new Set();
482
+
385
483
  // Debug tracer for selective path/scope tracing
386
484
  // Enable via: CODEYAM_DEBUG=true CODEYAM_DEBUG_PATHS="user.*,signature" npm test
387
485
  private tracer: DebugTracer = new DebugTracer({
@@ -540,6 +638,8 @@ export class ScopeDataStructure {
540
638
  const efcName = this.pathManager.stripGenerics(efc.name);
541
639
  for (const manager of this.equivalencyManagers) {
542
640
  if (manager.internalFunctions.has(efcName)) {
641
+ // Track this so we don't re-add it via subsequent finalize calls
642
+ this.filteredInternalFunctions.add(efcName);
543
643
  return false;
544
644
  }
545
645
  }
@@ -567,13 +667,51 @@ export class ScopeDataStructure {
567
667
  const baseName = this.pathManager.stripGenerics(
568
668
  candidate.scopeNodeName,
569
669
  );
670
+ // Check if this is a local variable path (doesn't contain function call pattern)
671
+ // Local variables like "surveys[]" or "items[]" are important for tracing data flow
672
+ // from parent to child components (e.g., surveys[] -> SurveyCard().signature[0].survey)
673
+ const isLocalVariablePath =
674
+ !candidate.schemaPath.includes('()') &&
675
+ !candidate.schemaPath.startsWith('signature[') &&
676
+ !candidate.schemaPath.startsWith('returnValue');
677
+
570
678
  return (
571
679
  validExternalFacingScopeNames.has(baseName) &&
572
680
  (candidate.schemaPath.startsWith('signature[') ||
573
- candidate.schemaPath.startsWith(baseName)) &&
681
+ candidate.schemaPath.startsWith(baseName) ||
682
+ isLocalVariablePath) &&
574
683
  !containsArrayMethod(candidate.schemaPath)
575
684
  );
576
685
  });
686
+
687
+ // If all sourceCandidates were filtered out (e.g., because they belonged to
688
+ // internal functions like useState), look for the highest-order intermediate
689
+ // that belongs to a valid external-facing scope
690
+ if (
691
+ entry.sourceCandidates.length === 0 &&
692
+ Object.keys(entry.intermediatesOrder).length > 0
693
+ ) {
694
+ // Find intermediates that belong to valid external-facing scopes
695
+ const validIntermediates = Object.entries(entry.intermediatesOrder)
696
+ .filter(([pathId]) => {
697
+ const [scopeNodeName, schemaPath] = pathId.split('::');
698
+ if (!scopeNodeName || !schemaPath) return false;
699
+ const baseName = this.pathManager.stripGenerics(scopeNodeName);
700
+ return (
701
+ validExternalFacingScopeNames.has(baseName) &&
702
+ !containsArrayMethod(schemaPath)
703
+ );
704
+ })
705
+ .sort((a, b) => b[1] - a[1]); // Sort by order descending (highest first)
706
+
707
+ if (validIntermediates.length > 0) {
708
+ const [pathId] = validIntermediates[0];
709
+ const [scopeNodeName, schemaPath] = pathId.split('::');
710
+ if (scopeNodeName && schemaPath) {
711
+ entry.sourceCandidates.push({ scopeNodeName, schemaPath });
712
+ }
713
+ }
714
+ }
577
715
  }
578
716
 
579
717
  this.propagateSourceAndUsageEquivalencies(
@@ -661,6 +799,11 @@ export class ScopeDataStructure {
661
799
  return;
662
800
  }
663
801
 
802
+ // PERF: Early exit for paths with repeated function-call signature patterns
803
+ if (this.hasExcessivePatternRepetition(path)) {
804
+ return;
805
+ }
806
+
664
807
  // Update chain metadata for database tracking
665
808
  if (equivalencyValueChain.length > 0) {
666
809
  equivalencyValueChain[equivalencyValueChain.length - 1].addToSchemaId =
@@ -904,8 +1047,8 @@ export class ScopeDataStructure {
904
1047
  equivalencyValueChain?: EquivalencyValueChainItem[],
905
1048
  traceId?: number,
906
1049
  ) {
907
- // DEBUG: Detect infinite loops
908
1050
  addEquivalencyCallCount++;
1051
+
909
1052
  if (addEquivalencyCallCount > 50000) {
910
1053
  console.error('INFINITE LOOP DETECTED in addEquivalency', {
911
1054
  callCount: addEquivalencyCallCount,
@@ -1151,10 +1294,38 @@ export class ScopeDataStructure {
1151
1294
  const existingFunctionCall =
1152
1295
  this.getExternalFunctionCallsIndex().get(searchKey);
1153
1296
  if (existingFunctionCall) {
1154
- existingFunctionCall.schema = {
1297
+ // Preserve per-call schemas BEFORE merging to enable per-variable mock data.
1298
+ // This is critical for hooks like useFetcher<UserData>() vs useFetcher<ReportData>()
1299
+ // where each call returns different typed data.
1300
+ if (!existingFunctionCall.perCallSignatureSchemas) {
1301
+ // First merge - save the existing call's schema
1302
+ existingFunctionCall.perCallSignatureSchemas = {
1303
+ [existingFunctionCall.callSignature]: {
1304
+ ...existingFunctionCall.schema,
1305
+ },
1306
+ };
1307
+ }
1308
+ // Save the new call's schema before it gets merged
1309
+ existingFunctionCall.perCallSignatureSchemas[
1310
+ functionCallInfo.callSignature
1311
+ ] = { ...functionCallInfo.schema };
1312
+
1313
+ // Merge schemas using selectBestValue to preserve specific types like 'null'
1314
+ // over generic types like 'unknown'. This ensures ref variables detected
1315
+ // earlier (marked as 'null') aren't overwritten by later 'unknown' values.
1316
+ const mergedSchema: Record<string, string> = {
1155
1317
  ...existingFunctionCall.schema,
1156
- ...functionCallInfo.schema,
1157
1318
  };
1319
+ for (const key in functionCallInfo.schema) {
1320
+ const existingValue = existingFunctionCall.schema[key];
1321
+ const newValue = functionCallInfo.schema[key];
1322
+ mergedSchema[key] = selectBestValue(
1323
+ existingValue,
1324
+ newValue,
1325
+ newValue,
1326
+ );
1327
+ }
1328
+ existingFunctionCall.schema = mergedSchema;
1158
1329
 
1159
1330
  existingFunctionCall.equivalencies = {
1160
1331
  ...existingFunctionCall.equivalencies,
@@ -1187,8 +1358,15 @@ export class ScopeDataStructure {
1187
1358
  );
1188
1359
 
1189
1360
  if (isExternal) {
1190
- this.externalFunctionCalls.push(functionCallInfo);
1191
- this.invalidateExternalFunctionCallsIndex();
1361
+ // Check if this function was already filtered out as an internal function
1362
+ // (e.g., useState was filtered in captureCompleteSchema but finalize is trying to re-add it)
1363
+ const strippedName = this.pathManager.stripGenerics(
1364
+ functionCallInfo.name,
1365
+ );
1366
+ if (!this.filteredInternalFunctions.has(strippedName)) {
1367
+ this.externalFunctionCalls.push(functionCallInfo);
1368
+ this.invalidateExternalFunctionCallsIndex();
1369
+ }
1192
1370
  }
1193
1371
  }
1194
1372
  }
@@ -1296,11 +1474,32 @@ export class ScopeDataStructure {
1296
1474
  const equivalentSchemaPath = equivalentSchemaPathMap.get(remainingKey);
1297
1475
 
1298
1476
  if (equivalentSchemaPath) {
1477
+ // Skip propagation when there's a structural mismatch:
1478
+ // - schemaPath ends with [] (array element, represents an object)
1479
+ // - equivalentSchemaPath doesn't end with [] (non-array prop, usually a scalar)
1480
+ // This prevents incorrectly typing array elements as strings when they're
1481
+ // equivalent to scalar props like JSX keys (e.g., workouts[] ↔ Card().key)
1482
+ const schemaPathEndsWithArray = schemaPath.endsWith('[]');
1483
+ const equivalentEndsWithArray = equivalentSchemaPath.endsWith('[]');
1484
+ if (schemaPathEndsWithArray !== equivalentEndsWithArray) {
1485
+ // Don't propagate between array element paths and non-array paths
1486
+ continue;
1487
+ }
1488
+
1299
1489
  const value1 = scopeNode.schema[schemaPath];
1300
1490
  const value2 = equivalentScopeNode.schema[equivalentSchemaPath];
1301
1491
 
1302
1492
  const bestValue = selectBestValue(value1, value2);
1303
1493
 
1494
+ // PERF: Skip paths with repeated function-call signature patterns
1495
+ // to prevent recursive type expansion (e.g., string.localeCompare returns string)
1496
+ if (
1497
+ this.hasExcessivePatternRepetition(schemaPath) ||
1498
+ this.hasExcessivePatternRepetition(equivalentSchemaPath)
1499
+ ) {
1500
+ continue;
1501
+ }
1502
+
1304
1503
  scopeNode.schema[schemaPath] = bestValue;
1305
1504
  equivalentScopeNode.schema[equivalentSchemaPath] = bestValue;
1306
1505
  } else if (
@@ -1314,6 +1513,11 @@ export class ScopeDataStructure {
1314
1513
  ...remainingSchemaPathParts,
1315
1514
  ]);
1316
1515
 
1516
+ // PERF: Skip paths with repeated function-call signature patterns
1517
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
1518
+ continue;
1519
+ }
1520
+
1317
1521
  equivalentScopeNode.schema[newEquivalentPath] =
1318
1522
  scopeNode.schema[schemaPath];
1319
1523
  }
@@ -1404,6 +1608,77 @@ export class ScopeDataStructure {
1404
1608
  return this.pathManager.isValidPath(path);
1405
1609
  }
1406
1610
 
1611
+ /**
1612
+ * Detects if a path contains excessive repetition of the same pattern.
1613
+ *
1614
+ * This prevents exponential blowup when analyzing recursive type structures.
1615
+ * For example, TypeScript AST nodes have `.attributes.properties[]` where each
1616
+ * property is also a node with `.attributes.properties[]`. Without this check,
1617
+ * paths like `signature[0].attributes.properties[].attributes.properties[].attributes.properties[]...`
1618
+ * would be generated exponentially.
1619
+ *
1620
+ * Two detection strategies:
1621
+ * 1. Known patterns: Check RECURSIVE_PATH_PATTERNS for common recursive structures
1622
+ * 2. Generic detection: For longer paths, detect any 2-3 part segment that repeats
1623
+ *
1624
+ * @param path - The schema path to check
1625
+ * @param maxRepetitions - Maximum allowed repetitions of any pattern (default: 2)
1626
+ * @returns true if the path has excessive repetition
1627
+ */
1628
+ private hasExcessivePatternRepetition(
1629
+ path: string,
1630
+ maxRepetitions = 2,
1631
+ ): boolean {
1632
+ // Check known recursive patterns
1633
+ for (const pattern of RECURSIVE_PATH_PATTERNS) {
1634
+ const matches = path.match(pattern);
1635
+ if (matches && matches.length > maxRepetitions) {
1636
+ return true;
1637
+ }
1638
+ }
1639
+
1640
+ // Check for repeated function calls that indicate recursive type expansion.
1641
+ // E.g., localeCompare(b[])...localeCompare(b[]) means string.localeCompare
1642
+ // returns a type that again has localeCompare, causing infinite expansion.
1643
+ // We extract all function call patterns like "funcName(args)" and check if
1644
+ // the same normalized call appears more than once.
1645
+ const funcCallPattern = /(?:^|\.)[^.([]+\([^)]*\)/g;
1646
+ const funcCallMatches = path.match(funcCallPattern);
1647
+ if (funcCallMatches && funcCallMatches.length > 1) {
1648
+ const seen = new Set<string>();
1649
+ for (const match of funcCallMatches) {
1650
+ // Strip leading dot and normalize array indices
1651
+ const normalized = match.replace(/^\./, '').replace(/\[\d+\]/g, '[]');
1652
+ if (seen.has(normalized)) return true;
1653
+ seen.add(normalized);
1654
+ }
1655
+ }
1656
+
1657
+ // For longer paths, detect any repeated multi-part segments we haven't explicitly listed
1658
+ const pathParts = this.splitPath(path);
1659
+ if (pathParts.length <= 6) {
1660
+ return false;
1661
+ }
1662
+
1663
+ // Check for repeated sequences of 2-3 consecutive parts
1664
+ for (let segmentLength = 2; segmentLength <= 3; segmentLength++) {
1665
+ const seen = new Map<string, number>();
1666
+
1667
+ for (let i = 0; i <= pathParts.length - segmentLength; i++) {
1668
+ const segment = pathParts.slice(i, i + segmentLength).join('.');
1669
+ const normalizedSegment = segment.replace(/\[\d+\]/g, '[]');
1670
+ const count = (seen.get(normalizedSegment) || 0) + 1;
1671
+ seen.set(normalizedSegment, count);
1672
+
1673
+ if (count > maxRepetitions) {
1674
+ return true;
1675
+ }
1676
+ }
1677
+ }
1678
+
1679
+ return false;
1680
+ }
1681
+
1407
1682
  private addToTree(pathParts: string[]) {
1408
1683
  this.scopeTreeManager.addPath(pathParts);
1409
1684
  }
@@ -1411,17 +1686,26 @@ export class ScopeDataStructure {
1411
1686
  private setInstantiatedVariables(scopeNode: ScopeNode) {
1412
1687
  let instantiatedVariables = scopeNode.analysis?.instantiatedVariables ?? [];
1413
1688
 
1414
- for (const [path, equivalentPath] of Object.entries(
1689
+ for (const [path, rawEquivalentPath] of Object.entries(
1415
1690
  scopeNode.analysis.isolatedEquivalentVariables ?? {},
1416
1691
  )) {
1417
- if (typeof equivalentPath !== 'string') {
1418
- continue;
1419
- }
1692
+ // Normalize to array for consistent handling (supports both string and string[])
1693
+ const equivalentPaths = Array.isArray(rawEquivalentPath)
1694
+ ? rawEquivalentPath
1695
+ : rawEquivalentPath
1696
+ ? [rawEquivalentPath]
1697
+ : [];
1698
+
1699
+ for (const equivalentPath of equivalentPaths) {
1700
+ if (typeof equivalentPath !== 'string') {
1701
+ continue;
1702
+ }
1420
1703
 
1421
- if (equivalentPath.startsWith('signature[')) {
1422
- const equivalentPathParts = this.splitPath(equivalentPath);
1423
- instantiatedVariables.push(equivalentPathParts[0]);
1424
- instantiatedVariables.push(path);
1704
+ if (equivalentPath.startsWith('signature[')) {
1705
+ const equivalentPathParts = this.splitPath(equivalentPath);
1706
+ instantiatedVariables.push(equivalentPathParts[0]);
1707
+ instantiatedVariables.push(path);
1708
+ }
1425
1709
  }
1426
1710
 
1427
1711
  const duplicateInstantiated = instantiatedVariables.find(
@@ -1434,9 +1718,14 @@ export class ScopeDataStructure {
1434
1718
  }
1435
1719
  }
1436
1720
 
1437
- instantiatedVariables = instantiatedVariables.filter(
1438
- (varName, index, self) => self.indexOf(varName) === index,
1439
- );
1721
+ const instantiatedSeen = new Set<string>();
1722
+ instantiatedVariables = instantiatedVariables.filter((varName) => {
1723
+ if (instantiatedSeen.has(varName)) {
1724
+ return false;
1725
+ }
1726
+ instantiatedSeen.add(varName);
1727
+ return true;
1728
+ });
1440
1729
 
1441
1730
  scopeNode.instantiatedVariables = instantiatedVariables;
1442
1731
 
@@ -1457,13 +1746,19 @@ export class ScopeDataStructure {
1457
1746
  ...parentScopeNode.instantiatedVariables.filter(
1458
1747
  (v) => !v.startsWith('signature[') && !v.startsWith('returnValue'),
1459
1748
  ),
1460
- ].filter(
1461
- (varName, index, self) =>
1462
- !instantiatedVariables.includes(varName) &&
1463
- self.indexOf(varName) === index,
1464
- );
1749
+ ].filter((varName) => !instantiatedSeen.has(varName));
1750
+
1751
+ const parentInstantiatedSeen = new Set<string>();
1752
+ const dedupedParentInstantiatedVariables =
1753
+ parentInstantiatedVariables.filter((varName) => {
1754
+ if (parentInstantiatedSeen.has(varName)) {
1755
+ return false;
1756
+ }
1757
+ parentInstantiatedSeen.add(varName);
1758
+ return true;
1759
+ });
1465
1760
 
1466
- scopeNode.parentInstantiatedVariables = parentInstantiatedVariables;
1761
+ scopeNode.parentInstantiatedVariables = dedupedParentInstantiatedVariables;
1467
1762
  }
1468
1763
 
1469
1764
  private trackFunctionCalls(scopeNode: ScopeNode) {
@@ -1472,197 +1767,205 @@ export class ScopeDataStructure {
1472
1767
  }
1473
1768
 
1474
1769
  private determineEquivalenciesAndBuildSchema(scopeNode: ScopeNode) {
1770
+ if (!scopeNode.analysis) {
1771
+ return;
1772
+ }
1773
+
1475
1774
  const { isolatedStructure, isolatedEquivalentVariables } =
1476
1775
  scopeNode.analysis;
1477
1776
 
1478
- // DEBUG: Log all equivalencies related to useFetcher
1479
- if (
1480
- Object.keys(isolatedEquivalentVariables || {}).some(
1481
- (k) => k.includes('Fetcher') || k.includes('fetcher'),
1482
- )
1483
- ) {
1484
- console.log(
1485
- 'CodeYam DEBUG determineEquivalenciesAndBuildSchema:',
1486
- JSON.stringify(
1487
- {
1488
- scopeNodeName: scopeNode.name,
1489
- fetcherEquivalencies: Object.entries(
1490
- isolatedEquivalentVariables || {},
1491
- )
1492
- .filter(
1493
- ([k, v]) =>
1494
- k.includes('Fetcher') ||
1495
- k.includes('fetcher') ||
1496
- String(v).includes('Fetcher') ||
1497
- String(v).includes('fetcher'),
1498
- )
1499
- .reduce(
1500
- (acc, [k, v]) => {
1501
- acc[k] = v;
1502
- return acc;
1503
- },
1504
- {} as Record<string, string>,
1505
- ),
1506
- },
1507
- null,
1508
- 2,
1509
- ),
1510
- );
1511
- }
1777
+ // Flatten isolatedEquivalentVariables values for allPaths (handles both string and string[])
1778
+ const flattenedEquivValues = Object.values(
1779
+ isolatedEquivalentVariables || {},
1780
+ ).flatMap((v) => (Array.isArray(v) ? v : [v]));
1512
1781
 
1513
1782
  const allPaths = Array.from(
1514
1783
  new Set([
1515
1784
  ...Object.keys(isolatedStructure || {}),
1516
1785
  ...Object.keys(isolatedEquivalentVariables || {}),
1517
- ...Object.values(isolatedEquivalentVariables || {}),
1786
+ ...flattenedEquivValues,
1518
1787
  ]),
1519
1788
  );
1520
1789
 
1521
1790
  for (let path in isolatedEquivalentVariables) {
1522
- let equivalentValue = isolatedEquivalentVariables?.[path];
1523
-
1524
- if (equivalentValue && this.isValidPath(equivalentValue)) {
1525
- path = cleanPath(path.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1526
- equivalentValue = cleanPath(
1527
- equivalentValue.replace(/::cyDuplicateKey\d+::/g, ''),
1528
- allPaths,
1529
- );
1530
-
1531
- this.addEquivalency(
1532
- path,
1533
- equivalentValue,
1534
- scopeNode.name,
1535
- scopeNode,
1536
- 'original equivalency',
1537
- );
1791
+ const rawEquivalentValue = isolatedEquivalentVariables?.[path];
1792
+ // Normalize to array for consistent handling
1793
+ const equivalentValues = Array.isArray(rawEquivalentValue)
1794
+ ? rawEquivalentValue
1795
+ : [rawEquivalentValue];
1796
+
1797
+ for (let equivalentValue of equivalentValues) {
1798
+ if (equivalentValue && this.isValidPath(equivalentValue)) {
1799
+ // IMPORTANT: DO NOT strip ::cyDuplicateKey:: markers from equivalencies.
1800
+ // These markers are critical for distinguishing variable reassignments.
1801
+ // For example, with:
1802
+ // let fetcher = useFetcher<ConfigData>();
1803
+ // const configData = fetcher.data?.data;
1804
+ // fetcher = useFetcher<SettingsData>();
1805
+ // const settingsData = fetcher.data?.data;
1806
+ //
1807
+ // mergeStatements creates:
1808
+ // fetcher → useFetcher<ConfigData>()...
1809
+ // fetcher::cyDuplicateKey1:: → useFetcher<SettingsData>()...
1810
+ // configData → fetcher.data.data
1811
+ // settingsData → fetcher::cyDuplicateKey1::.data.data
1812
+ //
1813
+ // If we strip ::cyDuplicateKey::, settingsData would incorrectly trace
1814
+ // to useFetcher<ConfigData>() instead of useFetcher<SettingsData>().
1815
+ path = cleanPath(path, allPaths);
1816
+ equivalentValue = cleanPath(equivalentValue, allPaths);
1817
+
1818
+ this.addEquivalency(
1819
+ path,
1820
+ equivalentValue,
1821
+ scopeNode.name,
1822
+ scopeNode,
1823
+ 'original equivalency',
1824
+ );
1538
1825
 
1539
- // Propagate equivalencies involving parent-scope variables to those parent scopes.
1540
- // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1541
- // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1542
- // visible when tracing from the parent scope.
1543
- const rootVariable = this.extractRootVariable(path);
1544
- const equivalentRootVariable =
1545
- this.extractRootVariable(equivalentValue);
1546
-
1547
- // Skip propagation for self-referential reassignment patterns like:
1548
- // x = x.method().functionCallReturnValue
1549
- // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1550
- // These create circular references since both sides reference the same variable.
1551
- //
1552
- // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1553
- // where the path has additional segments beyond the root variable.
1554
- const pathIsJustRootVariable = path === rootVariable;
1555
- const isSelfReferentialReassignment =
1556
- pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1826
+ // Propagate equivalencies involving parent-scope variables to those parent scopes.
1827
+ // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1828
+ // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1829
+ // visible when tracing from the parent scope.
1830
+ const rootVariable = this.extractRootVariable(path);
1831
+ const equivalentRootVariable =
1832
+ this.extractRootVariable(equivalentValue);
1833
+
1834
+ // Skip propagation for self-referential reassignment patterns like:
1835
+ // x = x.method().functionCallReturnValue
1836
+ // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1837
+ // These create circular references since both sides reference the same variable.
1838
+ //
1839
+ // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1840
+ // where the path has additional segments beyond the root variable.
1841
+ const pathIsJustRootVariable = path === rootVariable;
1842
+ const isSelfReferentialReassignment =
1843
+ pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1557
1844
 
1558
- if (
1559
- rootVariable &&
1560
- !isSelfReferentialReassignment &&
1561
- scopeNode.parentInstantiatedVariables?.includes(rootVariable)
1562
- ) {
1563
- // Find the parent scope where this variable is defined
1564
- for (const parentScopeName of scopeNode.tree || []) {
1565
- const parentScope = this.scopeNodes[parentScopeName];
1566
- if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1567
- // Add the equivalency to the parent scope as well
1568
- this.addEquivalency(
1569
- path,
1570
- equivalentValue,
1571
- scopeNode.name, // The equivalent path's scope remains the child scope
1572
- parentScope, // But store it in the parent scope's equivalencies
1573
- 'propagated parent-variable equivalency',
1574
- );
1575
- break;
1845
+ if (
1846
+ rootVariable &&
1847
+ !isSelfReferentialReassignment &&
1848
+ scopeNode.parentInstantiatedVariables?.includes(rootVariable)
1849
+ ) {
1850
+ // Find the parent scope where this variable is defined
1851
+ for (const parentScopeName of scopeNode.tree || []) {
1852
+ const parentScope = this.scopeNodes[parentScopeName];
1853
+ if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1854
+ // Add the equivalency to the parent scope as well
1855
+ this.addEquivalency(
1856
+ path,
1857
+ equivalentValue,
1858
+ scopeNode.name, // The equivalent path's scope remains the child scope
1859
+ parentScope, // But store it in the parent scope's equivalencies
1860
+ 'propagated parent-variable equivalency',
1861
+ );
1862
+ break;
1863
+ }
1576
1864
  }
1577
1865
  }
1578
- }
1579
1866
 
1580
- // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1581
- // that has sub-properties defined in the isolatedEquivalentVariables.
1582
- // This handles cases like: dataItem={{ structure: completeDataStructure }}
1583
- // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1584
- // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1585
- const isSimpleVariable =
1586
- !equivalentValue.startsWith('signature[') &&
1587
- !equivalentValue.includes('functionCallReturnValue') &&
1588
- !equivalentValue.includes('.') &&
1589
- !equivalentValue.includes('[');
1590
-
1591
- if (isSimpleVariable) {
1592
- // Look in current scope and all parent scopes for sub-properties
1593
- const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1594
- for (const scopeName of scopesToCheck) {
1595
- const checkScope = this.scopeNodes[scopeName];
1596
- if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1597
-
1598
- for (const [subPath, subValue] of Object.entries(
1599
- checkScope.analysis.isolatedEquivalentVariables,
1600
- )) {
1601
- // Check if this is a sub-property of the equivalentValue variable
1602
- // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1603
- const matchesDot = subPath.startsWith(equivalentValue + '.');
1604
- const matchesBracket = subPath.startsWith(equivalentValue + '[');
1605
- if (matchesDot || matchesBracket) {
1606
- const subPropertyPath = subPath.substring(
1607
- equivalentValue.length,
1867
+ // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1868
+ // that has sub-properties defined in the isolatedEquivalentVariables.
1869
+ // This handles cases like: dataItem={{ structure: completeDataStructure }}
1870
+ // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1871
+ // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1872
+ const isSimpleVariable =
1873
+ !equivalentValue.startsWith('signature[') &&
1874
+ !equivalentValue.includes('functionCallReturnValue') &&
1875
+ !equivalentValue.includes('.') &&
1876
+ !equivalentValue.includes('[');
1877
+
1878
+ if (isSimpleVariable) {
1879
+ // Look in current scope and all parent scopes for sub-properties
1880
+ const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1881
+ for (const scopeName of scopesToCheck) {
1882
+ const checkScope = this.scopeNodes[scopeName];
1883
+ if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1884
+
1885
+ for (const [subPath, rawSubValue] of Object.entries(
1886
+ checkScope.analysis.isolatedEquivalentVariables,
1887
+ )) {
1888
+ // Normalize to array for consistent handling
1889
+ const subValues = Array.isArray(rawSubValue)
1890
+ ? rawSubValue
1891
+ : rawSubValue
1892
+ ? [rawSubValue]
1893
+ : [];
1894
+
1895
+ // Check if this is a sub-property of the equivalentValue variable
1896
+ // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1897
+ const matchesDot = subPath.startsWith(equivalentValue + '.');
1898
+ const matchesBracket = subPath.startsWith(
1899
+ equivalentValue + '[',
1608
1900
  );
1609
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1610
- const newEquivalentValue = cleanPath(
1611
- (subValue as string).replace(/::cyDuplicateKey\d+::/g, ''),
1612
- allPaths,
1613
- );
1614
-
1615
- if (
1616
- newEquivalentValue &&
1617
- this.isValidPath(newEquivalentValue)
1618
- ) {
1619
- this.addEquivalency(
1620
- newPath,
1621
- newEquivalentValue,
1622
- checkScope.name, // Use the scope where the sub-property was found
1623
- scopeNode,
1624
- 'propagated sub-property equivalency',
1901
+ if (matchesDot || matchesBracket) {
1902
+ const subPropertyPath = subPath.substring(
1903
+ equivalentValue.length,
1625
1904
  );
1905
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
1906
+
1907
+ for (const subValue of subValues) {
1908
+ if (typeof subValue !== 'string') continue;
1909
+ const newEquivalentValue = cleanPath(
1910
+ subValue.replace(/::cyDuplicateKey\d+::/g, ''),
1911
+ allPaths,
1912
+ );
1913
+
1914
+ if (
1915
+ newEquivalentValue &&
1916
+ this.isValidPath(newEquivalentValue)
1917
+ ) {
1918
+ this.addEquivalency(
1919
+ newPath,
1920
+ newEquivalentValue,
1921
+ checkScope.name, // Use the scope where the sub-property was found
1922
+ scopeNode,
1923
+ 'propagated sub-property equivalency',
1924
+ );
1925
+ }
1926
+ }
1626
1927
  }
1627
- }
1628
1928
 
1629
- // Also check if equivalentValue itself maps to a functionCallReturnValue
1630
- // e.g., result = useMemo(...).functionCallReturnValue
1631
- if (
1632
- subPath === equivalentValue &&
1633
- typeof subValue === 'string' &&
1634
- subValue.endsWith('.functionCallReturnValue')
1635
- ) {
1636
- this.propagateFunctionCallReturnSubProperties(
1637
- path,
1638
- subValue,
1639
- scopeNode,
1640
- allPaths,
1641
- );
1929
+ // Also check if equivalentValue itself maps to a functionCallReturnValue
1930
+ // e.g., result = useMemo(...).functionCallReturnValue
1931
+ for (const subValue of subValues) {
1932
+ if (
1933
+ subPath === equivalentValue &&
1934
+ typeof subValue === 'string' &&
1935
+ subValue.endsWith('.functionCallReturnValue')
1936
+ ) {
1937
+ this.propagateFunctionCallReturnSubProperties(
1938
+ path,
1939
+ subValue,
1940
+ scopeNode,
1941
+ allPaths,
1942
+ );
1943
+ }
1944
+ }
1642
1945
  }
1643
1946
  }
1644
1947
  }
1645
- }
1646
1948
 
1647
- // Handle function call return values by propagating returnValue.* sub-properties
1648
- // from the callback scope to the usage path
1649
- if (equivalentValue.endsWith('.functionCallReturnValue')) {
1650
- this.propagateFunctionCallReturnSubProperties(
1651
- path,
1652
- equivalentValue,
1653
- scopeNode,
1654
- allPaths,
1655
- );
1949
+ // Handle function call return values by propagating returnValue.* sub-properties
1950
+ // from the callback scope to the usage path
1951
+ if (equivalentValue.endsWith('.functionCallReturnValue')) {
1952
+ this.propagateFunctionCallReturnSubProperties(
1953
+ path,
1954
+ equivalentValue,
1955
+ scopeNode,
1956
+ allPaths,
1957
+ );
1656
1958
 
1657
- // Track which variable receives the return value of each function call
1658
- // This enables generating separate mock data for each call site
1659
- this.trackReceivingVariable(path, equivalentValue);
1660
- }
1959
+ // Track which variable receives the return value of each function call
1960
+ // This enables generating separate mock data for each call site
1961
+ this.trackReceivingVariable(path, equivalentValue);
1962
+ }
1661
1963
 
1662
- // Also track variables that receive destructured properties from function call return values
1663
- // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1664
- if (equivalentValue.includes('.functionCallReturnValue.')) {
1665
- this.trackReceivingVariable(path, equivalentValue);
1964
+ // Also track variables that receive destructured properties from function call return values
1965
+ // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1966
+ if (equivalentValue.includes('.functionCallReturnValue.')) {
1967
+ this.trackReceivingVariable(path, equivalentValue);
1968
+ }
1666
1969
  }
1667
1970
  }
1668
1971
  }
@@ -1672,7 +1975,7 @@ export class ScopeDataStructure {
1672
1975
  this.batchProcessor = new BatchSchemaProcessor();
1673
1976
  this.batchQueuedSet = new Set();
1674
1977
 
1675
- for (const key of Array.from(allPaths)) {
1978
+ for (const key of allPaths) {
1676
1979
  let value = isolatedStructure[key] ?? 'unknown';
1677
1980
 
1678
1981
  if (['null', 'undefined'].includes(value)) {
@@ -1713,7 +2016,19 @@ export class ScopeDataStructure {
1713
2016
  private processBatchQueue(): void {
1714
2017
  if (!this.batchProcessor) return;
1715
2018
 
2019
+ let iterations = 0;
2020
+
1716
2021
  while (this.batchProcessor.hasWork()) {
2022
+ iterations++;
2023
+
2024
+ // Safety: detect potential infinite loops
2025
+ if (iterations > 100000) {
2026
+ console.error(
2027
+ `[ScopeDataStructure] processBatchQueue exceeded 100k iterations, possible infinite loop!`,
2028
+ );
2029
+ break;
2030
+ }
2031
+
1717
2032
  const item = this.batchProcessor.getNextWork();
1718
2033
  if (!item) break;
1719
2034
 
@@ -1771,26 +2086,6 @@ export class ScopeDataStructure {
1771
2086
  const functionCallInfo =
1772
2087
  this.getExternalFunctionCallsIndex().get(searchKey);
1773
2088
 
1774
- // DEBUG: Track useFetcher calls
1775
- if (searchKey === 'useFetcher' || callSignature.includes('useFetcher')) {
1776
- console.log(
1777
- 'CodeYam DEBUG trackReceivingVariable:',
1778
- JSON.stringify(
1779
- {
1780
- receivingVariable,
1781
- equivalentValue,
1782
- callSignature,
1783
- searchKey,
1784
- foundFunctionCallInfo: !!functionCallInfo,
1785
- existingRecvVars: functionCallInfo?.receivingVariableNames,
1786
- existingCallSigToVar: functionCallInfo?.callSignatureToVariable,
1787
- },
1788
- null,
1789
- 2,
1790
- ),
1791
- );
1792
- }
1793
-
1794
2089
  if (!functionCallInfo) {
1795
2090
  return;
1796
2091
  }
@@ -1851,9 +2146,18 @@ export class ScopeDataStructure {
1851
2146
  const checkScope = this.scopeNodes[scopeName];
1852
2147
  if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1853
2148
 
1854
- const functionRef =
2149
+ const rawFunctionRef =
1855
2150
  checkScope.analysis.isolatedEquivalentVariables[functionName];
1856
- if (typeof functionRef === 'string' && functionRef.endsWith('F')) {
2151
+ // Normalize to array and find first string ending with 'F'
2152
+ const functionRefs = Array.isArray(rawFunctionRef)
2153
+ ? rawFunctionRef
2154
+ : rawFunctionRef
2155
+ ? [rawFunctionRef]
2156
+ : [];
2157
+ const functionRef = functionRefs.find(
2158
+ (r) => typeof r === 'string' && r.endsWith('F'),
2159
+ );
2160
+ if (typeof functionRef === 'string') {
1857
2161
  callbackScopeName = functionRef.slice(0, -1);
1858
2162
  break;
1859
2163
  }
@@ -1881,19 +2185,24 @@ export class ScopeDataStructure {
1881
2185
 
1882
2186
  const isolatedVars = callbackScope.analysis.isolatedEquivalentVariables;
1883
2187
 
2188
+ // Get the first returnValue equivalency (normalize array to single value for these checks)
2189
+ const rawReturnValue = isolatedVars.returnValue;
2190
+ const firstReturnValue = Array.isArray(rawReturnValue)
2191
+ ? rawReturnValue[0]
2192
+ : rawReturnValue;
2193
+
1884
2194
  // First, check if returnValue is an alias to another variable (e.g., returnValue = intermediate)
1885
2195
  // If so, we need to look for that variable's sub-properties too
1886
2196
  const returnValueAlias =
1887
- typeof isolatedVars.returnValue === 'string' &&
1888
- !isolatedVars.returnValue.includes('.')
1889
- ? isolatedVars.returnValue
2197
+ typeof firstReturnValue === 'string' && !firstReturnValue.includes('.')
2198
+ ? firstReturnValue
1890
2199
  : undefined;
1891
2200
 
1892
2201
  // Pattern 3: Object.keys(X).reduce() - the reduce result has the same sub-properties as X
1893
2202
  // When returnValue = "Object.keys(source).reduce(...).functionCallReturnValue", look for source.* sub-properties
1894
2203
  let reduceSourceVar: string | undefined;
1895
- if (typeof isolatedVars.returnValue === 'string') {
1896
- const reduceMatch = isolatedVars.returnValue.match(
2204
+ if (typeof firstReturnValue === 'string') {
2205
+ const reduceMatch = firstReturnValue.match(
1897
2206
  /^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/,
1898
2207
  );
1899
2208
  if (reduceMatch) {
@@ -1901,7 +2210,14 @@ export class ScopeDataStructure {
1901
2210
  }
1902
2211
  }
1903
2212
 
1904
- for (const [subPath, subValue] of Object.entries(isolatedVars)) {
2213
+ for (const [subPath, rawSubValue] of Object.entries(isolatedVars)) {
2214
+ // Normalize to array for consistent handling
2215
+ const subValues = Array.isArray(rawSubValue)
2216
+ ? rawSubValue
2217
+ : rawSubValue
2218
+ ? [rawSubValue]
2219
+ : [];
2220
+
1905
2221
  // Check for direct returnValue.* sub-properties
1906
2222
  const isReturnValueSub =
1907
2223
  subPath.startsWith('returnValue.') ||
@@ -1919,57 +2235,59 @@ export class ScopeDataStructure {
1919
2235
  (subPath.startsWith(reduceSourceVar + '.') ||
1920
2236
  subPath.startsWith(reduceSourceVar + '['));
1921
2237
 
1922
- if (
1923
- typeof subValue !== 'string' ||
1924
- (!isReturnValueSub && !isAliasSub && !isReduceSourceSub)
1925
- )
1926
- continue;
1927
-
1928
- // Convert alias/reduceSource paths to returnValue paths
1929
- let effectiveSubPath = subPath;
1930
- if (isAliasSub && !isReturnValueSub) {
1931
- // Replace the alias prefix with returnValue
1932
- effectiveSubPath =
1933
- 'returnValue' + subPath.substring(returnValueAlias!.length);
1934
- } else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
1935
- // Replace the reduce source prefix with returnValue
1936
- effectiveSubPath =
1937
- 'returnValue' + subPath.substring(reduceSourceVar!.length);
1938
- }
1939
- const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
1940
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1941
- let newEquivalentValue = cleanPath(
1942
- subValue.replace(/::cyDuplicateKey\d+::/g, ''),
1943
- allPaths,
1944
- );
2238
+ if (!isReturnValueSub && !isAliasSub && !isReduceSourceSub) continue;
2239
+
2240
+ for (const subValue of subValues) {
2241
+ if (typeof subValue !== 'string') continue;
2242
+
2243
+ // Convert alias/reduceSource paths to returnValue paths
2244
+ let effectiveSubPath = subPath;
2245
+ if (isAliasSub && !isReturnValueSub) {
2246
+ // Replace the alias prefix with returnValue
2247
+ effectiveSubPath =
2248
+ 'returnValue' + subPath.substring(returnValueAlias!.length);
2249
+ } else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
2250
+ // Replace the reduce source prefix with returnValue
2251
+ effectiveSubPath =
2252
+ 'returnValue' + subPath.substring(reduceSourceVar!.length);
2253
+ }
2254
+ const subPropertyPath = effectiveSubPath.substring(
2255
+ 'returnValue'.length,
2256
+ );
2257
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
2258
+ let newEquivalentValue = cleanPath(
2259
+ subValue.replace(/::cyDuplicateKey\d+::/g, ''),
2260
+ allPaths,
2261
+ );
1945
2262
 
1946
- // Resolve variable references through parent scope equivalencies
1947
- const resolved = this.resolveVariableThroughParentScopes(
1948
- newEquivalentValue,
1949
- callbackScope,
1950
- allPaths,
1951
- );
1952
- newEquivalentValue = resolved.resolvedPath;
1953
- const equivalentScopeName = resolved.scopeName;
2263
+ // Resolve variable references through parent scope equivalencies
2264
+ const resolved = this.resolveVariableThroughParentScopes(
2265
+ newEquivalentValue,
2266
+ callbackScope,
2267
+ allPaths,
2268
+ );
2269
+ newEquivalentValue = resolved.resolvedPath;
2270
+ const equivalentScopeName = resolved.scopeName;
1954
2271
 
1955
- if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
1956
- continue;
2272
+ if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
2273
+ continue;
1957
2274
 
1958
- this.addEquivalency(
1959
- newPath,
1960
- newEquivalentValue,
1961
- equivalentScopeName,
1962
- scopeNode,
1963
- 'propagated function call return sub-property equivalency',
1964
- );
2275
+ this.addEquivalency(
2276
+ newPath,
2277
+ newEquivalentValue,
2278
+ equivalentScopeName,
2279
+ scopeNode,
2280
+ 'propagated function call return sub-property equivalency',
2281
+ );
1965
2282
 
1966
- // Ensure the database entry has the usage path
1967
- this.addUsageToEquivalencyDatabaseEntry(
1968
- newPath,
1969
- newEquivalentValue,
1970
- equivalentScopeName,
1971
- scopeNode.name,
1972
- );
2283
+ // Ensure the database entry has the usage path
2284
+ this.addUsageToEquivalencyDatabaseEntry(
2285
+ newPath,
2286
+ newEquivalentValue,
2287
+ equivalentScopeName,
2288
+ scopeNode.name,
2289
+ );
2290
+ }
1973
2291
  }
1974
2292
  }
1975
2293
 
@@ -2009,8 +2327,15 @@ export class ScopeDataStructure {
2009
2327
  const parentScope = this.scopeNodes[parentScopeName];
2010
2328
  if (!parentScope?.analysis?.isolatedEquivalentVariables) continue;
2011
2329
 
2012
- const rootEquiv =
2330
+ const rawRootEquiv =
2013
2331
  parentScope.analysis.isolatedEquivalentVariables[rootVar];
2332
+ // Normalize to array and use first string value
2333
+ const rootEquivs = Array.isArray(rawRootEquiv)
2334
+ ? rawRootEquiv
2335
+ : rawRootEquiv
2336
+ ? [rawRootEquiv]
2337
+ : [];
2338
+ const rootEquiv = rootEquivs.find((r) => typeof r === 'string');
2014
2339
  if (typeof rootEquiv === 'string') {
2015
2340
  return {
2016
2341
  resolvedPath: cleanPath(rootEquiv + restOfPath, allPaths),
@@ -2285,11 +2610,27 @@ export class ScopeDataStructure {
2285
2610
  relevantSubPathParts.every((part, i) => part === schemaPathParts[i]) &&
2286
2611
  equivalentValue.scopeNodeName === scopeNode.name
2287
2612
  ) {
2613
+ // DEBUG
2288
2614
  continue;
2289
2615
  }
2290
2616
 
2291
2617
  const newEquivalentPath = this.joinPathParts([schemaPath, remainingPath]);
2292
2618
 
2619
+ // PERF: Detect repeated patterns in paths to prevent exponential blowup
2620
+ // Paths like `signature[0].attributes.properties[].attributes.properties[]...`
2621
+ // indicate recursive type structures that cause exponential schema explosion
2622
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
2623
+ if (traceId && debugLevel > 0) {
2624
+ console.info(
2625
+ 'Debug: skipping path with excessive pattern repetition',
2626
+ {
2627
+ path: newEquivalentPath,
2628
+ },
2629
+ );
2630
+ }
2631
+ continue;
2632
+ }
2633
+
2293
2634
  if (!equivalentScopeNode) {
2294
2635
  if (traceId) {
2295
2636
  console.info('Debug Propagation: missing equivalent scope info', {
@@ -2661,10 +3002,105 @@ export class ScopeDataStructure {
2661
3002
  this.intermediatesOrderIndex.set(pathId, databaseEntry);
2662
3003
 
2663
3004
  if (intermediateIndex === 0) {
2664
- const isValidSourceCandidate =
3005
+ let isValidSourceCandidate =
2665
3006
  pathInfo.schemaPath.startsWith('signature[') ||
2666
3007
  pathInfo.schemaPath.includes('functionCallReturnValue');
2667
- if (isValidSourceCandidate) {
3008
+
3009
+ // Check if path STARTS with a spread pattern like [...var]
3010
+ // This handles cases like [...files][][0] or [...files].sort(...).functionCallReturnValue[][0]
3011
+ // where the spread source variable needs to be resolved to a signature path.
3012
+ // We do this REGARDLESS of isValidSourceCandidate because even paths containing
3013
+ // functionCallReturnValue may need spread resolution to trace back to the signature.
3014
+ const spreadMatch = pathInfo.schemaPath.match(/^\[\.\.\.(\w+)\]/);
3015
+ if (spreadMatch) {
3016
+ const spreadVar = spreadMatch[1];
3017
+ const spreadPattern = spreadMatch[0]; // The full [...var] match
3018
+ const scopeNode = this.scopeNodes[pathInfo.scopeNodeName];
3019
+
3020
+ if (scopeNode?.equivalencies) {
3021
+ // Follow the equivalency chain to find a signature path
3022
+ // e.g., files (cyScope1) → files (root) → signature[0].files
3023
+ const resolveToSignature = (
3024
+ varName: string,
3025
+ currentScopeName: string,
3026
+ visited: Set<string>,
3027
+ ): { schemaPath: string; scopeNodeName: string } | null => {
3028
+ const visitKey = `${currentScopeName}::${varName}`;
3029
+ if (visited.has(visitKey)) return null;
3030
+ visited.add(visitKey);
3031
+
3032
+ const currentScope = this.scopeNodes[currentScopeName];
3033
+ if (!currentScope?.equivalencies) return null;
3034
+
3035
+ const varEquivs = currentScope.equivalencies[varName];
3036
+ if (!varEquivs) return null;
3037
+
3038
+ // First check if any equivalency directly points to a signature path
3039
+ const signatureEquiv = varEquivs.find((eq) =>
3040
+ eq.schemaPath.startsWith('signature['),
3041
+ );
3042
+ if (signatureEquiv) {
3043
+ return signatureEquiv;
3044
+ }
3045
+
3046
+ // Otherwise, follow the chain to other scopes
3047
+ for (const equiv of varEquivs) {
3048
+ // If the equivalency points to the same variable in a different scope,
3049
+ // follow the chain
3050
+ if (
3051
+ equiv.schemaPath === varName &&
3052
+ equiv.scopeNodeName !== currentScopeName
3053
+ ) {
3054
+ const result = resolveToSignature(
3055
+ varName,
3056
+ equiv.scopeNodeName,
3057
+ visited,
3058
+ );
3059
+ if (result) return result;
3060
+ }
3061
+ }
3062
+
3063
+ return null;
3064
+ };
3065
+
3066
+ const signatureEquiv = resolveToSignature(
3067
+ spreadVar,
3068
+ pathInfo.scopeNodeName,
3069
+ new Set(),
3070
+ );
3071
+ if (signatureEquiv) {
3072
+ // Replace ONLY the [...var] part with the resolved signature path
3073
+ // This preserves any suffix like .sort(...).functionCallReturnValue[][0]
3074
+ const resolvedPath = pathInfo.schemaPath.replace(
3075
+ spreadPattern,
3076
+ signatureEquiv.schemaPath,
3077
+ );
3078
+ // Add the resolved path as a source candidate
3079
+ if (
3080
+ !databaseEntry.sourceCandidates.some(
3081
+ (sc) =>
3082
+ sc.schemaPath === resolvedPath &&
3083
+ sc.scopeNodeName === pathInfo.scopeNodeName,
3084
+ )
3085
+ ) {
3086
+ databaseEntry.sourceCandidates.push({
3087
+ scopeNodeName: pathInfo.scopeNodeName,
3088
+ schemaPath: resolvedPath,
3089
+ });
3090
+ }
3091
+ isValidSourceCandidate = true;
3092
+ }
3093
+ }
3094
+ }
3095
+
3096
+ if (
3097
+ isValidSourceCandidate &&
3098
+ !databaseEntry.sourceCandidates.some(
3099
+ (sc) =>
3100
+ sc.schemaPath === pathInfo.schemaPath &&
3101
+ sc.scopeNodeName === pathInfo.scopeNodeName,
3102
+ )
3103
+ ) {
2668
3104
  databaseEntry.sourceCandidates.push(pathInfo);
2669
3105
  }
2670
3106
  } else {
@@ -2892,6 +3328,14 @@ export class ScopeDataStructure {
2892
3328
  }
2893
3329
  }
2894
3330
 
3331
+ // Ensure parameter-to-signature equivalencies are fully propagated.
3332
+ // When a parameter variable (e.g., `node`) is equivalenced to `signature[N]`,
3333
+ // all sub-paths of that variable should also appear under `signature[N]`.
3334
+ // This handles cases where the sub-path was added to the schema via a propagation
3335
+ // chain that already included the variable↔signature equivalency, causing the
3336
+ // cycle detection to prevent the reverse mapping.
3337
+ this.propagateParameterToSignaturePaths(scopeNode);
3338
+
2895
3339
  fillInSchemaGapsAndUnknowns(scopeNode, fillInUnknowns);
2896
3340
 
2897
3341
  if (final) {
@@ -2906,7 +3350,51 @@ export class ScopeDataStructure {
2906
3350
  }
2907
3351
  }
2908
3352
 
2909
- private filterAndConvertSchema({
3353
+ /**
3354
+ * For each equivalency where a simple variable maps to signature[N],
3355
+ * ensure all sub-paths of that variable are reflected under signature[N].
3356
+ */
3357
+ private propagateParameterToSignaturePaths(scopeNode: ScopeNode) {
3358
+ // Find variable → signature[N] equivalencies
3359
+ for (const [varName, equivalencies] of Object.entries(
3360
+ scopeNode.equivalencies,
3361
+ )) {
3362
+ // Only process simple variable names (no dots, brackets, or parens)
3363
+ if (
3364
+ varName.includes('.') ||
3365
+ varName.includes('[') ||
3366
+ varName.includes('(')
3367
+ ) {
3368
+ continue;
3369
+ }
3370
+
3371
+ for (const equiv of equivalencies) {
3372
+ if (
3373
+ equiv.scopeNodeName === scopeNode.name &&
3374
+ equiv.schemaPath.startsWith('signature[')
3375
+ ) {
3376
+ const signaturePath = equiv.schemaPath;
3377
+ const varPrefix = varName + '.';
3378
+ const varBracketPrefix = varName + '[';
3379
+
3380
+ // Find all schema keys starting with the variable
3381
+ for (const key in scopeNode.schema) {
3382
+ if (key.startsWith(varPrefix) || key.startsWith(varBracketPrefix)) {
3383
+ const suffix = key.slice(varName.length);
3384
+ const sigKey = signaturePath + suffix;
3385
+
3386
+ // Only add if the signature path doesn't already exist
3387
+ if (!scopeNode.schema[sigKey]) {
3388
+ scopeNode.schema[sigKey] = scopeNode.schema[key];
3389
+ }
3390
+ }
3391
+ }
3392
+ }
3393
+ }
3394
+ }
3395
+ }
3396
+
3397
+ private filterAndConvertSchema({
2910
3398
  filterPath,
2911
3399
  newPath,
2912
3400
  schema,
@@ -2992,6 +3480,9 @@ export class ScopeDataStructure {
2992
3480
  equivalentValueSchemaPathParts.length,
2993
3481
  ),
2994
3482
  ]);
3483
+ // PERF: Skip keys with repeated function-call signature patterns
3484
+ // to prevent recursive type expansion (e.g., string.localeCompare returns string)
3485
+ if (this.hasExcessivePatternRepetition(newKey)) continue;
2995
3486
  resolvedSchema[newKey] = value;
2996
3487
  }
2997
3488
  }
@@ -3014,6 +3505,8 @@ export class ScopeDataStructure {
3014
3505
  if (!subSchema) continue;
3015
3506
 
3016
3507
  for (const resolvedKey in subSchema) {
3508
+ // PERF: Skip keys with repeated function-call signature patterns
3509
+ if (this.hasExcessivePatternRepetition(resolvedKey)) continue;
3017
3510
  if (
3018
3511
  !resolvedSchema[resolvedKey] ||
3019
3512
  subSchema[resolvedKey] === 'unknown'
@@ -3160,7 +3653,12 @@ export class ScopeDataStructure {
3160
3653
  );
3161
3654
  }
3162
3655
 
3656
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
3657
+ // during this "getter" method. See comment in getFunctionSignature.
3658
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
3659
+ this.onlyEquivalencies = true;
3163
3660
  this.validateSchema(scopeNode, true, fillInUnknowns);
3661
+ this.onlyEquivalencies = wasOnlyEquivalencies;
3164
3662
 
3165
3663
  const { schema } = scopeNode;
3166
3664
 
@@ -3194,10 +3692,29 @@ export class ScopeDataStructure {
3194
3692
  }
3195
3693
  }
3196
3694
  }
3197
- return mergedSchema;
3695
+ return this.filterDuplicateKeys(mergedSchema);
3198
3696
  }
3199
3697
 
3200
- return schema;
3698
+ return this.filterDuplicateKeys(schema);
3699
+ }
3700
+
3701
+ /**
3702
+ * Filter out ::cyDuplicateKey:: entries from a schema.
3703
+ * These are internal markers for tracking variable reassignments
3704
+ * and should not appear in output schemas or LLM prompts.
3705
+ */
3706
+ private filterDuplicateKeys(
3707
+ schema: Record<string, string>,
3708
+ ): Record<string, string> {
3709
+ return Object.entries(schema).reduce(
3710
+ (acc, [key, value]) => {
3711
+ if (!key.includes('::cyDuplicateKey')) {
3712
+ acc[key] = value;
3713
+ }
3714
+ return acc;
3715
+ },
3716
+ {} as Record<string, string>,
3717
+ );
3201
3718
  }
3202
3719
 
3203
3720
  getEquivalencies(scopeName?: string) {
@@ -3227,18 +3744,171 @@ export class ScopeDataStructure {
3227
3744
  return {};
3228
3745
  }
3229
3746
 
3747
+ // Collect all descendant scope names (including the scope itself)
3748
+ // This ensures we include external calls from nested scopes like cyScope2
3749
+ const getAllDescendantScopeNames = (
3750
+ node: import('./helpers/ScopeTreeManager').ScopeTreeNode,
3751
+ ): Set<string> => {
3752
+ const names = new Set<string>([node.name]);
3753
+ for (const child of node.children) {
3754
+ for (const name of getAllDescendantScopeNames(child)) {
3755
+ names.add(name);
3756
+ }
3757
+ }
3758
+ return names;
3759
+ };
3760
+
3761
+ const treeNode = this.scopeTreeManager.findNode(scopeNode.name);
3762
+ const descendantScopeNames = treeNode
3763
+ ? getAllDescendantScopeNames(treeNode)
3764
+ : new Set<string>([scopeNode.name]);
3765
+
3766
+ // Get all external function calls made from this scope or any descendant scope
3767
+ // This allows us to include prop equivalencies from JSX components
3768
+ // that were rendered in nested scopes (e.g., FileTableRow called from cyScope2)
3769
+ const externalCallsFromScope = this.externalFunctionCalls.filter((efc) =>
3770
+ descendantScopeNames.has(efc.callScope),
3771
+ );
3772
+ const externalCallNames = new Set(
3773
+ externalCallsFromScope.map((efc) => efc.name),
3774
+ );
3775
+
3776
+ // Helper to check if a usage belongs to this scope (directly, via descendant, or via external call)
3777
+ const usageMatchesScope = (usage: { scopeNodeName: string }) =>
3778
+ descendantScopeNames.has(usage.scopeNodeName) ||
3779
+ externalCallNames.has(usage.scopeNodeName);
3780
+
3230
3781
  const entries = this.equivalencyDatabase.filter((entry) =>
3231
- entry.usages.some((usage) => usage.scopeNodeName === scopeNode.name),
3782
+ entry.usages.some(usageMatchesScope),
3232
3783
  );
3784
+
3785
+ // Helper to resolve a source candidate through equivalency chains to find signature paths
3786
+ const resolveToSignature = (
3787
+ source: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>,
3788
+ visited: Set<string>,
3789
+ ): Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] => {
3790
+ const visitKey = `${source.scopeNodeName}::${source.schemaPath}`;
3791
+ if (visited.has(visitKey)) return [];
3792
+ visited.add(visitKey);
3793
+
3794
+ // If already a signature path, return as-is
3795
+ if (source.schemaPath.startsWith('signature[')) {
3796
+ return [source];
3797
+ }
3798
+
3799
+ const currentScope = this.scopeNodes[source.scopeNodeName];
3800
+ if (!currentScope?.equivalencies) return [source];
3801
+
3802
+ // Check for direct equivalencies FIRST (full path match)
3803
+ // This ensures paths like "useMemo(...).functionCallReturnValue" follow to "cyScope1::returnValue"
3804
+ // before prefix matching tries "useMemo(...)" which goes to the useMemo scope
3805
+ const directEquivs = currentScope.equivalencies[source.schemaPath];
3806
+ if (directEquivs?.length > 0) {
3807
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3808
+ [];
3809
+ for (const equiv of directEquivs) {
3810
+ const resolved = resolveToSignature(
3811
+ {
3812
+ scopeNodeName: equiv.scopeNodeName,
3813
+ schemaPath: equiv.schemaPath,
3814
+ },
3815
+ visited,
3816
+ );
3817
+ results.push(...resolved);
3818
+ }
3819
+ if (results.length > 0) return results;
3820
+ }
3821
+
3822
+ // Handle spread patterns like [...items].sort().functionCallReturnValue
3823
+ // Extract the spread variable and resolve it through the equivalency chain
3824
+ const spreadMatch = source.schemaPath.match(/^\[\.\.\.(\w+)\]/);
3825
+ if (spreadMatch) {
3826
+ const spreadVar = spreadMatch[1];
3827
+ const spreadPattern = spreadMatch[0];
3828
+ const varEquivs = currentScope.equivalencies[spreadVar];
3829
+
3830
+ if (varEquivs?.length > 0) {
3831
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3832
+ [];
3833
+ for (const equiv of varEquivs) {
3834
+ // Follow the variable equivalency and then resolve from there
3835
+ const resolvedVar = resolveToSignature(
3836
+ {
3837
+ scopeNodeName: equiv.scopeNodeName,
3838
+ schemaPath: equiv.schemaPath,
3839
+ },
3840
+ visited,
3841
+ );
3842
+ // For each resolved variable path, create the full path with array element suffix
3843
+ for (const rv of resolvedVar) {
3844
+ if (rv.schemaPath.startsWith('signature[')) {
3845
+ // Get the suffix after the spread pattern
3846
+ let suffix = source.schemaPath.slice(spreadPattern.length);
3847
+
3848
+ // Clean the suffix: strip array method chains like .sort(...).functionCallReturnValue[]
3849
+ // These don't change the data identity, just transform it.
3850
+ // Keep only the final element access parts like [0], [1], etc.
3851
+ // Pattern: strip everything from a method call up through functionCallReturnValue[]
3852
+ suffix = suffix.replace(
3853
+ /\.\w+\([^)]*\)\.functionCallReturnValue\[\]/g,
3854
+ '',
3855
+ );
3856
+ // Also handle simpler case without nested parens
3857
+ suffix = suffix.replace(
3858
+ /\.sort\(\w*\(\)\)\.functionCallReturnValue\[\]/g,
3859
+ '',
3860
+ );
3861
+
3862
+ // Add [] to indicate array element access from the spread
3863
+ const resolvedPath = rv.schemaPath + '[]' + suffix;
3864
+ results.push({
3865
+ scopeNodeName: rv.scopeNodeName,
3866
+ schemaPath: resolvedPath,
3867
+ });
3868
+ }
3869
+ }
3870
+ }
3871
+ if (results.length > 0) return results;
3872
+ }
3873
+ }
3874
+
3875
+ // Try to find prefix equivalencies that can resolve this path
3876
+ // For path like "cyScope3().signature[0][0]", check "cyScope3().signature[0]", etc.
3877
+ const pathParts = this.splitPath(source.schemaPath);
3878
+ for (let i = pathParts.length - 1; i > 0; i--) {
3879
+ const prefix = this.joinPathParts(pathParts.slice(0, i));
3880
+ const suffix = this.joinPathParts(pathParts.slice(i));
3881
+ const prefixEquivs = currentScope.equivalencies[prefix];
3882
+
3883
+ if (prefixEquivs?.length > 0) {
3884
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3885
+ [];
3886
+ for (const equiv of prefixEquivs) {
3887
+ const newPath = this.joinPathParts([equiv.schemaPath, suffix]);
3888
+ const resolved = resolveToSignature(
3889
+ { scopeNodeName: equiv.scopeNodeName, schemaPath: newPath },
3890
+ visited,
3891
+ );
3892
+ results.push(...resolved);
3893
+ }
3894
+ if (results.length > 0) return results;
3895
+ }
3896
+ }
3897
+
3898
+ return [source];
3899
+ };
3900
+
3233
3901
  return entries.reduce(
3234
3902
  (acc, entry) => {
3235
3903
  if (entry.sourceCandidates.length === 0) return acc;
3236
- const usages = entry.usages.filter(
3237
- (u) => u.scopeNodeName === scopeNode.name,
3238
- );
3904
+ const usages = entry.usages.filter(usageMatchesScope);
3239
3905
  for (const usage of usages) {
3240
3906
  acc[usage.schemaPath] ||= [];
3241
- acc[usage.schemaPath].push(...entry.sourceCandidates);
3907
+ // Resolve each source candidate through the equivalency chain
3908
+ for (const source of entry.sourceCandidates) {
3909
+ const resolvedSources = resolveToSignature(source, new Set());
3910
+ acc[usage.schemaPath].push(...resolvedSources);
3911
+ }
3242
3912
  }
3243
3913
  return acc;
3244
3914
  },
@@ -3261,6 +3931,7 @@ export class ScopeDataStructure {
3261
3931
  (candidate) => candidate.scopeNodeName === scopeNode.name,
3262
3932
  ),
3263
3933
  );
3934
+
3264
3935
  return entries.reduce(
3265
3936
  (acc, entry) => {
3266
3937
  if (entry.usages.length === 0) return acc;
@@ -3304,12 +3975,14 @@ export class ScopeDataStructure {
3304
3975
  );
3305
3976
 
3306
3977
  const equivalencies = this.getEquivalencies(functionName);
3978
+ const scopeName = functionName ?? this.scopeTreeManager.getRootName();
3979
+
3307
3980
  for (const equivalenceKey in equivalencies ?? {}) {
3308
3981
  for (const equivalenceValue of equivalencies[equivalenceKey]) {
3309
3982
  const schemaPath = equivalenceValue.schemaPath;
3310
3983
  if (
3311
3984
  schemaPath.startsWith('signature[') &&
3312
- equivalenceValue.scopeNodeName === functionName &&
3985
+ equivalenceValue.scopeNodeName === scopeName &&
3313
3986
  !signatureInSchema[schemaPath]
3314
3987
  ) {
3315
3988
  signatureInSchema[schemaPath] = 'unknown';
@@ -3325,7 +3998,108 @@ export class ScopeDataStructure {
3325
3998
 
3326
3999
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
3327
4000
 
3328
- return tempScopeNode.schema;
4001
+ // After validateSchema has filled in types, propagate nested paths from
4002
+ // variables to their signature equivalents.
4003
+ // e.g., workouts[].activity_type -> signature[0].workouts[].activity_type
4004
+ //
4005
+ // Build a map of variable names that are equivalent to signature paths
4006
+ // e.g., { 'workouts': 'signature[0].workouts' }
4007
+ const variableToSignatureMap: Record<string, string> = {};
4008
+
4009
+ for (const equivalenceKey in equivalencies ?? {}) {
4010
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
4011
+ const schemaPath = equivalenceValue.schemaPath;
4012
+ // Track which variables map to signature paths
4013
+ // equivalenceKey is the variable name (e.g., 'workouts')
4014
+ // schemaPath is where it comes from (e.g., 'signature[0].workouts')
4015
+ if (
4016
+ schemaPath.startsWith('signature[') &&
4017
+ equivalenceValue.scopeNodeName === scopeName
4018
+ ) {
4019
+ variableToSignatureMap[equivalenceKey] = schemaPath;
4020
+ }
4021
+ }
4022
+ }
4023
+
4024
+ // Enrich schema with deeply nested paths from internal function call scopes.
4025
+ // When a function call like traverse(tree) exists, and traverse's scope has
4026
+ // signature[0].children[path][entityName] (from propagateParameterToSignaturePaths),
4027
+ // we need to map those paths back to the argument variable (tree) in this scope.
4028
+ // This handles cases where cycle detection prevented the equivalency chain from
4029
+ // propagating deep paths during Phase 2 batch queue processing.
4030
+ for (const equivalenceKey in equivalencies ?? {}) {
4031
+ // Look for keys matching function call pattern: funcName(...).signature[N]
4032
+ const funcCallMatch = equivalenceKey.match(
4033
+ /^([^(]+)\(.*?\)\.(signature\[\d+\])$/,
4034
+ );
4035
+ if (!funcCallMatch) continue;
4036
+
4037
+ const calledFunctionName = funcCallMatch[1];
4038
+ const signatureParam = funcCallMatch[2]; // e.g., "signature[0]"
4039
+
4040
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
4041
+ if (equivalenceValue.scopeNodeName !== scopeName) continue;
4042
+
4043
+ const targetVariable = equivalenceValue.schemaPath;
4044
+
4045
+ // Get the called function's schema (includes propagated parameter paths)
4046
+ const childSchema = this.getSchema({
4047
+ scopeName: calledFunctionName,
4048
+ });
4049
+ if (!childSchema) continue;
4050
+
4051
+ // Map child function's signature paths to parent variable paths
4052
+ const sigPrefix = signatureParam + '.';
4053
+ const sigBracketPrefix = signatureParam + '[';
4054
+ for (const childKey in childSchema) {
4055
+ let suffix: string | null = null;
4056
+ if (childKey.startsWith(sigPrefix)) {
4057
+ suffix = childKey.slice(signatureParam.length);
4058
+ } else if (childKey.startsWith(sigBracketPrefix)) {
4059
+ suffix = childKey.slice(signatureParam.length);
4060
+ }
4061
+
4062
+ if (suffix !== null) {
4063
+ const parentKey = targetVariable + suffix;
4064
+ if (!schema[parentKey]) {
4065
+ schema[parentKey] = childSchema[childKey];
4066
+ }
4067
+ }
4068
+ }
4069
+ }
4070
+ }
4071
+
4072
+ // Propagate nested paths from variables to their signature equivalents
4073
+ // e.g., if workouts = signature[0].workouts, then workouts[].title becomes
4074
+ // signature[0].workouts[].title
4075
+ for (const schemaKey in schema) {
4076
+ // Skip keys that already start with signature[
4077
+ if (schemaKey.startsWith('signature[')) continue;
4078
+
4079
+ // Check if this key starts with a variable that maps to a signature path
4080
+ for (const [variableName, signaturePath] of Object.entries(
4081
+ variableToSignatureMap,
4082
+ )) {
4083
+ // Check if schemaKey starts with variableName followed by a property accessor
4084
+ // e.g., 'workouts[]' starts with 'workouts'
4085
+ if (
4086
+ schemaKey === variableName ||
4087
+ schemaKey.startsWith(variableName + '.') ||
4088
+ schemaKey.startsWith(variableName + '[')
4089
+ ) {
4090
+ // Transform the path: replace the variable prefix with the signature path
4091
+ const suffix = schemaKey.slice(variableName.length);
4092
+ const signatureKey = signaturePath + suffix;
4093
+
4094
+ // Add to schema if not already present
4095
+ if (!tempScopeNode.schema[signatureKey]) {
4096
+ tempScopeNode.schema[signatureKey] = schema[schemaKey];
4097
+ }
4098
+ }
4099
+ }
4100
+ }
4101
+
4102
+ return this.filterDuplicateKeys(tempScopeNode.schema);
3329
4103
  }
3330
4104
 
3331
4105
  getReturnValue({
@@ -3335,6 +4109,15 @@ export class ScopeDataStructure {
3335
4109
  functionName?: string;
3336
4110
  fillInUnknowns?: boolean;
3337
4111
  }) {
4112
+ // Trigger finalization on all managers to apply any pending updates
4113
+ // (e.g., ref type propagation to external function call schemas)
4114
+ const rootScope = this.scopeNodes[this.scopeTreeManager.getRootName()];
4115
+ if (rootScope) {
4116
+ for (const manager of this.equivalencyManagers) {
4117
+ manager.finalize(rootScope, this);
4118
+ }
4119
+ }
4120
+
3338
4121
  const scopeName = functionName ?? this.scopeTreeManager.getRootName();
3339
4122
  const scopeNode = this.scopeNodes[scopeName];
3340
4123
 
@@ -3345,7 +4128,8 @@ export class ScopeDataStructure {
3345
4128
  scopeNode: scopeNode,
3346
4129
  });
3347
4130
  } else {
3348
- for (const externalFunctionCall of this.externalFunctionCalls) {
4131
+ // Use getExternalFunctionCalls() which cleans cyScope from schemas
4132
+ for (const externalFunctionCall of this.getExternalFunctionCalls()) {
3349
4133
  const functionNameParts = this.splitPath(functionName).map((p) =>
3350
4134
  this.functionOrScopeName(p),
3351
4135
  );
@@ -3377,7 +4161,17 @@ export class ScopeDataStructure {
3377
4161
  // Include function paths even if their return value wasn't captured
3378
4162
  // This ensures methods like onAuthStateChange are included in the schema
3379
4163
  // But exclude signature entries (they should only be included via functionCallReturnValue paths)
3380
- (schema[key] === 'function' && key.indexOf('signature[') === -1),
4164
+ // Also exclude bare function call signatures - paths that are JUST a call like
4165
+ // "useCustomSizes(projectSlug)" should not be included as return values.
4166
+ // These represent "the function exists" not actual return data, and including
4167
+ // them causes nested path bugs in dependencySchemas.
4168
+ (schema[key] === 'function' &&
4169
+ key.indexOf('signature[') === -1 &&
4170
+ // Exclude bare call signatures: function calls with no dots OUTSIDE parentheses
4171
+ // e.g., "useCustomSizes(projectSlug)" is bare (exclude)
4172
+ // e.g., "loadProject({nested.property})" is bare - dots are inside args (exclude)
4173
+ // e.g., "getSupabase().auth.method()" has dots outside - method chain (include)
4174
+ !this.isBareCallSignature(key)),
3381
4175
  )
3382
4176
  .reduce(
3383
4177
  (acc, key) => {
@@ -3387,7 +4181,10 @@ export class ScopeDataStructure {
3387
4181
  for (const path in schema) {
3388
4182
  const pathParts = this.splitPath(path);
3389
4183
  if (pathParts.every((p, i) => keyParts[i] === p)) {
3390
- acc[path] = schema[path];
4184
+ // Also exclude bare call signatures from prefix paths
4185
+ if (!this.isBareCallSignature(path)) {
4186
+ acc[path] = schema[path];
4187
+ }
3391
4188
  }
3392
4189
  }
3393
4190
 
@@ -3401,14 +4198,73 @@ export class ScopeDataStructure {
3401
4198
 
3402
4199
  const tempScopeNode = this.createTempScopeNode(scopeName, resolvedSchema);
3403
4200
 
4201
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
4202
+ // during this "getter" method. See comment in getFunctionSignature.
4203
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
4204
+ this.onlyEquivalencies = true;
3404
4205
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
4206
+ this.onlyEquivalencies = wasOnlyEquivalencies;
4207
+
4208
+ // Remove bare call signatures from the return value schema.
4209
+ // fillInSchemaGapsAndUnknowns may add parent paths like "useCustomSizes(projectSlug)"
4210
+ // when it sees "useCustomSizes(projectSlug).functionCallReturnValue". These bare
4211
+ // call signatures represent "the function exists" not actual return data, and
4212
+ // including them causes nested path bugs in dependencySchemas.
4213
+ const resultSchema = tempScopeNode.schema;
4214
+ for (const key of Object.keys(resultSchema)) {
4215
+ if (this.isBareCallSignature(key)) {
4216
+ delete resultSchema[key];
4217
+ }
4218
+ }
3405
4219
 
3406
- return tempScopeNode.schema;
4220
+ return resultSchema;
4221
+ }
4222
+
4223
+ /**
4224
+ * Checks if a schema key is a "bare call signature" - a function call with no
4225
+ * method chain before it and no path segments after it.
4226
+ *
4227
+ * A bare call signature represents "this function exists" rather than actual
4228
+ * return data, and including them causes nested path bugs in dependencySchemas.
4229
+ *
4230
+ * Examples:
4231
+ * - "useCustomSizes(projectSlug)" -> bare (true)
4232
+ * - "loadProject({nested.property})" -> bare (dots are inside args, true)
4233
+ * - "getSupabase().auth.method()" -> not bare (has dots outside parens, false)
4234
+ * - "useProject().functionCallReturnValue" -> not bare (has path after, false)
4235
+ */
4236
+ private isBareCallSignature(key: string): boolean {
4237
+ // Must end with ) and contain ( to be a call
4238
+ if (!key.endsWith(')') || key.indexOf('(') === -1) {
4239
+ return false;
4240
+ }
4241
+
4242
+ // Check if there are any dots OUTSIDE of parentheses
4243
+ // Strip out content inside balanced parentheses, then check for dots
4244
+ let depth = 0;
4245
+ let hasDotsOutsideParens = false;
4246
+
4247
+ for (let i = 0; i < key.length; i++) {
4248
+ const char = key[i];
4249
+ if (char === '(') {
4250
+ depth++;
4251
+ } else if (char === ')') {
4252
+ depth--;
4253
+ } else if (char === '.' && depth === 0) {
4254
+ hasDotsOutsideParens = true;
4255
+ break;
4256
+ }
4257
+ }
4258
+
4259
+ // It's a bare call signature if there are no dots outside parentheses
4260
+ return !hasDotsOutsideParens;
3407
4261
  }
3408
4262
 
3409
4263
  /**
3410
4264
  * Replaces cyScope placeholder references (e.g., cyScope10()) in schema keys
3411
4265
  * with the actual callback function text from the corresponding scope node.
4266
+ * If the scope text can't be found, uses a generic fallback to avoid leaking
4267
+ * internal cyScope names into stored data.
3412
4268
  */
3413
4269
  private replaceCyScopePlaceholders(
3414
4270
  schema: Record<string, string>,
@@ -3424,10 +4280,10 @@ export class ScopeDataStructure {
3424
4280
  for (const match of matches) {
3425
4281
  const cyScopeName = `cyScope${match[1]}`;
3426
4282
  const scopeText = this.findCyScopeText(cyScopeName);
3427
- if (scopeText) {
3428
- // Replace cyScope10() with the actual callback text
3429
- newKey = newKey.replace(match[0], scopeText);
3430
- }
4283
+ // Always replace cyScope references - use actual text if available,
4284
+ // otherwise use a generic callback placeholder
4285
+ const replacement = scopeText || '() => {}';
4286
+ newKey = newKey.replace(match[0], replacement);
3431
4287
  }
3432
4288
 
3433
4289
  result[newKey] = value;
@@ -3485,18 +4341,419 @@ export class ScopeDataStructure {
3485
4341
  return scopeText;
3486
4342
  }
3487
4343
 
3488
- getEquivalentSignatureVariables() {
4344
+ getEquivalentSignatureVariables(): Record<string, string | string[]> {
3489
4345
  const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
3490
4346
 
3491
- const equivalentSignatureVariables: Record<string, string> = {};
4347
+ const equivalentSignatureVariables: Record<string, string | string[]> = {};
4348
+
4349
+ // Helper to add equivalencies - accumulates into array if multiple values for same key
4350
+ // This is critical for OR expressions like `x = a || b` where x should map to both a and b
4351
+ const addEquivalency = (key: string, value: string) => {
4352
+ const existing = equivalentSignatureVariables[key];
4353
+ if (existing === undefined) {
4354
+ // First value - store as string
4355
+ equivalentSignatureVariables[key] = value;
4356
+ } else if (typeof existing === 'string') {
4357
+ if (existing !== value) {
4358
+ // Second different value - convert to array
4359
+ equivalentSignatureVariables[key] = [existing, value];
4360
+ }
4361
+ // Same value - no change needed
4362
+ } else {
4363
+ // Already an array - add if not already present
4364
+ if (!existing.includes(value)) {
4365
+ existing.push(value);
4366
+ }
4367
+ }
4368
+ };
4369
+
3492
4370
  for (const [path, equivalentValues] of Object.entries(
3493
4371
  scopeNode.equivalencies,
3494
4372
  )) {
3495
4373
  for (const equivalentValue of equivalentValues) {
4374
+ // Case 1: Props/signature equivalencies (existing behavior)
4375
+ // Maps local variable names to their signature paths
4376
+ // e.g., "propValue" -> "signature[0].prop"
3496
4377
  if (path.startsWith('signature[')) {
3497
- equivalentSignatureVariables[equivalentValue.schemaPath] = path;
4378
+ addEquivalency(equivalentValue.schemaPath, path);
4379
+ }
4380
+
4381
+ // Case 2: Hook variable equivalencies (new behavior)
4382
+ // The equivalencies are stored as: path = variable name, schemaPath = data source
4383
+ // e.g., path = "debugFetcher", schemaPath = "useFetcher<...>().functionCallReturnValue"
4384
+ // We need to map: "debugFetcher" -> "useFetcher<...>()"
4385
+ // This enables resolving paths like "debugFetcher.state" to
4386
+ // "useFetcher<...>().state" for execution flow validation
4387
+ if (equivalentValue.schemaPath.endsWith('.functionCallReturnValue')) {
4388
+ // Extract the hook call path (everything before .functionCallReturnValue)
4389
+ let hookCallPath = equivalentValue.schemaPath.slice(
4390
+ 0,
4391
+ -'.functionCallReturnValue'.length,
4392
+ );
4393
+ // Only include if it looks like a hook call (contains parentheses)
4394
+ // and the variable name (path) is a simple identifier (no dots)
4395
+ if (hookCallPath.includes('(') && !path.includes('.')) {
4396
+ // Special case: If hookCallPath is a callback scope (cyScope pattern),
4397
+ // trace through it to find what the callback actually returns.
4398
+ // This handles useState(() => { return prop; }) patterns.
4399
+ const cyScopeMatch = hookCallPath.match(/^(cyScope\d+)\(\)$/);
4400
+ if (cyScopeMatch) {
4401
+ // Use the equivalency database to trace the callback's return value
4402
+ // to its actual source (e.g., viewModeFromUrl -> segments -> params -> useParams)
4403
+ const dbEntry = this.getEquivalenciesDatabaseEntry(
4404
+ scopeNode.name, // Component scope
4405
+ path, // variable name (e.g., viewMode)
4406
+ );
4407
+ if (dbEntry?.sourceCandidates?.length > 0) {
4408
+ // Use the traced source instead of the callback scope
4409
+ hookCallPath = dbEntry.sourceCandidates[0].schemaPath;
4410
+ }
4411
+ }
4412
+ addEquivalency(path, hookCallPath);
4413
+ }
4414
+ }
4415
+
4416
+ // Case 3: Destructured variables from local variables
4417
+ // e.g., const { scenarios } = currentEntityAnalysis;
4418
+ // This creates: path = "scenarios", schemaPath = "currentEntityAnalysis.scenarios"
4419
+ // We need to map: "scenarios" -> "currentEntityAnalysis.scenarios"
4420
+ // AND resolve transitively if currentEntityAnalysis is itself equivalent to a hook call
4421
+ if (
4422
+ !path.includes('.') && // path is a simple identifier
4423
+ !equivalentValue.schemaPath.startsWith('signature[') && // not a signature path
4424
+ !equivalentValue.schemaPath.endsWith('.functionCallReturnValue') // not already handled above
4425
+ ) {
4426
+ // Add equivalency (will accumulate if multiple values for OR expressions)
4427
+ addEquivalency(path, equivalentValue.schemaPath);
4428
+ }
4429
+
4430
+ // Case 4: Child component prop mappings (Fix 22)
4431
+ // When parent renders <ChildComponent prop={value} />, we get equivalencies like:
4432
+ // path = "ChildComponent().signature[0].prop"
4433
+ // schemaPath = "value" (the variable passed as the prop)
4434
+ // We need to include these so translateChildPathToParent can work.
4435
+ // Pattern: ComponentName().signature[N] or ComponentName().signature[N].propName
4436
+ if (
4437
+ path.includes('().signature[') &&
4438
+ !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable, not a function call
4439
+ ) {
4440
+ addEquivalency(path, equivalentValue.schemaPath);
4441
+ }
4442
+
4443
+ // Case 5: Destructured function parameters (Fix 25)
4444
+ // When a function has destructured props: function Comp({ propA, propB }: Props)
4445
+ // We get equivalencies like:
4446
+ // path = "propA" (the destructured variable name)
4447
+ // schemaPath = "signature[0].propA" (the signature path)
4448
+ // We need to map: "propA" -> "signature[0].propA"
4449
+ // This enables translateChildPathToParent to resolve child variable paths
4450
+ // to their signature paths when merging execution flows.
4451
+ if (
4452
+ !path.includes('.') && // path is a simple identifier (destructured prop name)
4453
+ equivalentValue.schemaPath.startsWith('signature[') // schemaPath IS a signature path
4454
+ ) {
4455
+ addEquivalency(path, equivalentValue.schemaPath);
4456
+ }
4457
+
4458
+ // Case 7: Method calls on variables that result in .functionCallReturnValue (Fix 33)
4459
+ // When we have patterns like:
4460
+ // path = "segments" (simple identifier)
4461
+ // schemaPath = "splat.split('/').functionCallReturnValue"
4462
+ // This is a method call on a variable (not a hook call), but we still need to
4463
+ // track it so transitive resolution can resolve `splat` to its actual source.
4464
+ // E.g., if splat -> useParams().functionCallReturnValue['*'], then
4465
+ // segments -> useParams().functionCallReturnValue['*'].split('/').functionCallReturnValue
4466
+ if (
4467
+ !path.includes('.') && // path is a simple identifier
4468
+ equivalentValue.schemaPath.endsWith('.functionCallReturnValue') && // ends with function return
4469
+ equivalentValue.schemaPath.includes('.') // has property access (method call)
4470
+ ) {
4471
+ // Check if this looks like a method call on a variable (not a hook call)
4472
+ // Hook calls look like: hookName() or hookName<T>()
4473
+ // Method calls look like: variable.method() or variable.method<T>()
4474
+ const hookCallPath = equivalentValue.schemaPath.slice(
4475
+ 0,
4476
+ -'.functionCallReturnValue'.length,
4477
+ );
4478
+ // If it's a method call (contains a dot before the parenthesis), include it
4479
+ const dotBeforeParen = hookCallPath.indexOf('.');
4480
+ const parenPos = hookCallPath.indexOf('(');
4481
+ if (dotBeforeParen !== -1 && dotBeforeParen < parenPos) {
4482
+ // This is a method call like "splat.split('/')", not a hook call
4483
+ addEquivalency(path, equivalentValue.schemaPath);
4484
+ }
4485
+ }
4486
+ }
4487
+ }
4488
+
4489
+ // Case 6: Collect JSX child prop equivalencies from child scopes (Fix 26)
4490
+ // When a parent component renders <ChildComponent prop={value} />, the JSX
4491
+ // return statement may be in a child scope (e.g., cyScope2). The equivalencies
4492
+ // like ChildComponent().signature[0].prop -> value get stored in that child scope.
4493
+ // But translateChildPathToParent needs to find them from the parent scope's context.
4494
+ // So we collect Case 4 patterns from ALL child scopes that belong to this root scope.
4495
+ const rootName = this.scopeTreeManager.getRootName();
4496
+ for (const [scopeName, childScopeNode] of Object.entries(this.scopeNodes)) {
4497
+ // Skip the root scope (already processed above)
4498
+ if (scopeName === rootName) continue;
4499
+
4500
+ // Only include scopes that are children of the root (their tree includes root)
4501
+ if (!childScopeNode.tree?.includes(rootName)) continue;
4502
+
4503
+ // Look for Case 4 patterns in the child scope
4504
+ for (const [path, equivalentValues] of Object.entries(
4505
+ childScopeNode.equivalencies || {},
4506
+ )) {
4507
+ for (const equivalentValue of equivalentValues) {
4508
+ // Case 4 pattern: ChildComponent().signature[0].propName -> parentVariable
4509
+ if (
4510
+ path.includes('().signature[') &&
4511
+ !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable
4512
+ ) {
4513
+ // Only add if not already present from the root scope
4514
+ // Root scope values take precedence over child scope values
4515
+ if (!(path in equivalentSignatureVariables)) {
4516
+ addEquivalency(path, equivalentValue.schemaPath);
4517
+ }
4518
+ }
4519
+ }
4520
+ }
4521
+ }
4522
+
4523
+ // Transitive resolution: Resolve variable chains through multiple levels
4524
+ // E.g., analysis → currentEntityAnalysis → useLoaderData().functionCallReturnValue.currentEntityAnalysis
4525
+ // We need multiple passes because resolutions can depend on each other
4526
+ const maxIterations = 5; // Prevent infinite loops
4527
+
4528
+ // Helper function to resolve a single source path using equivalencies
4529
+ const resolveSourcePath = (
4530
+ sourcePath: string,
4531
+ equivMap: Record<string, string | string[]>,
4532
+ ): string | null => {
4533
+ // Extract base variable from the path
4534
+ const dotIndex = sourcePath.indexOf('.');
4535
+ const bracketIndex = sourcePath.indexOf('[');
4536
+
4537
+ let baseVar: string;
4538
+ let rest: string;
4539
+
4540
+ if (dotIndex === -1 && bracketIndex === -1) {
4541
+ baseVar = sourcePath;
4542
+ rest = '';
4543
+ } else if (dotIndex === -1) {
4544
+ baseVar = sourcePath.slice(0, bracketIndex);
4545
+ rest = sourcePath.slice(bracketIndex);
4546
+ } else if (bracketIndex === -1) {
4547
+ baseVar = sourcePath.slice(0, dotIndex);
4548
+ rest = sourcePath.slice(dotIndex);
4549
+ } else {
4550
+ const firstIndex = Math.min(dotIndex, bracketIndex);
4551
+ baseVar = sourcePath.slice(0, firstIndex);
4552
+ rest = sourcePath.slice(firstIndex);
4553
+ }
4554
+
4555
+ // Look up the base variable in equivalencies
4556
+ if (baseVar in equivMap && equivMap[baseVar] !== sourcePath) {
4557
+ const baseResolved = equivMap[baseVar];
4558
+ // Skip if baseResolved is an array (handle later)
4559
+ if (Array.isArray(baseResolved)) return null;
4560
+ // If it resolves to a signature path, build the full resolved path
4561
+ if (
4562
+ baseResolved.startsWith('signature[') ||
4563
+ baseResolved.includes('()')
4564
+ ) {
4565
+ if (baseResolved.endsWith('()')) {
4566
+ return baseResolved + '.functionCallReturnValue' + rest;
4567
+ }
4568
+ return baseResolved + rest;
4569
+ }
4570
+ }
4571
+ return null;
4572
+ };
4573
+
4574
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
4575
+ let changed = false;
4576
+
4577
+ for (const [varName, sourcePathOrArray] of Object.entries(
4578
+ equivalentSignatureVariables,
4579
+ )) {
4580
+ // Handle arrays (OR expressions) by resolving each element
4581
+ if (Array.isArray(sourcePathOrArray)) {
4582
+ const resolvedArray: string[] = [];
4583
+ let arrayChanged = false;
4584
+ for (const sourcePath of sourcePathOrArray) {
4585
+ // Try to resolve this path using transitive resolution
4586
+ const resolved = resolveSourcePath(
4587
+ sourcePath,
4588
+ equivalentSignatureVariables,
4589
+ );
4590
+ if (resolved && resolved !== sourcePath) {
4591
+ resolvedArray.push(resolved);
4592
+ arrayChanged = true;
4593
+ } else {
4594
+ resolvedArray.push(sourcePath);
4595
+ }
4596
+ }
4597
+ if (arrayChanged) {
4598
+ equivalentSignatureVariables[varName] = resolvedArray;
4599
+ changed = true;
4600
+ }
4601
+ continue;
4602
+ }
4603
+ const sourcePath = sourcePathOrArray;
4604
+
4605
+ // Skip if already fully resolved (contains function call syntax)
4606
+ // BUT first check for computed value patterns that need resolution (Fix 28)
4607
+ // AND method call patterns that need base variable resolution (Fix 33)
4608
+ if (sourcePath.includes('()')) {
4609
+ // Fix 28: Handle computed value patterns with dependency arrays
4610
+ // Patterns like `functionName(arg, [dep1, dep2, ...])` are NOT controllable
4611
+ // data sources. We trace through the dependencies to find controllable sources.
4612
+ const bracketStart = sourcePath.indexOf('[');
4613
+ const bracketEnd = sourcePath.lastIndexOf(']');
4614
+
4615
+ if (bracketStart !== -1 && bracketEnd > bracketStart) {
4616
+ const arrayContent = sourcePath.slice(bracketStart + 1, bracketEnd);
4617
+ const items = arrayContent.split(',').map((s) => s.trim());
4618
+
4619
+ // Only process if this looks like a dependency array:
4620
+ // multiple items that are all simple identifiers (not numbers or expressions)
4621
+ const isIdentifier = (s: string) =>
4622
+ /^\w+$/.test(s) && !/^\d+$/.test(s);
4623
+ if (items.length > 1 && items.every(isIdentifier)) {
4624
+ // Look for a dependency that's already resolved to a controllable source
4625
+ for (const dep of items) {
4626
+ if (dep in equivalentSignatureVariables) {
4627
+ const resolvedDep = equivalentSignatureVariables[dep];
4628
+ // Use if it's a controllable path (contains hook call)
4629
+ // and is NOT another unresolved computed pattern (has comma-separated deps)
4630
+ const hasCommaInBrackets =
4631
+ resolvedDep.includes('[') &&
4632
+ resolvedDep.includes(',') &&
4633
+ resolvedDep.indexOf(',') > resolvedDep.indexOf('[');
4634
+ if (resolvedDep.includes('()') && !hasCommaInBrackets) {
4635
+ // Computed value is typically an element from an array
4636
+ equivalentSignatureVariables[varName] = resolvedDep + '[]';
4637
+ changed = true;
4638
+ break;
4639
+ }
4640
+ }
4641
+ }
4642
+ }
4643
+ }
4644
+
4645
+ // Fix 33: Handle method call patterns on variables
4646
+ // Patterns like: "splat.split('/').functionCallReturnValue"
4647
+ // We need to resolve the base variable (splat) to its actual source
4648
+ // Check if this is a method call on a variable (dot before first parenthesis)
4649
+ const dotIndex = sourcePath.indexOf('.');
4650
+ const parenIndex = sourcePath.indexOf('(');
4651
+ if (
4652
+ dotIndex !== -1 &&
4653
+ dotIndex < parenIndex &&
4654
+ !sourcePath.startsWith('use') // Not a hook call like useState()
4655
+ ) {
4656
+ // Extract the base variable (before the first dot)
4657
+ const baseVar = sourcePath.slice(0, dotIndex);
4658
+ const rest = sourcePath.slice(dotIndex); // includes ".method(...).functionCallReturnValue"
4659
+
4660
+ // Check if the base variable can be resolved
4661
+ if (
4662
+ baseVar in equivalentSignatureVariables &&
4663
+ baseVar !== varName
4664
+ ) {
4665
+ const baseResolved = equivalentSignatureVariables[baseVar];
4666
+ // Skip if baseResolved is an array (OR expression)
4667
+ if (Array.isArray(baseResolved)) continue;
4668
+ // Only resolve if the base resolved to something useful (contains () or .)
4669
+ if (baseResolved.includes('()') || baseResolved.includes('.')) {
4670
+ const newPath = baseResolved + rest;
4671
+ if (newPath !== equivalentSignatureVariables[varName]) {
4672
+ equivalentSignatureVariables[varName] = newPath;
4673
+ changed = true;
4674
+ }
4675
+ }
4676
+ }
4677
+ }
4678
+
4679
+ // Fix 38: Handle cyScope lazy initializer return values
4680
+ // When we have viewMode -> cyScope20(), trace through to find what cyScope20 returns.
4681
+ // The lazy initializer's return value should be the controllable data source.
4682
+ // Pattern: cyScopeN() where N is a number
4683
+ const cyScopeMatch = sourcePath.match(/^(cyScope\d+)\(\)$/);
4684
+ if (cyScopeMatch) {
4685
+ const cyScopeName = cyScopeMatch[1];
4686
+ const cyScopeNode = this.scopeNodes[cyScopeName];
4687
+
4688
+ if (cyScopeNode?.equivalencies) {
4689
+ // Look for returnValue equivalency in the cyScope
4690
+ const returnValueEquivs =
4691
+ cyScopeNode.equivalencies['returnValue'];
4692
+ if (returnValueEquivs && returnValueEquivs.length > 0) {
4693
+ // Get the first return value source
4694
+ const returnSource = returnValueEquivs[0].schemaPath;
4695
+
4696
+ // If the return source is a simple variable (not a complex path),
4697
+ // resolve varName directly to that variable
4698
+ if (
4699
+ returnSource &&
4700
+ !returnSource.includes('(') &&
4701
+ !returnSource.includes('[')
4702
+ ) {
4703
+ // Update varName to point to the return source
4704
+ if (equivalentSignatureVariables[varName] !== returnSource) {
4705
+ equivalentSignatureVariables[varName] = returnSource;
4706
+ changed = true;
4707
+ }
4708
+ }
4709
+ }
4710
+ }
4711
+ }
4712
+
4713
+ continue;
4714
+ }
4715
+
4716
+ // Check if the source path starts with a variable that's also in the map
4717
+ const dotIndex = sourcePath.indexOf('.');
4718
+ let baseVar: string;
4719
+ let rest: string;
4720
+
4721
+ if (dotIndex > 0) {
4722
+ // Path has a dot: "a.b.c" -> baseVar="a", rest=".b.c"
4723
+ baseVar = sourcePath.slice(0, dotIndex);
4724
+ rest = sourcePath.slice(dotIndex); // includes the leading dot
4725
+ } else {
4726
+ // Path is a simple identifier: "currentEntityAnalysis" -> baseVar="currentEntityAnalysis", rest=""
4727
+ baseVar = sourcePath;
4728
+ rest = '';
4729
+ }
4730
+
4731
+ if (baseVar in equivalentSignatureVariables && baseVar !== varName) {
4732
+ // Handle array case (OR expressions) - use first element
4733
+ const rawBaseResolved = equivalentSignatureVariables[baseVar];
4734
+ const baseResolved = Array.isArray(rawBaseResolved)
4735
+ ? rawBaseResolved[0]
4736
+ : rawBaseResolved;
4737
+ if (!baseResolved) continue;
4738
+ // If the base resolves to a hook call, add .functionCallReturnValue
4739
+ if (baseResolved.endsWith('()')) {
4740
+ const newPath = baseResolved + '.functionCallReturnValue' + rest;
4741
+ if (newPath !== equivalentSignatureVariables[varName]) {
4742
+ equivalentSignatureVariables[varName] = newPath;
4743
+ changed = true;
4744
+ }
4745
+ } else if (baseResolved !== sourcePath) {
4746
+ const newPath = baseResolved + rest;
4747
+ if (newPath !== equivalentSignatureVariables[varName]) {
4748
+ equivalentSignatureVariables[varName] = newPath;
4749
+ changed = true;
4750
+ }
4751
+ }
3498
4752
  }
3499
4753
  }
4754
+
4755
+ // Stop if no changes were made in this iteration
4756
+ if (!changed) break;
3500
4757
  }
3501
4758
 
3502
4759
  return equivalentSignatureVariables;
@@ -3549,7 +4806,12 @@ export class ScopeDataStructure {
3549
4806
  relevantSchema,
3550
4807
  );
3551
4808
 
4809
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
4810
+ // during this "getter" method. See comment in getFunctionSignature.
4811
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
4812
+ this.onlyEquivalencies = true;
3552
4813
  this.validateSchema(tempScopeNode, true, final);
4814
+ this.onlyEquivalencies = wasOnlyEquivalencies;
3553
4815
 
3554
4816
  return {
3555
4817
  name: variableName,
@@ -3558,8 +4820,123 @@ export class ScopeDataStructure {
3558
4820
  };
3559
4821
  }
3560
4822
 
3561
- getExternalFunctionCalls() {
3562
- return this.externalFunctionCalls;
4823
+ getExternalFunctionCalls(): FunctionCallInfo[] {
4824
+ // Replace cyScope placeholders in all external function call data
4825
+ // This ensures call signatures and schema paths use actual callback text
4826
+ // instead of internal cyScope names, preventing mock data merge conflicts.
4827
+ return this.externalFunctionCalls.map((efc) =>
4828
+ this.cleanCyScopeFromFunctionCallInfo(efc),
4829
+ );
4830
+ }
4831
+
4832
+ /**
4833
+ * Cleans cyScope placeholder references from a FunctionCallInfo.
4834
+ * Replaces cyScopeN() with the actual callback text in:
4835
+ * - callSignature
4836
+ * - allCallSignatures
4837
+ * - schema keys
4838
+ */
4839
+ private cleanCyScopeFromFunctionCallInfo(
4840
+ efc: FunctionCallInfo,
4841
+ ): FunctionCallInfo {
4842
+ const cyScopePattern = /cyScope\d+\(\)/g;
4843
+
4844
+ // Check if any cleaning is needed
4845
+ const hasCyScope =
4846
+ cyScopePattern.test(efc.callSignature) ||
4847
+ (efc.allCallSignatures &&
4848
+ efc.allCallSignatures.some((sig) => /cyScope\d+\(\)/.test(sig))) ||
4849
+ (efc.schema &&
4850
+ Object.keys(efc.schema).some((key) => /cyScope\d+\(\)/.test(key)));
4851
+
4852
+ if (!hasCyScope) {
4853
+ return efc;
4854
+ }
4855
+
4856
+ // Create cleaned copy
4857
+ const cleaned: FunctionCallInfo = { ...efc };
4858
+
4859
+ // Clean callSignature
4860
+ cleaned.callSignature = this.replaceCyScopeInString(efc.callSignature);
4861
+
4862
+ // Clean allCallSignatures
4863
+ if (efc.allCallSignatures) {
4864
+ cleaned.allCallSignatures = efc.allCallSignatures.map((sig) =>
4865
+ this.replaceCyScopeInString(sig),
4866
+ );
4867
+ }
4868
+
4869
+ // Clean schema keys
4870
+ if (efc.schema) {
4871
+ cleaned.schema = this.replaceCyScopePlaceholders(efc.schema);
4872
+ }
4873
+
4874
+ // Clean callSignatureToVariable keys
4875
+ if (efc.callSignatureToVariable) {
4876
+ cleaned.callSignatureToVariable = Object.entries(
4877
+ efc.callSignatureToVariable,
4878
+ ).reduce(
4879
+ (acc, [key, value]) => {
4880
+ acc[this.replaceCyScopeInString(key)] = value;
4881
+ return acc;
4882
+ },
4883
+ {} as Record<string, string>,
4884
+ );
4885
+ }
4886
+
4887
+ return cleaned;
4888
+ }
4889
+
4890
+ /**
4891
+ * Replaces cyScope placeholder references in a single string.
4892
+ * If the scope text can't be found, uses a generic fallback to avoid leaking
4893
+ * internal cyScope names into stored data.
4894
+ *
4895
+ * Handles two patterns:
4896
+ * 1. Function call style: cyScope7() - matched by cyScope(\d+)\(\)
4897
+ * 2. Scope name style: parentName____cyScopeXX or cyScopeXX - matched by (\w+____)?cyScope([0-9A-Fa-f]+)
4898
+ */
4899
+ private replaceCyScopeInString(str: string): string {
4900
+ let result = str;
4901
+
4902
+ // Pattern 1: Function call style - cyScope7()
4903
+ const functionCallPattern = /cyScope(\d+)\(\)/g;
4904
+ const functionCallMatches = [...str.matchAll(functionCallPattern)];
4905
+ for (const match of functionCallMatches) {
4906
+ const cyScopeName = `cyScope${match[1]}`;
4907
+ const scopeText = this.findCyScopeText(cyScopeName);
4908
+ // Always replace cyScope references - use actual text if available,
4909
+ // otherwise use a generic callback placeholder
4910
+ const replacement = scopeText || '() => {}';
4911
+ result = result.replace(match[0], replacement);
4912
+ }
4913
+
4914
+ // Pattern 2: Scope name style - parentName____cyScopeXX or just cyScopeXX
4915
+ // This handles hex-encoded scope IDs like cyScope1F
4916
+ const scopeNamePattern = /(\w+____)?cyScope([0-9A-Fa-f]+)/g;
4917
+ const scopeNameMatches = [...result.matchAll(scopeNamePattern)];
4918
+ for (const match of scopeNameMatches) {
4919
+ const fullMatch = match[0];
4920
+ const prefix = match[1] || ''; // e.g., "getTitleColor____"
4921
+ const cyScopeId = match[2]; // e.g., "1F"
4922
+ const cyScopeName = `cyScope${cyScopeId}`;
4923
+
4924
+ // Try to find the scope text, checking both with and without prefix
4925
+ let scopeText = this.findCyScopeText(cyScopeName);
4926
+ if (!scopeText && prefix) {
4927
+ // Try looking up with the full prefixed name
4928
+ scopeText = this.findCyScopeText(`${prefix}${cyScopeName}`);
4929
+ }
4930
+
4931
+ if (scopeText) {
4932
+ result = result.replace(fullMatch, scopeText);
4933
+ } else {
4934
+ // Replace with a generic identifier to avoid leaking internal names
4935
+ result = result.replace(fullMatch, 'callback');
4936
+ }
4937
+ }
4938
+
4939
+ return result;
3563
4940
  }
3564
4941
 
3565
4942
  getEnvironmentVariables() {
@@ -3577,7 +4954,7 @@ export class ScopeDataStructure {
3577
4954
  path: string;
3578
4955
  conditionType: 'truthiness' | 'comparison' | 'switch';
3579
4956
  comparedValues?: string[];
3580
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
4957
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
3581
4958
  }>
3582
4959
  >,
3583
4960
  ): void {
@@ -3602,29 +4979,145 @@ export class ScopeDataStructure {
3602
4979
  }
3603
4980
 
3604
4981
  /**
3605
- * Get enriched conditional usages with source tracing.
3606
- * Uses explainPath to trace each local variable back to its data source.
4982
+ * Add conditional effects from AST analysis.
4983
+ * Called during scope analysis to collect all setter calls inside conditionals.
4984
+ */
4985
+ addConditionalEffects(
4986
+ effects: import('../astScopes/types').ConditionalEffect[],
4987
+ ): void {
4988
+ // Add effects, avoiding duplicates based on effect stateVariable and condition paths
4989
+ for (const effect of effects) {
4990
+ const exists = this.rawConditionalEffects.some((existing) => {
4991
+ // Same effect target (stateVariable + value)
4992
+ const sameEffect =
4993
+ existing.effect.stateVariable === effect.effect.stateVariable &&
4994
+ existing.effect.value === effect.effect.value;
4995
+ if (!sameEffect) return false;
4996
+
4997
+ // Same condition(s)
4998
+ if (existing.condition && effect.condition) {
4999
+ return (
5000
+ existing.condition.path === effect.condition.path &&
5001
+ existing.condition.requiredValue === effect.condition.requiredValue
5002
+ );
5003
+ }
5004
+ if (existing.conditions && effect.conditions) {
5005
+ if (existing.conditions.length !== effect.conditions.length)
5006
+ return false;
5007
+ return existing.conditions.every((ec, i) => {
5008
+ const newCond = effect.conditions![i];
5009
+ return (
5010
+ ec.path === newCond.path &&
5011
+ ec.requiredValue === newCond.requiredValue
5012
+ );
5013
+ });
5014
+ }
5015
+ return false;
5016
+ });
5017
+ if (!exists) {
5018
+ this.rawConditionalEffects.push(effect);
5019
+ }
5020
+ }
5021
+ }
5022
+
5023
+ /**
5024
+ * Get conditional effects collected during analysis.
5025
+ */
5026
+ getConditionalEffects(): import('../astScopes/types').ConditionalEffect[] {
5027
+ return this.rawConditionalEffects;
5028
+ }
5029
+
5030
+ /**
5031
+ * Add compound conditionals from AST analysis.
5032
+ * Called during scope analysis to collect grouped conditions (e.g., a && b && c).
5033
+ */
5034
+ addCompoundConditionals(
5035
+ compounds: import('../astScopes/types').CompoundConditional[],
5036
+ ): void {
5037
+ // Add compounds, avoiding duplicates based on chainId
5038
+ for (const compound of compounds) {
5039
+ const exists = this.rawCompoundConditionals.some(
5040
+ (existing) => existing.chainId === compound.chainId,
5041
+ );
5042
+ if (!exists) {
5043
+ this.rawCompoundConditionals.push(compound);
5044
+ }
5045
+ }
5046
+ }
5047
+
5048
+ /**
5049
+ * Get compound conditionals collected during analysis.
5050
+ */
5051
+ getCompoundConditionals(): import('../astScopes/types').CompoundConditional[] {
5052
+ return this.rawCompoundConditionals;
5053
+ }
5054
+
5055
+ /**
5056
+ * Add child boundary gating conditions from AST analysis.
5057
+ * These track which conditions must be true for a child component to render.
3607
5058
  */
3608
- getEnrichedConditionalUsages(): Record<
5059
+ addChildBoundaryGatingConditions(
5060
+ conditions: Record<string, import('../astScopes/types').ConditionalUsage[]>,
5061
+ ): void {
5062
+ for (const [childName, usages] of Object.entries(conditions)) {
5063
+ if (!this.rawChildBoundaryGatingConditions[childName]) {
5064
+ this.rawChildBoundaryGatingConditions[childName] = [];
5065
+ }
5066
+ // Add usages, avoiding duplicates
5067
+ for (const usage of usages) {
5068
+ const exists = this.rawChildBoundaryGatingConditions[childName].some(
5069
+ (existing) =>
5070
+ existing.path === usage.path &&
5071
+ existing.conditionType === usage.conditionType &&
5072
+ existing.isNegated === usage.isNegated,
5073
+ );
5074
+ if (!exists) {
5075
+ this.rawChildBoundaryGatingConditions[childName].push(usage);
5076
+ }
5077
+ }
5078
+ }
5079
+ }
5080
+
5081
+ /**
5082
+ * Get enriched child boundary gating conditions with source tracing.
5083
+ * Similar to getEnrichedConditionalUsages but for gating conditions.
5084
+ */
5085
+ getEnrichedChildBoundaryGatingConditions(): Record<
3609
5086
  string,
3610
- Array<{
3611
- path: string;
3612
- conditionType: 'truthiness' | 'comparison' | 'switch';
3613
- comparedValues?: string[];
3614
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
3615
- sourceDataPath?: string;
3616
- }>
5087
+ EnrichedConditionalUsage[]
3617
5088
  > {
3618
- const enriched: Record<
3619
- string,
3620
- Array<{
3621
- path: string;
3622
- conditionType: 'truthiness' | 'comparison' | 'switch';
3623
- comparedValues?: string[];
3624
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
3625
- sourceDataPath?: string;
3626
- }>
3627
- > = {};
5089
+ const enriched: Record<string, EnrichedConditionalUsage[]> = {};
5090
+ const rootScopeName = this.scopeTreeManager.getTree().name;
5091
+
5092
+ for (const [childName, usages] of Object.entries(
5093
+ this.rawChildBoundaryGatingConditions,
5094
+ )) {
5095
+ enriched[childName] = usages.map((usage) => {
5096
+ // Try to trace this path back to a data source
5097
+ const explanation = this.explainPath(rootScopeName, usage.path);
5098
+
5099
+ let sourceDataPath: string | undefined;
5100
+ if (explanation.source) {
5101
+ sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
5102
+ }
5103
+
5104
+ return {
5105
+ ...usage,
5106
+ sourceDataPath,
5107
+ };
5108
+ });
5109
+ }
5110
+
5111
+ return enriched;
5112
+ }
5113
+
5114
+ /**
5115
+ * Get enriched conditional usages with source tracing.
5116
+ * Uses explainPath to trace each local variable back to its data source.
5117
+ * Preserves all fields from the raw conditional usages including derivedFrom.
5118
+ */
5119
+ getEnrichedConditionalUsages(): Record<string, EnrichedConditionalUsage[]> {
5120
+ const enriched: Record<string, EnrichedConditionalUsage[]> = {};
3628
5121
 
3629
5122
  for (const [path, usages] of Object.entries(this.rawConditionalUsages)) {
3630
5123
  // Try to trace this path back to a data source
@@ -3647,35 +5140,86 @@ export class ScopeDataStructure {
3647
5140
  return enriched;
3648
5141
  }
3649
5142
 
5143
+ /**
5144
+ * Add JSX rendering usages from AST analysis.
5145
+ * These track arrays rendered via .map() and strings interpolated in JSX.
5146
+ */
5147
+ addJsxRenderingUsages(
5148
+ usages: import('../astScopes/types').JsxRenderingUsage[],
5149
+ ): void {
5150
+ // Add usages, avoiding duplicates based on path and renderingType
5151
+ for (const usage of usages) {
5152
+ const exists = this.rawJsxRenderingUsages.some(
5153
+ (existing) =>
5154
+ existing.path === usage.path &&
5155
+ existing.renderingType === usage.renderingType,
5156
+ );
5157
+ if (!exists) {
5158
+ this.rawJsxRenderingUsages.push(usage);
5159
+ }
5160
+ }
5161
+ }
5162
+
5163
+ /**
5164
+ * Get JSX rendering usages collected during analysis.
5165
+ */
5166
+ getJsxRenderingUsages(): import('../astScopes/types').JsxRenderingUsage[] {
5167
+ return this.rawJsxRenderingUsages;
5168
+ }
5169
+
3650
5170
  toSerializable(): SerializableDataStructure {
3651
- // Helper to convert ScopeVariable to SerializableScopeVariable
5171
+ // Helper to clean cyScope and cyDuplicateKey from a string for output
5172
+ const cleanCyScope = (str: string): string =>
5173
+ this.replaceCyScopeInString(str).replace(/::cyDuplicateKey\d+::/g, '');
5174
+
5175
+ // Helper to convert ScopeVariable to SerializableScopeVariable (with cyScope cleaned)
3652
5176
  const toSerializableVariable = (
3653
5177
  vars:
3654
5178
  | ScopeVariable[]
3655
5179
  | Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[],
3656
5180
  ): SerializableScopeVariable[] =>
3657
5181
  vars.map((v) => ({
3658
- scopeNodeName: v.scopeNodeName,
3659
- schemaPath: v.schemaPath,
5182
+ scopeNodeName: cleanCyScope(v.scopeNodeName),
5183
+ schemaPath: cleanCyScope(v.schemaPath),
3660
5184
  }));
3661
5185
 
5186
+ // Helper to clean cyScope from all keys in a schema
5187
+ const cleanSchemaKeys = (
5188
+ schema: Record<string, string>,
5189
+ ): Record<string, string> => {
5190
+ return Object.entries(schema).reduce(
5191
+ (acc, [key, value]) => {
5192
+ acc[cleanCyScope(key)] = value;
5193
+ return acc;
5194
+ },
5195
+ {} as Record<string, string>,
5196
+ );
5197
+ };
5198
+
3662
5199
  // Helper to get function result for a given function name
3663
5200
  const getFunctionResult = (
3664
5201
  functionName?: string,
3665
5202
  ): SerializableFunctionResult => {
3666
5203
  return {
3667
- signature: this.getFunctionSignature({ functionName }) ?? {},
3668
- signatureWithUnknowns:
5204
+ signature: cleanSchemaKeys(
5205
+ this.getFunctionSignature({ functionName }) ?? {},
5206
+ ),
5207
+ signatureWithUnknowns: cleanSchemaKeys(
3669
5208
  this.getFunctionSignature({ functionName, fillInUnknowns: true }) ??
3670
- {},
3671
- returnValue: this.getReturnValue({ functionName }) ?? {},
3672
- returnValueWithUnknowns:
5209
+ {},
5210
+ ),
5211
+ returnValue: cleanSchemaKeys(
5212
+ this.getReturnValue({ functionName }) ?? {},
5213
+ ),
5214
+ returnValueWithUnknowns: cleanSchemaKeys(
3673
5215
  this.getReturnValue({ functionName, fillInUnknowns: true }) ?? {},
5216
+ ),
3674
5217
  usageEquivalencies: Object.entries(
3675
5218
  this.getUsageEquivalencies(functionName) ?? {},
3676
5219
  ).reduce(
3677
5220
  (acc, [key, vars]) => {
3678
- acc[key] = toSerializableVariable(vars);
5221
+ // Clean cyScope from the key as well as variable properties
5222
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
3679
5223
  return acc;
3680
5224
  },
3681
5225
  {} as Record<string, SerializableScopeVariable[]>,
@@ -3684,7 +5228,8 @@ export class ScopeDataStructure {
3684
5228
  this.getSourceEquivalencies(functionName) ?? {},
3685
5229
  ).reduce(
3686
5230
  (acc, [key, vars]) => {
3687
- acc[key] = toSerializableVariable(vars);
5231
+ // Clean cyScope from the key as well as variable properties
5232
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
3688
5233
  return acc;
3689
5234
  },
3690
5235
  {} as Record<string, SerializableScopeVariable[]>,
@@ -3693,39 +5238,417 @@ export class ScopeDataStructure {
3693
5238
  };
3694
5239
  };
3695
5240
 
3696
- // Convert external function calls
5241
+ // Convert external function calls - use getExternalFunctionCalls() which cleans cyScope
5242
+ const cleanedExternalCalls = this.getExternalFunctionCalls();
5243
+
5244
+ // Get root scope schema for building per-variable return value schemas
5245
+ const rootScopeName = this.scopeTreeManager.getRootName();
5246
+ const rootScope = this.scopeNodes[rootScopeName];
5247
+ const rootSchema = rootScope?.schema ?? {};
5248
+
3697
5249
  const externalFunctionCalls: SerializableFunctionCallInfo[] =
3698
- this.externalFunctionCalls.map((efc) => ({
3699
- name: efc.name,
3700
- callSignature: efc.callSignature,
3701
- callScope: efc.callScope,
3702
- schema: efc.schema,
3703
- equivalencies: efc.equivalencies
3704
- ? Object.entries(efc.equivalencies).reduce(
3705
- (acc, [key, vars]) => {
3706
- acc[key] = toSerializableVariable(vars);
3707
- return acc;
3708
- },
3709
- {} as Record<string, SerializableScopeVariable[]>,
3710
- )
3711
- : undefined,
3712
- allCallSignatures: efc.allCallSignatures,
3713
- receivingVariableNames: efc.receivingVariableNames,
3714
- callSignatureToVariable: efc.callSignatureToVariable,
3715
- }));
5250
+ cleanedExternalCalls.map((efc) => {
5251
+ // Build perVariableSchemas from perCallSignatureSchemas when available.
5252
+ // This preserves distinct schemas per variable when the same function is called
5253
+ // multiple times with DIFFERENT call signatures (e.g., different type parameters).
5254
+ //
5255
+ // When field accesses happen in child scopes (like JSX expressions), the
5256
+ // rootSchema doesn't contain the detailed paths - they end up in child scope
5257
+ // schemas. Using perCallSignatureSchemas ensures we get the correct schema
5258
+ // for each call, regardless of where field accesses occur.
5259
+ let perVariableSchemas:
5260
+ | Record<string, Record<string, string>>
5261
+ | undefined;
5262
+
5263
+ // Use perCallSignatureSchemas only when:
5264
+ // 1. It exists and has distinct entries for different call signatures
5265
+ // 2. The number of distinct call signatures >= number of receiving variables
5266
+ //
5267
+ // This prevents using it when all calls have the same signature (e.g., useFetcher() x 2)
5268
+ // because in that case, perCallSignatureSchemas only has one entry.
5269
+ const numCallSignatures = efc.perCallSignatureSchemas
5270
+ ? Object.keys(efc.perCallSignatureSchemas).length
5271
+ : 0;
5272
+ const numReceivingVars = efc.receivingVariableNames?.length ?? 0;
5273
+ const hasDistinctSchemas =
5274
+ numCallSignatures >= numReceivingVars && numCallSignatures > 1;
5275
+
5276
+ // CASE 1: Multiple call signatures with distinct schemas - use indexed variable names
5277
+ if (
5278
+ hasDistinctSchemas &&
5279
+ efc.perCallSignatureSchemas &&
5280
+ efc.callSignatureToVariable
5281
+ ) {
5282
+ perVariableSchemas = {};
5283
+
5284
+ // Build a reverse map: variable -> array of call signatures (in order)
5285
+ // This handles the case where the same variable name is reused for different calls
5286
+ const varToCallSigs: Record<string, string[]> = {};
5287
+ for (const [callSig, varName] of Object.entries(
5288
+ efc.callSignatureToVariable,
5289
+ )) {
5290
+ if (!varToCallSigs[varName]) {
5291
+ varToCallSigs[varName] = [];
5292
+ }
5293
+ varToCallSigs[varName].push(callSig);
5294
+ }
5295
+
5296
+ // Track how many times each variable name has been seen
5297
+ const varNameCounts: Record<string, number> = {};
5298
+
5299
+ // For each receiving variable, get its original schema from perCallSignatureSchemas
5300
+ for (const varName of efc.receivingVariableNames ?? []) {
5301
+ const occurrence = varNameCounts[varName] ?? 0;
5302
+ varNameCounts[varName] = occurrence + 1;
5303
+
5304
+ const callSigs = varToCallSigs[varName];
5305
+ // Use the nth call signature for the nth occurrence of this variable
5306
+ const callSig = callSigs?.[occurrence];
5307
+
5308
+ if (callSig && efc.perCallSignatureSchemas[callSig]) {
5309
+ // Use indexed key if this variable name is reused (e.g., fetcher, fetcher[1])
5310
+ const key =
5311
+ occurrence === 0 ? varName : `${varName}[${occurrence}]`;
5312
+ // Clone the schema to avoid shared references
5313
+ perVariableSchemas[key] = {
5314
+ ...efc.perCallSignatureSchemas[callSig],
5315
+ };
5316
+ }
5317
+ }
5318
+
5319
+ // Only include if we have entries for ALL receiving variables
5320
+ if (Object.keys(perVariableSchemas).length < numReceivingVars) {
5321
+ // Not all variables have schemas - fall back to rootSchema extraction
5322
+ perVariableSchemas = undefined;
5323
+ } else {
5324
+ // Also check that at least one schema is non-empty
5325
+ // Bug fix: perCallSignatureSchemas may have entries but with empty schemas {}
5326
+ // In this case, we should fall through to Fallback which uses rootSchema
5327
+ const hasNonEmptySchema = Object.values(perVariableSchemas).some(
5328
+ (schema) => Object.keys(schema).length > 0,
5329
+ );
5330
+ if (!hasNonEmptySchema) {
5331
+ perVariableSchemas = undefined;
5332
+ }
5333
+ }
5334
+ }
5335
+
5336
+ // CASE 2: Single call signature with single variable - use perCallSignatureSchemas directly
5337
+ // This handles parameterized calls like useFetcher<ConfigData>() where each is a separate efc entry
5338
+ if (
5339
+ !perVariableSchemas &&
5340
+ efc.perCallSignatureSchemas &&
5341
+ numCallSignatures === 1 &&
5342
+ numReceivingVars === 1
5343
+ ) {
5344
+ const varName = efc.receivingVariableNames![0];
5345
+ const callSig = Object.keys(efc.perCallSignatureSchemas)[0];
5346
+ const schema = efc.perCallSignatureSchemas[callSig];
5347
+ if (schema && Object.keys(schema).length > 0) {
5348
+ perVariableSchemas = { [varName]: { ...schema } };
5349
+ }
5350
+ }
5351
+
5352
+ // CASE 3: Extract from efc.schema when perCallSignatureSchemas is missing or empty
5353
+ // This handles two scenarios:
5354
+ // 1. Parameterized calls that create SEPARATE efc entries (no perCallSignatureSchemas)
5355
+ // 2. Destructuring where perCallSignatureSchemas exists but has EMPTY schemas
5356
+ //
5357
+ // When useFetcher<ConfigData>() and useFetcher<SettingsData>() are called, they create separate
5358
+ // efc entries because getFunctionCallRoot preserves type parameters. Each entry has its own
5359
+ // `schema` field, but due to variable reassignment, the schema may be contaminated with paths
5360
+ // from other calls (the tracer attributes field accesses to ALL equivalencies).
5361
+ //
5362
+ // Solution: Filter efc.schema to only include paths that match THIS entry's call signature.
5363
+ // The schema paths include the full call signature prefix, so we can filter by it.
5364
+ //
5365
+ // Example: ConfigData entry has paths like:
5366
+ // "useFetcher<{ data: ConfigData | null }>().functionCallReturnValue.data.data.theme"
5367
+ // But also (contaminated):
5368
+ // "useFetcher<{ data: ConfigData | null }>().functionCallReturnValue.data.data.notifications"
5369
+ //
5370
+ // We filter to only keep paths that should belong to THIS call by checking if the
5371
+ // receiving variable's equivalency points to this call's return value.
5372
+ //
5373
+ // BUG FIX: The old condition `!efc.perCallSignatureSchemas` was FALSE when the object
5374
+ // existed (even with empty schemas), causing this case to be skipped. We now also check
5375
+ // if all schemas in perCallSignatureSchemas are empty.
5376
+ const hasNonEmptyPerCallSignatureSchemas =
5377
+ efc.perCallSignatureSchemas &&
5378
+ Object.values(efc.perCallSignatureSchemas).some(
5379
+ (schema) => Object.keys(schema).length > 0,
5380
+ );
5381
+
5382
+ // Build the call signature prefix that paths should start with
5383
+ const callSigPrefix = `${efc.callSignature}.functionCallReturnValue`;
5384
+
5385
+ // Check if efc.schema has variable-specific paths (indicating destructuring).
5386
+ // Destructuring: const { entities, gitStatus } = useLoaderData()
5387
+ // - efc.schema has paths like: useLoaderData().functionCallReturnValue.entities...
5388
+ // Multiple calls: const x = useFetcher(); const y = useFetcher();
5389
+ // - efc.schema has paths like: useFetcher().functionCallReturnValue.data...
5390
+ // CASE 3 should only run for destructuring (variable-specific paths exist).
5391
+ const hasVariableSpecificPaths = (
5392
+ efc.receivingVariableNames ?? []
5393
+ ).some((varName) =>
5394
+ Object.keys(efc.schema).some((path) =>
5395
+ path.startsWith(`${callSigPrefix}.${varName}`),
5396
+ ),
5397
+ );
5398
+
5399
+ if (
5400
+ !perVariableSchemas &&
5401
+ !hasNonEmptyPerCallSignatureSchemas &&
5402
+ numReceivingVars >= 1 &&
5403
+ hasVariableSpecificPaths
5404
+ ) {
5405
+ // Filter efc.schema to only include paths matching this call signature
5406
+ const filteredSchema: Record<string, string> = {};
5407
+ for (const [path, type] of Object.entries(efc.schema)) {
5408
+ if (path.startsWith(callSigPrefix) || path === efc.callSignature) {
5409
+ filteredSchema[path] = type;
5410
+ }
5411
+ }
5412
+
5413
+ // Build perVariableSchemas from the filtered schema
5414
+ // For destructuring, filter paths by variable name
5415
+ if (Object.keys(filteredSchema).length > 0) {
5416
+ perVariableSchemas = {};
5417
+ for (const varName of efc.receivingVariableNames ?? []) {
5418
+ // For destructuring, extract only paths specific to this variable
5419
+ const varSpecificPrefix = `${callSigPrefix}.${varName}`;
5420
+ const varSchema: Record<string, string> = {};
5421
+
5422
+ for (const [path, type] of Object.entries(filteredSchema)) {
5423
+ if (path.startsWith(varSpecificPrefix)) {
5424
+ // Transform: useLoaderData().functionCallReturnValue.entities.sha
5425
+ // -> functionCallReturnValue.entities.sha (keep the variable name)
5426
+ const suffix = path.slice(callSigPrefix.length);
5427
+ const returnValuePath = `functionCallReturnValue${suffix}`;
5428
+ varSchema[returnValuePath] = type;
5429
+ } else if (path === efc.callSignature) {
5430
+ // Include the function call type itself
5431
+ varSchema[path] = type;
5432
+ }
5433
+ }
5434
+ if (Object.keys(varSchema).length > 0) {
5435
+ perVariableSchemas[varName] = varSchema;
5436
+ }
5437
+ }
5438
+ // Only include if we have entries
5439
+ if (Object.keys(perVariableSchemas).length === 0) {
5440
+ perVariableSchemas = undefined;
5441
+ }
5442
+ }
5443
+ }
5444
+
5445
+ // Fallback: extract from root scope schema when perCallSignatureSchemas is not available
5446
+ // or doesn't have distinct entries for each variable.
5447
+ // This works when field accesses are in the root scope.
5448
+ if (
5449
+ !perVariableSchemas &&
5450
+ efc.receivingVariableNames &&
5451
+ efc.receivingVariableNames.length > 0
5452
+ ) {
5453
+ perVariableSchemas = {};
5454
+ for (const varName of efc.receivingVariableNames) {
5455
+ const varSchema: Record<string, string> = {};
5456
+ for (const [path, type] of Object.entries(rootSchema)) {
5457
+ // Check if path starts with this variable name
5458
+ if (
5459
+ path === varName ||
5460
+ path.startsWith(varName + '.') ||
5461
+ path.startsWith(varName + '[')
5462
+ ) {
5463
+ // Transform to functionCallReturnValue format
5464
+ // e.g., userFetcher.data.id -> functionCallReturnValue.data.id
5465
+ const suffix = path.slice(varName.length);
5466
+ const returnValuePath = `functionCallReturnValue${suffix}`;
5467
+ varSchema[returnValuePath] = type;
5468
+ }
5469
+ }
5470
+ if (Object.keys(varSchema).length > 0) {
5471
+ // Clean the variable name when using as key in output
5472
+ perVariableSchemas[cleanCyScope(varName)] = varSchema;
5473
+ }
5474
+ }
5475
+ // Only include if we have any entries
5476
+ if (Object.keys(perVariableSchemas).length === 0) {
5477
+ perVariableSchemas = undefined;
5478
+ }
5479
+ }
5480
+
5481
+ // Enrich the schema with inferred types by applying fillInSchemaGapsAndUnknowns.
5482
+ // This ensures the serialized schema has the same type inference as getReturnValue().
5483
+ // Without this, evidence like "entities[].analyses: array" becomes "unknown".
5484
+ const enrichedSchema = { ...efc.schema };
5485
+ const tempScopeNode = {
5486
+ name: efc.name,
5487
+ schema: enrichedSchema,
5488
+ equivalencies: efc.equivalencies ?? {},
5489
+ };
5490
+ fillInSchemaGapsAndUnknowns(tempScopeNode, true);
5491
+
5492
+ return {
5493
+ name: efc.name,
5494
+ callSignature: efc.callSignature,
5495
+ callScope: efc.callScope,
5496
+ schema: enrichedSchema,
5497
+ equivalencies: efc.equivalencies
5498
+ ? Object.entries(efc.equivalencies).reduce(
5499
+ (acc, [key, vars]) => {
5500
+ // Clean cyScope from the key as well as variable properties
5501
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
5502
+ return acc;
5503
+ },
5504
+ {} as Record<string, SerializableScopeVariable[]>,
5505
+ )
5506
+ : undefined,
5507
+ allCallSignatures: efc.allCallSignatures,
5508
+ receivingVariableNames: efc.receivingVariableNames?.map(cleanCyScope),
5509
+ callSignatureToVariable: efc.callSignatureToVariable
5510
+ ? Object.fromEntries(
5511
+ Object.entries(efc.callSignatureToVariable).map(([k, v]) => [
5512
+ k,
5513
+ cleanCyScope(v),
5514
+ ]),
5515
+ )
5516
+ : undefined,
5517
+ perVariableSchemas,
5518
+ };
5519
+ });
5520
+
5521
+ // POST-PROCESSING: Deduplicate schemas across parameterized calls to same base function
5522
+ // When useFetcher<ConfigData>() and useFetcher<SettingsData>() are called, they create
5523
+ // separate entries. Due to variable reassignment, BOTH entries may have ALL fields.
5524
+ // We deduplicate by assigning each field to ONLY ONE entry based on order of appearance.
5525
+ //
5526
+ // Strategy: Fields that appear first in order belong to the first entry,
5527
+ // fields that appear later belong to later entries (split evenly).
5528
+ const deduplicateParameterizedEntries = (
5529
+ entries: typeof externalFunctionCalls,
5530
+ ): typeof externalFunctionCalls => {
5531
+ // Group entries by base function name (without type parameters)
5532
+ const groups = new Map<string, typeof externalFunctionCalls>();
5533
+ for (const entry of entries) {
5534
+ // Extract base function name by stripping type parameters
5535
+ // e.g., "useFetcher<{ data: ConfigData | null }>" -> "useFetcher"
5536
+ const baseName = entry.name.replace(/<.*>$/, '');
5537
+ const group = groups.get(baseName) || [];
5538
+ group.push(entry);
5539
+ groups.set(baseName, group);
5540
+ }
5541
+
5542
+ // Process groups with multiple parameterized entries
5543
+ for (const [, group] of groups) {
5544
+ if (group.length <= 1) continue;
5545
+
5546
+ // Check if these are parameterized calls (have type parameters in name)
5547
+ const hasTypeParams = group.every((e) => e.name.includes('<'));
5548
+ if (!hasTypeParams) continue;
5549
+
5550
+ // Collect ALL unique field suffixes across all entries (in order of first appearance)
5551
+ // Field suffix is the path after functionCallReturnValue, e.g., ".data.data.theme"
5552
+ const allFieldSuffixes: string[] = [];
5553
+ for (const entry of group) {
5554
+ if (!entry.perVariableSchemas) continue;
5555
+ for (const varSchema of Object.values(entry.perVariableSchemas)) {
5556
+ for (const path of Object.keys(varSchema)) {
5557
+ // Skip the base "functionCallReturnValue" entry
5558
+ if (path === 'functionCallReturnValue') continue;
5559
+ // Extract field suffix
5560
+ const match = path.match(/functionCallReturnValue(.+)/);
5561
+ if (!match) continue;
5562
+ const fieldSuffix = match[1];
5563
+ if (!allFieldSuffixes.includes(fieldSuffix)) {
5564
+ allFieldSuffixes.push(fieldSuffix);
5565
+ }
5566
+ }
5567
+ }
5568
+ }
5569
+
5570
+ // Assign fields to entries: split evenly based on order
5571
+ // First N/2 fields go to first entry, remaining go to second entry
5572
+ const fieldToEntryMap = new Map<string, number>();
5573
+ const fieldsPerEntry = Math.ceil(
5574
+ allFieldSuffixes.length / group.length,
5575
+ );
5576
+ for (let i = 0; i < allFieldSuffixes.length; i++) {
5577
+ const fieldSuffix = allFieldSuffixes[i];
5578
+ const entryIdx = Math.min(
5579
+ Math.floor(i / fieldsPerEntry),
5580
+ group.length - 1,
5581
+ );
5582
+ fieldToEntryMap.set(fieldSuffix, entryIdx);
5583
+ }
5584
+
5585
+ // Filter each entry's perVariableSchemas to only include its assigned fields
5586
+ for (let i = 0; i < group.length; i++) {
5587
+ const entry = group[i];
5588
+ if (!entry.perVariableSchemas) continue;
5589
+
5590
+ const filteredPerVarSchemas: Record<
5591
+ string,
5592
+ Record<string, string>
5593
+ > = {};
5594
+ for (const [varName, varSchema] of Object.entries(
5595
+ entry.perVariableSchemas,
5596
+ )) {
5597
+ const filteredVarSchema: Record<string, string> = {};
5598
+ for (const [path, type] of Object.entries(varSchema)) {
5599
+ // Always keep the base functionCallReturnValue
5600
+ if (path === 'functionCallReturnValue') {
5601
+ filteredVarSchema[path] = type;
5602
+ continue;
5603
+ }
5604
+ // Extract field suffix
5605
+ const match = path.match(/functionCallReturnValue(.+)/);
5606
+ if (!match) {
5607
+ // Keep non-field paths
5608
+ filteredVarSchema[path] = type;
5609
+ continue;
5610
+ }
5611
+ const fieldSuffix = match[1];
5612
+ // Only include if this entry owns this field
5613
+ if (fieldToEntryMap.get(fieldSuffix) === i) {
5614
+ filteredVarSchema[path] = type;
5615
+ }
5616
+ }
5617
+ if (Object.keys(filteredVarSchema).length > 0) {
5618
+ filteredPerVarSchemas[varName] = filteredVarSchema;
5619
+ }
5620
+ }
5621
+ entry.perVariableSchemas =
5622
+ Object.keys(filteredPerVarSchemas).length > 0
5623
+ ? filteredPerVarSchemas
5624
+ : undefined;
5625
+ }
5626
+ }
5627
+
5628
+ return entries;
5629
+ };
5630
+
5631
+ // Apply deduplication
5632
+ const deduplicatedExternalFunctionCalls = deduplicateParameterizedEntries(
5633
+ externalFunctionCalls,
5634
+ );
5635
+
5636
+ // IMPORTANT: Get equivalent signature variables BEFORE calling getFunctionResult
5637
+ // because getFunctionResult calls validateSchema which may remove equivalencies
5638
+ // during the finalize step (e.g., cleanNonObjectFunctions removes method call
5639
+ // equivalencies like `segments -> splat.split('/').functionCallReturnValue`).
5640
+ // Fix 33: Move this call before any schema validation to preserve method call chains.
5641
+ const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
3716
5642
 
3717
5643
  // Get root function result
3718
5644
  const rootFunction = getFunctionResult();
3719
5645
 
3720
- // Get results for each external function
5646
+ // Get results for each external function (use cleaned calls for consistency)
3721
5647
  const functionResults: Record<string, SerializableFunctionResult> = {};
3722
- for (const efc of this.externalFunctionCalls) {
5648
+ for (const efc of cleanedExternalCalls) {
3723
5649
  functionResults[efc.name] = getFunctionResult(efc.name);
3724
5650
  }
3725
5651
 
3726
- // Get equivalent signature variables
3727
- const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
3728
-
3729
5652
  const environmentVariables = this.getEnvironmentVariables();
3730
5653
 
3731
5654
  // Get enriched conditional usages with source tracing
@@ -3735,13 +5658,43 @@ export class ScopeDataStructure {
3735
5658
  ? enrichedConditionalUsages
3736
5659
  : undefined;
3737
5660
 
5661
+ // Get conditional effects (setter calls inside conditionals)
5662
+ const conditionalEffects =
5663
+ this.rawConditionalEffects.length > 0
5664
+ ? this.rawConditionalEffects
5665
+ : undefined;
5666
+
5667
+ // Get compound conditionals (grouped conditions that must all be true)
5668
+ const compoundConditionals =
5669
+ this.rawCompoundConditionals.length > 0
5670
+ ? this.rawCompoundConditionals
5671
+ : undefined;
5672
+
5673
+ // Get child boundary gating conditions
5674
+ const enrichedGatingConditions =
5675
+ this.getEnrichedChildBoundaryGatingConditions();
5676
+ const childBoundaryGatingConditions =
5677
+ Object.keys(enrichedGatingConditions).length > 0
5678
+ ? enrichedGatingConditions
5679
+ : undefined;
5680
+
5681
+ // Get JSX rendering usages (arrays via .map(), strings via interpolation)
5682
+ const jsxRenderingUsages =
5683
+ this.rawJsxRenderingUsages.length > 0
5684
+ ? this.rawJsxRenderingUsages
5685
+ : undefined;
5686
+
3738
5687
  return {
3739
- externalFunctionCalls,
5688
+ externalFunctionCalls: deduplicatedExternalFunctionCalls,
3740
5689
  rootFunction,
3741
5690
  functionResults,
3742
5691
  equivalentSignatureVariables,
3743
5692
  environmentVariables,
3744
5693
  conditionalUsages,
5694
+ conditionalEffects,
5695
+ compoundConditionals,
5696
+ childBoundaryGatingConditions,
5697
+ jsxRenderingUsages,
3745
5698
  };
3746
5699
  }
3747
5700