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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1052) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/common/execAsync.ts +1 -1
  3. package/analyzer-template/log.txt +3 -3
  4. package/analyzer-template/package.json +30 -26
  5. package/analyzer-template/packages/ai/index.ts +21 -5
  6. package/analyzer-template/packages/ai/package.json +4 -4
  7. package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
  8. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +228 -24
  9. package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
  10. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +205 -10
  11. package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
  12. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +181 -23
  13. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.ts +10 -17
  14. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.ts +18 -0
  15. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +38 -1
  16. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +181 -1
  17. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +1619 -125
  18. package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
  19. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +324 -5
  20. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
  21. package/analyzer-template/packages/ai/src/lib/completionCall.ts +216 -36
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +2761 -390
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +21 -4
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +976 -0
  25. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +243 -77
  26. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
  27. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
  28. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +71 -2
  29. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +161 -19
  30. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
  31. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +163 -14
  32. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  33. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
  34. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
  35. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +441 -82
  36. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
  37. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  38. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +183 -0
  39. package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
  40. package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
  41. package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
  42. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +74 -7
  43. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +89 -112
  44. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +63 -2
  45. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1419 -101
  46. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +216 -109
  47. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +710 -0
  48. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
  49. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +2484 -0
  50. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
  51. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
  52. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
  53. package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +328 -7
  54. package/analyzer-template/packages/ai/src/lib/mergeJsonTypeDefinitions.ts +5 -0
  55. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +111 -87
  56. package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
  57. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +17 -7
  58. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +1 -1
  59. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -102
  60. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
  61. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
  62. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +110 -6
  63. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +14 -53
  64. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.ts +58 -0
  65. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
  66. package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
  67. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +824 -0
  68. package/analyzer-template/packages/ai/src/lib/splitOutsideParentheses.ts +5 -1
  69. package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
  70. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +127 -3
  71. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +121 -2
  72. package/analyzer-template/packages/analyze/index.ts +2 -0
  73. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +79 -59
  74. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
  75. package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
  76. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  77. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
  78. package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
  79. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
  80. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
  81. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
  82. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
  83. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
  84. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
  85. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +570 -180
  86. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +54 -1
  87. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +6 -0
  88. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
  89. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
  90. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
  91. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +31 -15
  92. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +11 -7
  93. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +11 -12
  94. package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
  95. package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
  96. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +22 -13
  97. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1315 -0
  98. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +313 -0
  99. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
  100. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +711 -78
  101. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
  102. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +28 -62
  103. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +550 -137
  104. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +264 -0
  105. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +78 -83
  106. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +4 -8
  107. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +1067 -167
  108. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
  109. package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
  110. package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
  111. package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
  112. package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
  113. package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
  114. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
  115. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
  116. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
  117. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
  118. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
  119. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
  120. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
  121. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  122. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
  123. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
  124. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
  125. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  126. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
  127. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
  128. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
  129. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
  130. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
  131. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
  132. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
  133. package/analyzer-template/packages/aws/package.json +10 -10
  134. package/analyzer-template/packages/aws/s3/index.ts +1 -0
  135. package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
  136. package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
  137. package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
  138. package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
  139. package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
  140. package/analyzer-template/packages/database/package.json +1 -1
  141. package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +1 -1
  142. package/analyzer-template/packages/database/src/lib/analysisToDb.ts +1 -1
  143. package/analyzer-template/packages/database/src/lib/branchToDb.ts +1 -1
  144. package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +1 -1
  145. package/analyzer-template/packages/database/src/lib/commitToDb.ts +1 -1
  146. package/analyzer-template/packages/database/src/lib/fileToDb.ts +1 -1
  147. package/analyzer-template/packages/database/src/lib/kysely/db.ts +18 -5
  148. package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
  149. package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
  150. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +36 -9
  151. package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
  152. package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
  153. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
  154. package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
  155. package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
  156. package/analyzer-template/packages/database/src/lib/loadCommits.ts +28 -0
  157. package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
  158. package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
  159. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +30 -5
  160. package/analyzer-template/packages/database/src/lib/projectToDb.ts +1 -1
  161. package/analyzer-template/packages/database/src/lib/saveFiles.ts +1 -1
  162. package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +1 -1
  163. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +7 -14
  164. package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +1 -1
  165. package/analyzer-template/packages/generate/index.ts +3 -0
  166. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
  167. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
  168. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
  169. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
  170. package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
  171. package/analyzer-template/packages/generate/src/lib/directExecutionScript.ts +17 -2
  172. package/analyzer-template/packages/generate/src/lib/getComponentScenarioPath.ts +8 -3
  173. package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
  174. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +1 -1
  175. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -1
  176. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +1 -1
  177. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -1
  178. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +1 -1
  179. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -1
  180. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +1 -1
  181. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -1
  182. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +1 -1
  183. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -1
  184. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +1 -1
  185. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -1
  186. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +4 -2
  187. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  188. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +13 -3
  189. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  190. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
  191. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +1 -11
  192. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  193. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +1 -0
  194. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
  195. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
  196. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  197. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +30 -7
  198. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  199. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  200. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  201. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
  202. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
  203. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
  204. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
  205. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  206. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  207. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +2 -6
  208. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  209. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +2 -0
  210. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
  211. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
  212. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
  213. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  214. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
  215. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  216. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
  217. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
  218. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
  219. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
  220. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
  221. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
  222. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  223. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +22 -1
  224. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  225. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
  226. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  227. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
  228. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  229. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
  230. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
  231. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -1
  232. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  233. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
  234. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  235. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +1 -1
  236. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -1
  237. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +1 -1
  238. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -1
  239. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +1 -1
  240. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -1
  241. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +2 -2
  242. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  243. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +5 -4
  244. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  245. package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
  246. package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
  247. package/analyzer-template/packages/github/dist/generate/index.js +3 -0
  248. package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
  249. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  250. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  251. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  252. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
  253. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
  254. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  255. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  256. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
  257. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
  258. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  259. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  260. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  261. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  262. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  263. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
  264. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
  265. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
  266. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.d.ts.map +1 -1
  267. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js +10 -1
  268. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js.map +1 -1
  269. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.d.ts.map +1 -1
  270. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js +7 -3
  271. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  272. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
  273. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
  274. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
  275. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  276. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
  277. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
  278. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
  279. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
  280. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
  281. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
  282. package/analyzer-template/packages/github/dist/types/index.d.ts +2 -2
  283. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  284. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  285. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +87 -13
  286. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  287. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts +2 -0
  288. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts.map +1 -1
  289. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
  290. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
  291. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  292. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  293. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +11 -6
  294. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  295. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
  296. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  297. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  298. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  299. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts +2 -0
  300. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  301. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  302. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  303. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  304. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  305. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  306. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  307. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
  308. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  309. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
  310. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
  311. package/analyzer-template/packages/github/package.json +1 -1
  312. package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
  313. package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
  314. package/analyzer-template/packages/process/index.ts +2 -0
  315. package/analyzer-template/packages/process/package.json +12 -0
  316. package/analyzer-template/packages/process/tsconfig.json +8 -0
  317. package/analyzer-template/packages/types/index.ts +5 -0
  318. package/analyzer-template/packages/types/src/types/Analysis.ts +104 -13
  319. package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
  320. package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
  321. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +7 -0
  322. package/analyzer-template/packages/types/src/types/Scenario.ts +11 -10
  323. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +228 -3
  324. package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
  325. package/analyzer-template/packages/types/src/types/StatementInfo.ts +2 -0
  326. package/analyzer-template/packages/ui-components/package.json +4 -4
  327. package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
  328. package/analyzer-template/packages/utils/dist/types/index.d.ts +2 -2
  329. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  330. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  331. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +87 -13
  332. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  333. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts +2 -0
  334. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts.map +1 -1
  335. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
  336. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
  337. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  338. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  339. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +11 -6
  340. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  341. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
  342. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  343. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  344. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  345. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts +2 -0
  346. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  347. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  348. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  349. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  350. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  351. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +98 -3
  352. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  353. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  354. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  355. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  356. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
  357. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  358. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
  359. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
  360. package/analyzer-template/packages/utils/src/lib/applyUniversalMocks.ts +28 -2
  361. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +121 -3
  362. package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
  363. package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
  364. package/analyzer-template/playwright/capture.ts +57 -26
  365. package/analyzer-template/playwright/captureStatic.ts +1 -1
  366. package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
  367. package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
  368. package/analyzer-template/playwright/takeScreenshot.ts +15 -9
  369. package/analyzer-template/playwright/waitForServer.ts +21 -6
  370. package/analyzer-template/project/TESTING.md +83 -0
  371. package/analyzer-template/project/analyzeBaselineCommit.ts +9 -0
  372. package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
  373. package/analyzer-template/project/analyzeFileEntities.ts +4 -0
  374. package/analyzer-template/project/analyzeRegularCommit.ts +9 -0
  375. package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
  376. package/analyzer-template/project/constructMockCode.ts +1347 -159
  377. package/analyzer-template/project/controller/startController.ts +16 -1
  378. package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
  379. package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
  380. package/analyzer-template/project/loadReadyToBeCaptured.ts +82 -42
  381. package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
  382. package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
  383. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +13 -9
  384. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +93 -42
  385. package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
  386. package/analyzer-template/project/orchestrateCapture.ts +92 -13
  387. package/analyzer-template/project/reconcileMockDataKeys.ts +245 -2
  388. package/analyzer-template/project/runAnalysis.ts +11 -0
  389. package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
  390. package/analyzer-template/project/serverOnlyModules.ts +413 -0
  391. package/analyzer-template/project/start.ts +72 -19
  392. package/analyzer-template/project/startScenarioCapture.ts +79 -41
  393. package/analyzer-template/project/writeMockDataTsx.ts +466 -73
  394. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  395. package/analyzer-template/project/writeScenarioComponents.ts +1509 -226
  396. package/analyzer-template/project/writeScenarioFiles.ts +26 -0
  397. package/analyzer-template/project/writeSimpleRoot.ts +56 -22
  398. package/analyzer-template/project/writeUniversalMocks.ts +32 -11
  399. package/analyzer-template/scripts/comboWorkerLoop.cjs +99 -50
  400. package/analyzer-template/scripts/defaultCmd.sh +9 -0
  401. package/analyzer-template/tsconfig.json +2 -1
  402. package/background/src/lib/local/createLocalAnalyzer.js +2 -30
  403. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  404. package/background/src/lib/local/execAsync.js +1 -1
  405. package/background/src/lib/local/execAsync.js.map +1 -1
  406. package/background/src/lib/virtualized/common/execAsync.js +1 -1
  407. package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
  408. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +7 -1
  409. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
  410. package/background/src/lib/virtualized/project/analyzeBranchCommit.js +2 -1
  411. package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
  412. package/background/src/lib/virtualized/project/analyzeFileEntities.js +2 -1
  413. package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
  414. package/background/src/lib/virtualized/project/analyzeRegularCommit.js +7 -1
  415. package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
  416. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
  417. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
  418. package/background/src/lib/virtualized/project/constructMockCode.js +1194 -120
  419. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  420. package/background/src/lib/virtualized/project/controller/startController.js +11 -1
  421. package/background/src/lib/virtualized/project/controller/startController.js.map +1 -1
  422. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js +73 -1
  423. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js.map +1 -1
  424. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js +6 -3
  425. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js.map +1 -1
  426. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +34 -9
  427. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  428. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js +7 -7
  429. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js.map +1 -1
  430. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js +2 -2
  431. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js.map +1 -1
  432. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +12 -6
  433. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  434. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +73 -36
  435. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  436. package/background/src/lib/virtualized/project/orchestrateCapture.js +76 -14
  437. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  438. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +204 -2
  439. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  440. package/background/src/lib/virtualized/project/runAnalysis.js +9 -0
  441. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  442. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
  443. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  444. package/background/src/lib/virtualized/project/serverOnlyModules.js +338 -0
  445. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -0
  446. package/background/src/lib/virtualized/project/start.js +62 -19
  447. package/background/src/lib/virtualized/project/start.js.map +1 -1
  448. package/background/src/lib/virtualized/project/startScenarioCapture.js +61 -31
  449. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  450. package/background/src/lib/virtualized/project/writeMockDataTsx.js +404 -62
  451. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  452. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
  453. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
  454. package/background/src/lib/virtualized/project/writeScenarioComponents.js +1112 -153
  455. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  456. package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
  457. package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
  458. package/background/src/lib/virtualized/project/writeSimpleRoot.js +57 -20
  459. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  460. package/background/src/lib/virtualized/project/writeUniversalMocks.js +27 -12
  461. package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
  462. package/codeyam-cli/scripts/apply-setup.js +180 -0
  463. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  464. package/codeyam-cli/src/cli.js +38 -17
  465. package/codeyam-cli/src/cli.js.map +1 -1
  466. package/codeyam-cli/src/codeyam-cli.js +18 -2
  467. package/codeyam-cli/src/codeyam-cli.js.map +1 -1
  468. package/codeyam-cli/src/commands/analyze.js +5 -3
  469. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  470. package/codeyam-cli/src/commands/baseline.js +176 -0
  471. package/codeyam-cli/src/commands/baseline.js.map +1 -0
  472. package/codeyam-cli/src/commands/debug.js +44 -18
  473. package/codeyam-cli/src/commands/debug.js.map +1 -1
  474. package/codeyam-cli/src/commands/default.js +30 -34
  475. package/codeyam-cli/src/commands/default.js.map +1 -1
  476. package/codeyam-cli/src/commands/detect-universal-mocks.js +2 -0
  477. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +1 -1
  478. package/codeyam-cli/src/commands/init.js +49 -257
  479. package/codeyam-cli/src/commands/init.js.map +1 -1
  480. package/codeyam-cli/src/commands/memory.js +254 -0
  481. package/codeyam-cli/src/commands/memory.js.map +1 -0
  482. package/codeyam-cli/src/commands/recapture.js +228 -0
  483. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  484. package/codeyam-cli/src/commands/report.js +72 -24
  485. package/codeyam-cli/src/commands/report.js.map +1 -1
  486. package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
  487. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
  488. package/codeyam-cli/src/commands/setup-simulations.js +284 -0
  489. package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
  490. package/codeyam-cli/src/commands/start.js +8 -12
  491. package/codeyam-cli/src/commands/start.js.map +1 -1
  492. package/codeyam-cli/src/commands/status.js +23 -1
  493. package/codeyam-cli/src/commands/status.js.map +1 -1
  494. package/codeyam-cli/src/commands/test-startup.js +3 -1
  495. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  496. package/codeyam-cli/src/commands/verify.js +14 -2
  497. package/codeyam-cli/src/commands/verify.js.map +1 -1
  498. package/codeyam-cli/src/commands/wipe.js +108 -0
  499. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  500. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +185 -0
  501. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  502. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
  503. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
  504. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +128 -82
  505. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  506. package/codeyam-cli/src/utils/analysisRunner.js +29 -15
  507. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  508. package/codeyam-cli/src/utils/analyzer.js +7 -0
  509. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  510. package/codeyam-cli/src/utils/backgroundServer.js +104 -23
  511. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  512. package/codeyam-cli/src/utils/database.js +91 -5
  513. package/codeyam-cli/src/utils/database.js.map +1 -1
  514. package/codeyam-cli/src/utils/generateReport.js +253 -106
  515. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  516. package/codeyam-cli/src/utils/git.js +79 -0
  517. package/codeyam-cli/src/utils/git.js.map +1 -0
  518. package/codeyam-cli/src/utils/install-skills.js +76 -42
  519. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  520. package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
  521. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
  522. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  523. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  524. package/codeyam-cli/src/utils/progress.js +7 -0
  525. package/codeyam-cli/src/utils/progress.js.map +1 -1
  526. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  527. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  528. package/codeyam-cli/src/utils/queue/job.js +249 -16
  529. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  530. package/codeyam-cli/src/utils/queue/manager.js +103 -7
  531. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  532. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  533. package/codeyam-cli/src/utils/requireSimulations.js +10 -0
  534. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
  535. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
  536. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
  537. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +230 -0
  538. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
  539. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
  540. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
  541. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
  542. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
  543. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
  544. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
  545. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
  546. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
  547. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +74 -0
  548. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
  549. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +376 -0
  550. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
  551. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +116 -0
  552. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
  553. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
  554. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
  555. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
  556. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
  557. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +116 -0
  558. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
  559. package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
  560. package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
  561. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +44 -0
  562. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
  563. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
  564. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
  565. package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
  566. package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
  567. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +84 -0
  568. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
  569. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
  570. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
  571. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js +83 -0
  572. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
  573. package/codeyam-cli/src/utils/rules/index.js +7 -0
  574. package/codeyam-cli/src/utils/rules/index.js.map +1 -0
  575. package/codeyam-cli/src/utils/rules/parser.js +83 -0
  576. package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
  577. package/codeyam-cli/src/utils/rules/pathMatcher.js +28 -0
  578. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
  579. package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
  580. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
  581. package/codeyam-cli/src/utils/rules/sourceFiles.js +47 -0
  582. package/codeyam-cli/src/utils/rules/sourceFiles.js.map +1 -0
  583. package/codeyam-cli/src/utils/rules/staleness.js +137 -0
  584. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
  585. package/codeyam-cli/src/utils/serverState.js +37 -10
  586. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  587. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +21 -42
  588. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  589. package/codeyam-cli/src/utils/simulationGateMiddleware.js +138 -0
  590. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  591. package/codeyam-cli/src/utils/syncMocksMiddleware.js +5 -24
  592. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  593. package/codeyam-cli/src/utils/versionInfo.js +67 -15
  594. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  595. package/codeyam-cli/src/utils/wipe.js +128 -0
  596. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  597. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  598. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  599. package/codeyam-cli/src/webserver/app/lib/database.js +118 -6
  600. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  601. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  602. package/codeyam-cli/src/webserver/backgroundServer.js +55 -10
  603. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  604. package/codeyam-cli/src/webserver/bootstrap.js +60 -0
  605. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  606. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-jNYXRRNI.js +1 -0
  607. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-bwuHPyTa.js +11 -0
  608. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-kykTbcnD.js → EntityTypeBadge-CvzqMxcu.js} +1 -1
  609. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BH0XDim7.js +41 -0
  610. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-EhOseatT.js +34 -0
  611. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-yjIHlOGa.js +25 -0
  612. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-Cq5o8jL4.js +3 -0
  613. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-BvMu2i-g.js +6 -0
  614. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-kgBTLoJD.js +3 -0
  615. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BzPgx-xO.js +11 -0
  616. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-CwZrv-Ok.js +1 -0
  617. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BX2Ny2Qj.js +10 -0
  618. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-C06nsHKY.js → TruncatedFilePath-CDpEprKa.js} +1 -1
  619. package/codeyam-cli/src/webserver/build/client/assets/_index-BRx8ZGZo.js +11 -0
  620. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-4S4yPfFw.js +27 -0
  621. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DHKuQSmR.js +17 -0
  622. package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
  623. package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
  624. package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-l0sNRNKZ.js +1 -0
  625. package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
  626. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  627. package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
  628. package/codeyam-cli/src/webserver/build/client/assets/book-open-D4IPYH_y.js +6 -0
  629. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-CG65viiV.js +6 -0
  630. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-DB3aFuEO.js +51 -0
  631. package/codeyam-cli/src/webserver/build/client/assets/circle-check-igfMr5DY.js +6 -0
  632. package/codeyam-cli/src/webserver/build/client/assets/copy-Coc4o_8c.js +11 -0
  633. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-D1zB-pYc.js +21 -0
  634. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
  635. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
  636. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-JTAjQ54M.js +1 -0
  637. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CYqBrC9s.js → entity._sha._-B0h9AqE6.js} +22 -15
  638. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DjLxr2JB.js +6 -0
  639. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-CtYowLOt.js +6 -0
  640. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-PePWg17F.js +5 -0
  641. package/codeyam-cli/src/webserver/build/client/assets/entry.client-I-Wo99C_.js +29 -0
  642. package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
  643. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-9sMMAiWJ.js +1 -0
  644. package/codeyam-cli/src/webserver/build/client/assets/files-Co65J0s3.js +1 -0
  645. package/codeyam-cli/src/webserver/build/client/assets/git-BdHOxVfg.js +15 -0
  646. package/codeyam-cli/src/webserver/build/client/assets/globals-Dzl-jeq-.css +1 -0
  647. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  648. package/codeyam-cli/src/webserver/build/client/assets/index-CUM5iXwc.js +9 -0
  649. package/codeyam-cli/src/webserver/build/client/assets/index-_417gcQW.js +3 -0
  650. package/codeyam-cli/src/webserver/build/client/assets/labs-DAvt-sy-.js +1 -0
  651. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-TzRHMVog.js +6 -0
  652. package/codeyam-cli/src/webserver/build/client/assets/manifest-2d0e2ebb.js +1 -0
  653. package/codeyam-cli/src/webserver/build/client/assets/memory-DVGtTawo.js +92 -0
  654. package/codeyam-cli/src/webserver/build/client/assets/pause-hjzB7t2z.js +11 -0
  655. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  656. package/codeyam-cli/src/webserver/build/client/assets/root-Bg3WICdl.js +62 -0
  657. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  658. package/codeyam-cli/src/webserver/build/client/assets/search-DcAwD_Ln.js +6 -0
  659. package/codeyam-cli/src/webserver/build/client/assets/settings-CclxrcPK.js +1 -0
  660. package/codeyam-cli/src/webserver/build/client/assets/simulations-DVNJVQgD.js +1 -0
  661. package/codeyam-cli/src/webserver/build/client/assets/terminal-DbEAHMbA.js +11 -0
  662. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-CAD5b1o_.js +6 -0
  663. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BqgrAzs3.js +1 -0
  664. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-Blr5oZDE.js → useLastLogLine-DAFqfEDH.js} +1 -1
  665. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DZlYx2c4.js +1 -0
  666. package/codeyam-cli/src/webserver/build/client/assets/{useToast-Bbf4Hokd.js → useToast-ihdMtlf6.js} +1 -1
  667. package/codeyam-cli/src/webserver/build/server/assets/index-CpreP2n8.js +1 -0
  668. package/codeyam-cli/src/webserver/build/server/assets/server-build-DyvoFrHR.js +273 -0
  669. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  670. package/codeyam-cli/src/webserver/build-info.json +5 -5
  671. package/codeyam-cli/src/webserver/devServer.js +1 -3
  672. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  673. package/codeyam-cli/src/webserver/server.js +35 -25
  674. package/codeyam-cli/src/webserver/server.js.map +1 -1
  675. package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam-debug.md} +48 -4
  676. package/codeyam-cli/templates/codeyam-diagnose.md +481 -0
  677. package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
  678. package/codeyam-cli/templates/codeyam-memory.md +396 -0
  679. package/codeyam-cli/templates/codeyam-new-rule.md +13 -0
  680. package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam-setup.md} +151 -4
  681. package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam-sim.md} +1 -1
  682. package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam-test.md} +1 -1
  683. package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam-verify.md} +1 -1
  684. package/codeyam-cli/templates/rule-notification-hook.py +56 -0
  685. package/codeyam-cli/templates/rule-reflection-hook.py +627 -0
  686. package/codeyam-cli/templates/rules-instructions.md +132 -0
  687. package/package.json +26 -23
  688. package/packages/ai/index.js +8 -6
  689. package/packages/ai/index.js.map +1 -1
  690. package/packages/ai/src/lib/analyzeScope.js +181 -13
  691. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  692. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  693. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  694. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +154 -9
  695. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  696. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
  697. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
  698. package/packages/ai/src/lib/astScopes/methodSemantics.js +138 -23
  699. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  700. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
  701. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
  702. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
  703. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
  704. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +23 -0
  705. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  706. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
  707. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  708. package/packages/ai/src/lib/astScopes/processExpression.js +1235 -104
  709. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  710. package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
  711. package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
  712. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  713. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  714. package/packages/ai/src/lib/completionCall.js +178 -31
  715. package/packages/ai/src/lib/completionCall.js.map +1 -1
  716. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +2171 -224
  717. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  718. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +19 -4
  719. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  720. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +661 -0
  721. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  722. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +180 -56
  723. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  724. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  725. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  726. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  727. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  728. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +66 -2
  729. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  730. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +139 -13
  731. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  732. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
  733. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
  734. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +142 -12
  735. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  736. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  737. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  738. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
  739. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  740. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  741. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  742. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +371 -73
  743. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  744. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  745. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  746. package/packages/ai/src/lib/dataStructureChunking.js +130 -0
  747. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  748. package/packages/ai/src/lib/deepEqual.js +32 -0
  749. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  750. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  751. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  752. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  753. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  754. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
  755. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  756. package/packages/ai/src/lib/generateChangesEntityScenarios.js +81 -90
  757. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  758. package/packages/ai/src/lib/generateEntityDataStructure.js +50 -1
  759. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  760. package/packages/ai/src/lib/generateEntityScenarioData.js +1127 -91
  761. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  762. package/packages/ai/src/lib/generateEntityScenarios.js +193 -83
  763. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  764. package/packages/ai/src/lib/generateExecutionFlows.js +495 -0
  765. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
  766. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
  767. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
  768. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1807 -0
  769. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
  770. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  771. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  772. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  773. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  774. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  775. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  776. package/packages/ai/src/lib/isolateScopes.js +270 -7
  777. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  778. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
  779. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
  780. package/packages/ai/src/lib/mergeStatements.js +88 -46
  781. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  782. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
  783. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
  784. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +16 -4
  785. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  786. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
  787. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  788. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -64
  789. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  790. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  791. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  792. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +83 -6
  793. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  794. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -34
  795. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  796. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
  797. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
  798. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  799. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  800. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  801. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  802. package/packages/ai/src/lib/resolvePathToControllable.js +677 -0
  803. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
  804. package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
  805. package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
  806. package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
  807. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  808. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +98 -1
  809. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  810. package/packages/analyze/index.js +1 -0
  811. package/packages/analyze/index.js.map +1 -1
  812. package/packages/analyze/src/lib/FileAnalyzer.js +75 -36
  813. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  814. package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
  815. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  816. package/packages/analyze/src/lib/analysisContext.js +30 -5
  817. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  818. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  819. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  820. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  821. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  822. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  823. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  824. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  825. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  826. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  827. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  828. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  829. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  830. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  831. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  832. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  833. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  834. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  835. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  836. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +428 -123
  837. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  838. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +42 -1
  839. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  840. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
  841. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  842. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  843. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  844. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  845. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  846. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
  847. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  848. package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
  849. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  850. package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
  851. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  852. package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
  853. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  854. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  855. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  856. package/packages/analyze/src/lib/files/enums/steps.js +1 -1
  857. package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
  858. package/packages/analyze/src/lib/files/getImportedExports.js +17 -8
  859. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  860. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
  861. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
  862. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +255 -0
  863. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  864. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  865. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  866. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +550 -62
  867. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  868. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  869. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  870. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
  871. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  872. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +404 -85
  873. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  874. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +144 -0
  875. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
  876. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +56 -69
  877. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  878. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +4 -8
  879. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  880. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +875 -141
  881. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  882. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  883. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  884. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  885. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  886. package/packages/analyze/src/lib/index.js +1 -0
  887. package/packages/analyze/src/lib/index.js.map +1 -1
  888. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  889. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  890. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  891. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  892. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  893. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  894. package/packages/database/src/lib/analysisBranchToDb.js +1 -1
  895. package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
  896. package/packages/database/src/lib/analysisToDb.js +1 -1
  897. package/packages/database/src/lib/analysisToDb.js.map +1 -1
  898. package/packages/database/src/lib/branchToDb.js +1 -1
  899. package/packages/database/src/lib/branchToDb.js.map +1 -1
  900. package/packages/database/src/lib/commitBranchToDb.js +1 -1
  901. package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
  902. package/packages/database/src/lib/commitToDb.js +1 -1
  903. package/packages/database/src/lib/commitToDb.js.map +1 -1
  904. package/packages/database/src/lib/fileToDb.js +1 -1
  905. package/packages/database/src/lib/fileToDb.js.map +1 -1
  906. package/packages/database/src/lib/kysely/db.js +13 -3
  907. package/packages/database/src/lib/kysely/db.js.map +1 -1
  908. package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
  909. package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  910. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  911. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  912. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  913. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  914. package/packages/database/src/lib/loadAnalyses.js +45 -2
  915. package/packages/database/src/lib/loadAnalyses.js.map +1 -1
  916. package/packages/database/src/lib/loadAnalysis.js +8 -0
  917. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  918. package/packages/database/src/lib/loadBranch.js +11 -1
  919. package/packages/database/src/lib/loadBranch.js.map +1 -1
  920. package/packages/database/src/lib/loadCommit.js +7 -0
  921. package/packages/database/src/lib/loadCommit.js.map +1 -1
  922. package/packages/database/src/lib/loadCommits.js +22 -1
  923. package/packages/database/src/lib/loadCommits.js.map +1 -1
  924. package/packages/database/src/lib/loadEntities.js +23 -4
  925. package/packages/database/src/lib/loadEntities.js.map +1 -1
  926. package/packages/database/src/lib/loadEntityBranches.js +9 -0
  927. package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
  928. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
  929. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  930. package/packages/database/src/lib/projectToDb.js +1 -1
  931. package/packages/database/src/lib/projectToDb.js.map +1 -1
  932. package/packages/database/src/lib/saveFiles.js +1 -1
  933. package/packages/database/src/lib/saveFiles.js.map +1 -1
  934. package/packages/database/src/lib/scenarioToDb.js +1 -1
  935. package/packages/database/src/lib/scenarioToDb.js.map +1 -1
  936. package/packages/database/src/lib/updateCommitMetadata.js +5 -4
  937. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  938. package/packages/generate/index.js +3 -0
  939. package/packages/generate/index.js.map +1 -1
  940. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  941. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  942. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  943. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  944. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  945. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  946. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  947. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  948. package/packages/generate/src/lib/deepMerge.js +27 -1
  949. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  950. package/packages/generate/src/lib/directExecutionScript.js +10 -1
  951. package/packages/generate/src/lib/directExecutionScript.js.map +1 -1
  952. package/packages/generate/src/lib/getComponentScenarioPath.js +7 -3
  953. package/packages/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  954. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  955. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  956. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  957. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  958. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  959. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  960. package/packages/process/index.js +3 -0
  961. package/packages/process/index.js.map +1 -0
  962. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  963. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  964. package/packages/process/src/ProcessManager.js.map +1 -0
  965. package/packages/process/src/index.js.map +1 -0
  966. package/packages/process/src/managedExecAsync.js.map +1 -0
  967. package/packages/types/index.js.map +1 -1
  968. package/packages/utils/src/lib/applyUniversalMocks.js +26 -2
  969. package/packages/utils/src/lib/applyUniversalMocks.js.map +1 -1
  970. package/packages/utils/src/lib/fs/rsyncCopy.js +98 -3
  971. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  972. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  973. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  974. package/packages/utils/src/lib/safeFileName.js +29 -3
  975. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  976. package/scripts/finalize-analyzer.cjs +8 -74
  977. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
  978. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -197
  979. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -271
  980. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -294
  981. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
  982. package/analyzer-template/packages/ai/src/lib/transformMockDataToMatchSchema.ts +0 -156
  983. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -115
  984. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  985. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  986. package/analyzer-template/process/README.md +0 -507
  987. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  988. package/background/src/lib/process/ProcessManager.js.map +0 -1
  989. package/background/src/lib/process/index.js.map +0 -1
  990. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  991. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  992. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  993. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-D4htqD-x.js +0 -1
  994. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-Catz6XEN.js +0 -1
  995. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-TlHocYno.js +0 -26
  996. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CVMmGuIc.js +0 -3
  997. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-JkfQ-VaI.js +0 -3
  998. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-CVZ0H4BL.js +0 -1
  999. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BrMAP1nP.js +0 -1
  1000. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CJhE4cCv.js +0 -5
  1001. package/codeyam-cli/src/webserver/build/client/assets/_index-faVIcr_i.js +0 -1
  1002. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CLMa2sgx.js +0 -7
  1003. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-DwYjrK_h.js +0 -1
  1004. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CgXbbZRx.js +0 -26
  1005. package/codeyam-cli/src/webserver/build/client/assets/circle-check-B2oHQ-zo.js +0 -1
  1006. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BBYuR56H.js +0 -1
  1007. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CT0Q5lVu.js +0 -1
  1008. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-Bj5GHkhb.js +0 -1
  1009. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-eW5z9AyZ.js +0 -5
  1010. package/codeyam-cli/src/webserver/build/client/assets/entry.client-B9tSboXM.js +0 -5
  1011. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-CmO-EZAB.js +0 -1
  1012. package/codeyam-cli/src/webserver/build/client/assets/files-DLinnTOx.js +0 -1
  1013. package/codeyam-cli/src/webserver/build/client/assets/git-CIxwBQvb.js +0 -12
  1014. package/codeyam-cli/src/webserver/build/client/assets/globals-xPz593l2.css +0 -1
  1015. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  1016. package/codeyam-cli/src/webserver/build/client/assets/index-_LjBsTxX.js +0 -8
  1017. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-D_EGChhq.js +0 -1
  1018. package/codeyam-cli/src/webserver/build/client/assets/manifest-ca438c41.js +0 -1
  1019. package/codeyam-cli/src/webserver/build/client/assets/root-CHHYHuzL.js +0 -16
  1020. package/codeyam-cli/src/webserver/build/client/assets/search-DY8yoDpH.js +0 -1
  1021. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  1022. package/codeyam-cli/src/webserver/build/client/assets/settings-BT6wVHd5.js +0 -1
  1023. package/codeyam-cli/src/webserver/build/client/assets/simulations-gv3H7JV7.js +0 -1
  1024. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-BthANBVv.js +0 -1
  1025. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-CANr3QJ5.js +0 -1
  1026. package/codeyam-cli/src/webserver/build/server/assets/index-BtBPtyHx.js +0 -1
  1027. package/codeyam-cli/src/webserver/build/server/assets/server-build-N2cTnejq.js +0 -166
  1028. package/codeyam-cli/templates/debug-command.md +0 -141
  1029. package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
  1030. package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
  1031. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -136
  1032. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
  1033. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -220
  1034. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
  1035. package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -241
  1036. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
  1037. package/packages/ai/src/lib/isFrontend.js +0 -5
  1038. package/packages/ai/src/lib/isFrontend.js.map +0 -1
  1039. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
  1040. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
  1041. package/packages/ai/src/lib/transformMockDataToMatchSchema.js +0 -124
  1042. package/packages/ai/src/lib/transformMockDataToMatchSchema.js.map +0 -1
  1043. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -72
  1044. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
  1045. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  1046. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  1047. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  1048. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  1049. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
  1050. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  1051. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  1052. /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
@@ -79,15 +79,29 @@
79
79
  * - `helpers/README.md` - Overview of the helper module architecture
80
80
  */
81
81
  import fillInSchemaGapsAndUnknowns from "./helpers/fillInSchemaGapsAndUnknowns.js";
82
+ import { clearCleanKnownObjectFunctionsCache } from "./helpers/cleanKnownObjectFunctions.js";
83
+ import { clearCleanNonObjectFunctionsCache } from "./helpers/cleanNonObjectFunctions.js";
84
+ /**
85
+ * Patterns that indicate recursive type structures in schema paths.
86
+ * Used by hasExcessivePatternRepetition() to detect exponential path blowup.
87
+ */
88
+ const RECURSIVE_PATH_PATTERNS = [
89
+ /\.attributes\.properties\[\]/g, // TypeScript AST JSX nodes
90
+ /\.children\[\]/g, // Tree structures
91
+ /\.elements\[\]/g, // Array-like structures
92
+ /\.members\[\]/g, // Class/interface members
93
+ /\.properties\[\]/g, // Object properties
94
+ /\.items\[\]/g, // Generic items arrays
95
+ ];
82
96
  import ensureSchemaConsistency from "./helpers/ensureSchemaConsistency.js";
83
97
  import cleanPath from "./helpers/cleanPath.js";
84
98
  import { PathManager } from "./helpers/PathManager.js";
85
- import { uniqueId, uniqueScopeVariables, uniqueScopeAndPaths, } from "./helpers/uniqueIdUtils.js";
99
+ import { uniqueId, uniqueScopeAndPaths, uniqueScopeVariables, } from "./helpers/uniqueIdUtils.js";
86
100
  import selectBestValue from "./helpers/selectBestValue.js";
87
101
  import { VisitedTracker } from "./helpers/VisitedTracker.js";
88
102
  import { DebugTracer } from "./helpers/DebugTracer.js";
89
103
  import { BatchSchemaProcessor } from "./helpers/BatchSchemaProcessor.js";
90
- import { ScopeTreeManager, ROOT_SCOPE_NAME, } from "./helpers/ScopeTreeManager.js";
104
+ import { ROOT_SCOPE_NAME, ScopeTreeManager, } from "./helpers/ScopeTreeManager.js";
91
105
  import cleanScopeNodeName from "./helpers/cleanScopeNodeName.js";
92
106
  import getFunctionCallRoot from "./helpers/getFunctionCallRoot.js";
93
107
  import cleanPathOfNonTransformingFunctions from "./helpers/cleanPathOfNonTransformingFunctions.js";
@@ -108,6 +122,17 @@ export function resetScopeDataStructureMetrics() {
108
122
  followEquivalenciesEarlyExitPhase1Count = 0;
109
123
  followEquivalenciesWithWorkCount = 0;
110
124
  addEquivalencyCallCount = 0;
125
+ // Clear module-level caches to prevent unbounded memory growth across entities
126
+ const knownObjectCache = clearCleanKnownObjectFunctionsCache();
127
+ const nonObjectCache = clearCleanNonObjectFunctionsCache();
128
+ if (knownObjectCache.count > 0 || nonObjectCache.count > 0) {
129
+ const totalBytes = knownObjectCache.estimatedBytes + nonObjectCache.estimatedBytes;
130
+ console.log('CodeYam: Cleared analysis caches', {
131
+ knownObjectCache: `${knownObjectCache.count} entries, ${(knownObjectCache.estimatedBytes / 1024).toFixed(1)}KB`,
132
+ nonObjectCache: `${nonObjectCache.count} entries, ${(nonObjectCache.estimatedBytes / 1024).toFixed(1)}KB`,
133
+ totalKB: `${(totalBytes / 1024).toFixed(1)}KB`,
134
+ });
135
+ }
111
136
  }
112
137
  // Performance: Pre-computed Sets for equivalency reason filtering (O(1) vs O(n))
113
138
  const ALLOWED_EQUIVALENCY_REASONS = new Set([
@@ -140,6 +165,10 @@ const ALLOWED_EQUIVALENCY_REASONS = new Set([
140
165
  'propagated function call return sub-property equivalency',
141
166
  'propagated parent-variable equivalency', // Added: propagate child scope equivalencies to parent scope when variable is defined in parent
142
167
  'where was this function called from', // Added: tracks which scope called an external function
168
+ 'MUI DataGrid renderCell params.row equivalency', // Added: links DataGrid renderCell params.row to rows array elements
169
+ 'MUI Autocomplete getOptionLabel option equivalency', // Added: links Autocomplete getOptionLabel callback param to options array
170
+ 'MUI Autocomplete renderOption option equivalency', // Added: links Autocomplete renderOption callback param to options array
171
+ 'MUI Autocomplete option property equivalency', // Added: propagates property accesses from Autocomplete callbacks
143
172
  ]);
144
173
  const SILENTLY_IGNORED_EQUIVALENCY_REASONS = new Set([
145
174
  'signature of functionCall',
@@ -152,6 +181,7 @@ const SILENTLY_IGNORED_EQUIVALENCY_REASONS = new Set([
152
181
  'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
153
182
  'transformed non-object function equivalency - Array.from() equivalency',
154
183
  'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
184
+ // 'transformed non-object function equivalency - Explicit array deconstruction equivalency value',
155
185
  ]);
156
186
  export class ScopeDataStructure {
157
187
  // Getter for backward compatibility - returns the tree structure
@@ -172,6 +202,26 @@ export class ScopeDataStructure {
172
202
  * Maps local variable path to array of usages.
173
203
  */
174
204
  this.rawConditionalUsages = {};
205
+ /**
206
+ * Conditional effects collected during AST analysis.
207
+ * Tracks what setter calls happen inside conditionals (if, switch, ternary).
208
+ */
209
+ this.rawConditionalEffects = [];
210
+ /**
211
+ * Compound conditionals collected during AST analysis.
212
+ * Groups conditions that must all be true together (e.g., a && b && c).
213
+ */
214
+ this.rawCompoundConditionals = [];
215
+ /**
216
+ * Gating conditions for child component boundaries.
217
+ * Maps child component name to the conditions that must be true for it to render.
218
+ */
219
+ this.rawChildBoundaryGatingConditions = {};
220
+ /**
221
+ * JSX rendering usages collected during AST analysis.
222
+ * Tracks arrays rendered via .map() and strings interpolated in JSX.
223
+ */
224
+ this.rawJsxRenderingUsages = [];
175
225
  this.lastAddToSchemaId = 0;
176
226
  this.lastEquivalencyId = 0;
177
227
  this.lastEquivalencyDatabaseId = 0;
@@ -183,6 +233,9 @@ export class ScopeDataStructure {
183
233
  // Index for O(1) lookup of external function calls by name
184
234
  // Invalidated by setting to null; rebuilt lazily on next access
185
235
  this.externalFunctionCallsIndex = null;
236
+ // Tracks internal functions that have been filtered out during captureCompleteSchema
237
+ // Prevents re-adding them via subsequent equivalency propagation (e.g., from getReturnValue)
238
+ this.filteredInternalFunctions = new Set();
186
239
  // Debug tracer for selective path/scope tracing
187
240
  // Enable via: CODEYAM_DEBUG=true CODEYAM_DEBUG_PATHS="user.*,signature" npm test
188
241
  this.tracer = new DebugTracer({
@@ -301,6 +354,8 @@ export class ScopeDataStructure {
301
354
  const efcName = this.pathManager.stripGenerics(efc.name);
302
355
  for (const manager of this.equivalencyManagers) {
303
356
  if (manager.internalFunctions.has(efcName)) {
357
+ // Track this so we don't re-add it via subsequent finalize calls
358
+ this.filteredInternalFunctions.add(efcName);
304
359
  return false;
305
360
  }
306
361
  }
@@ -321,11 +376,42 @@ export class ScopeDataStructure {
321
376
  });
322
377
  entry.sourceCandidates = entry.sourceCandidates.filter((candidate) => {
323
378
  const baseName = this.pathManager.stripGenerics(candidate.scopeNodeName);
379
+ // Check if this is a local variable path (doesn't contain function call pattern)
380
+ // Local variables like "surveys[]" or "items[]" are important for tracing data flow
381
+ // from parent to child components (e.g., surveys[] -> SurveyCard().signature[0].survey)
382
+ const isLocalVariablePath = !candidate.schemaPath.includes('()') &&
383
+ !candidate.schemaPath.startsWith('signature[') &&
384
+ !candidate.schemaPath.startsWith('returnValue');
324
385
  return (validExternalFacingScopeNames.has(baseName) &&
325
386
  (candidate.schemaPath.startsWith('signature[') ||
326
- candidate.schemaPath.startsWith(baseName)) &&
387
+ candidate.schemaPath.startsWith(baseName) ||
388
+ isLocalVariablePath) &&
327
389
  !containsArrayMethod(candidate.schemaPath));
328
390
  });
391
+ // If all sourceCandidates were filtered out (e.g., because they belonged to
392
+ // internal functions like useState), look for the highest-order intermediate
393
+ // that belongs to a valid external-facing scope
394
+ if (entry.sourceCandidates.length === 0 &&
395
+ Object.keys(entry.intermediatesOrder).length > 0) {
396
+ // Find intermediates that belong to valid external-facing scopes
397
+ const validIntermediates = Object.entries(entry.intermediatesOrder)
398
+ .filter(([pathId]) => {
399
+ const [scopeNodeName, schemaPath] = pathId.split('::');
400
+ if (!scopeNodeName || !schemaPath)
401
+ return false;
402
+ const baseName = this.pathManager.stripGenerics(scopeNodeName);
403
+ return (validExternalFacingScopeNames.has(baseName) &&
404
+ !containsArrayMethod(schemaPath));
405
+ })
406
+ .sort((a, b) => b[1] - a[1]); // Sort by order descending (highest first)
407
+ if (validIntermediates.length > 0) {
408
+ const [pathId] = validIntermediates[0];
409
+ const [scopeNodeName, schemaPath] = pathId.split('::');
410
+ if (scopeNodeName && schemaPath) {
411
+ entry.sourceCandidates.push({ scopeNodeName, schemaPath });
412
+ }
413
+ }
414
+ }
329
415
  }
330
416
  this.propagateSourceAndUsageEquivalencies(this.scopeNodes[this.scopeTreeManager.getRootName()]);
331
417
  for (const externalFunctionCall of this.externalFunctionCalls) {
@@ -390,6 +476,10 @@ export class ScopeDataStructure {
390
476
  }
391
477
  return;
392
478
  }
479
+ // PERF: Early exit for paths with repeated function-call signature patterns
480
+ if (this.hasExcessivePatternRepetition(path)) {
481
+ return;
482
+ }
393
483
  // Update chain metadata for database tracking
394
484
  if (equivalencyValueChain.length > 0) {
395
485
  equivalencyValueChain[equivalencyValueChain.length - 1].addToSchemaId =
@@ -559,7 +649,6 @@ export class ScopeDataStructure {
559
649
  }
560
650
  addEquivalency(path, equivalentPath, equivalentScopeName, scopeNode, equivalencyReason, equivalencyValueChain, traceId) {
561
651
  var _a;
562
- // DEBUG: Detect infinite loops
563
652
  addEquivalencyCallCount++;
564
653
  if (addEquivalencyCallCount > 50000) {
565
654
  console.error('INFINITE LOOP DETECTED in addEquivalency', {
@@ -610,12 +699,28 @@ export class ScopeDataStructure {
610
699
  return;
611
700
  }
612
701
  if (!equivalentScopeName) {
613
- console.warn('Debug Propagation: missing equivalent scope name', {
702
+ console.error('CodeYam Error: Missing equivalent scope name - FULL CONTEXT:', JSON.stringify({
614
703
  path,
615
704
  equivalentPath,
616
705
  equivalentScopeName,
617
706
  scopeNodeName: scopeNode.name,
618
- });
707
+ equivalencyReason,
708
+ tree: scopeNode.tree,
709
+ equivalencyValueChain: equivalencyValueChain?.map((ev) => ({
710
+ id: ev.id,
711
+ source: ev.source,
712
+ reason: ev.reason,
713
+ currentPath: ev.currentPath,
714
+ previousPath: ev.previousPath,
715
+ })),
716
+ scopeNodeFunctionCalls: scopeNode.functionCalls?.map((fc) => ({
717
+ name: fc.name,
718
+ callSignature: fc.callSignature,
719
+ callScope: fc.callScope,
720
+ })),
721
+ instantiatedVariables: scopeNode.instantiatedVariables,
722
+ parentInstantiatedVariables: scopeNode.parentInstantiatedVariables,
723
+ }, null, 2));
619
724
  throw new Error('CodeYam Error: Missing equivalent scope name');
620
725
  }
621
726
  (_a = scopeNode.equivalencies)[path] || (_a[path] = []);
@@ -738,10 +843,31 @@ export class ScopeDataStructure {
738
843
  const searchKey = getFunctionCallRoot(functionCallInfo.callSignature);
739
844
  const existingFunctionCall = this.getExternalFunctionCallsIndex().get(searchKey);
740
845
  if (existingFunctionCall) {
741
- existingFunctionCall.schema = {
846
+ // Preserve per-call schemas BEFORE merging to enable per-variable mock data.
847
+ // This is critical for hooks like useFetcher<UserData>() vs useFetcher<ReportData>()
848
+ // where each call returns different typed data.
849
+ if (!existingFunctionCall.perCallSignatureSchemas) {
850
+ // First merge - save the existing call's schema
851
+ existingFunctionCall.perCallSignatureSchemas = {
852
+ [existingFunctionCall.callSignature]: {
853
+ ...existingFunctionCall.schema,
854
+ },
855
+ };
856
+ }
857
+ // Save the new call's schema before it gets merged
858
+ existingFunctionCall.perCallSignatureSchemas[functionCallInfo.callSignature] = { ...functionCallInfo.schema };
859
+ // Merge schemas using selectBestValue to preserve specific types like 'null'
860
+ // over generic types like 'unknown'. This ensures ref variables detected
861
+ // earlier (marked as 'null') aren't overwritten by later 'unknown' values.
862
+ const mergedSchema = {
742
863
  ...existingFunctionCall.schema,
743
- ...functionCallInfo.schema,
744
864
  };
865
+ for (const key in functionCallInfo.schema) {
866
+ const existingValue = existingFunctionCall.schema[key];
867
+ const newValue = functionCallInfo.schema[key];
868
+ mergedSchema[key] = selectBestValue(existingValue, newValue, newValue);
869
+ }
870
+ existingFunctionCall.schema = mergedSchema;
745
871
  existingFunctionCall.equivalencies = {
746
872
  ...existingFunctionCall.equivalencies,
747
873
  ...functionCallInfo.equivalencies,
@@ -761,8 +887,13 @@ export class ScopeDataStructure {
761
887
  const isExternal = !callingScopeNode.instantiatedVariables?.includes(functionCallInfoNameParts[0]) &&
762
888
  !callingScopeNode.parentInstantiatedVariables?.includes(functionCallInfoNameParts[0]);
763
889
  if (isExternal) {
764
- this.externalFunctionCalls.push(functionCallInfo);
765
- this.invalidateExternalFunctionCallsIndex();
890
+ // Check if this function was already filtered out as an internal function
891
+ // (e.g., useState was filtered in captureCompleteSchema but finalize is trying to re-add it)
892
+ const strippedName = this.pathManager.stripGenerics(functionCallInfo.name);
893
+ if (!this.filteredInternalFunctions.has(strippedName)) {
894
+ this.externalFunctionCalls.push(functionCallInfo);
895
+ this.invalidateExternalFunctionCallsIndex();
896
+ }
766
897
  }
767
898
  }
768
899
  }
@@ -831,9 +962,26 @@ export class ScopeDataStructure {
831
962
  const remainingKey = remainingSchemaPathParts.join('|');
832
963
  const equivalentSchemaPath = equivalentSchemaPathMap.get(remainingKey);
833
964
  if (equivalentSchemaPath) {
965
+ // Skip propagation when there's a structural mismatch:
966
+ // - schemaPath ends with [] (array element, represents an object)
967
+ // - equivalentSchemaPath doesn't end with [] (non-array prop, usually a scalar)
968
+ // This prevents incorrectly typing array elements as strings when they're
969
+ // equivalent to scalar props like JSX keys (e.g., workouts[] ↔ Card().key)
970
+ const schemaPathEndsWithArray = schemaPath.endsWith('[]');
971
+ const equivalentEndsWithArray = equivalentSchemaPath.endsWith('[]');
972
+ if (schemaPathEndsWithArray !== equivalentEndsWithArray) {
973
+ // Don't propagate between array element paths and non-array paths
974
+ continue;
975
+ }
834
976
  const value1 = scopeNode.schema[schemaPath];
835
977
  const value2 = equivalentScopeNode.schema[equivalentSchemaPath];
836
978
  const bestValue = selectBestValue(value1, value2);
979
+ // PERF: Skip paths with repeated function-call signature patterns
980
+ // to prevent recursive type expansion (e.g., string.localeCompare returns string)
981
+ if (this.hasExcessivePatternRepetition(schemaPath) ||
982
+ this.hasExcessivePatternRepetition(equivalentSchemaPath)) {
983
+ continue;
984
+ }
837
985
  scopeNode.schema[schemaPath] = bestValue;
838
986
  equivalentScopeNode.schema[equivalentSchemaPath] = bestValue;
839
987
  }
@@ -845,6 +993,10 @@ export class ScopeDataStructure {
845
993
  equivalentPath,
846
994
  ...remainingSchemaPathParts,
847
995
  ]);
996
+ // PERF: Skip paths with repeated function-call signature patterns
997
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
998
+ continue;
999
+ }
848
1000
  equivalentScopeNode.schema[newEquivalentPath] =
849
1001
  scopeNode.schema[schemaPath];
850
1002
  }
@@ -901,26 +1053,103 @@ export class ScopeDataStructure {
901
1053
  isValidPath(path) {
902
1054
  return this.pathManager.isValidPath(path);
903
1055
  }
1056
+ /**
1057
+ * Detects if a path contains excessive repetition of the same pattern.
1058
+ *
1059
+ * This prevents exponential blowup when analyzing recursive type structures.
1060
+ * For example, TypeScript AST nodes have `.attributes.properties[]` where each
1061
+ * property is also a node with `.attributes.properties[]`. Without this check,
1062
+ * paths like `signature[0].attributes.properties[].attributes.properties[].attributes.properties[]...`
1063
+ * would be generated exponentially.
1064
+ *
1065
+ * Two detection strategies:
1066
+ * 1. Known patterns: Check RECURSIVE_PATH_PATTERNS for common recursive structures
1067
+ * 2. Generic detection: For longer paths, detect any 2-3 part segment that repeats
1068
+ *
1069
+ * @param path - The schema path to check
1070
+ * @param maxRepetitions - Maximum allowed repetitions of any pattern (default: 2)
1071
+ * @returns true if the path has excessive repetition
1072
+ */
1073
+ hasExcessivePatternRepetition(path, maxRepetitions = 2) {
1074
+ // Check known recursive patterns
1075
+ for (const pattern of RECURSIVE_PATH_PATTERNS) {
1076
+ const matches = path.match(pattern);
1077
+ if (matches && matches.length > maxRepetitions) {
1078
+ return true;
1079
+ }
1080
+ }
1081
+ // Check for repeated function calls that indicate recursive type expansion.
1082
+ // E.g., localeCompare(b[])...localeCompare(b[]) means string.localeCompare
1083
+ // returns a type that again has localeCompare, causing infinite expansion.
1084
+ // We extract all function call patterns like "funcName(args)" and check if
1085
+ // the same normalized call appears more than once.
1086
+ const funcCallPattern = /(?:^|\.)[^.([]+\([^)]*\)/g;
1087
+ const funcCallMatches = path.match(funcCallPattern);
1088
+ if (funcCallMatches && funcCallMatches.length > 1) {
1089
+ const seen = new Set();
1090
+ for (const match of funcCallMatches) {
1091
+ // Strip leading dot and normalize array indices
1092
+ const normalized = match.replace(/^\./, '').replace(/\[\d+\]/g, '[]');
1093
+ if (seen.has(normalized))
1094
+ return true;
1095
+ seen.add(normalized);
1096
+ }
1097
+ }
1098
+ // For longer paths, detect any repeated multi-part segments we haven't explicitly listed
1099
+ const pathParts = this.splitPath(path);
1100
+ if (pathParts.length <= 6) {
1101
+ return false;
1102
+ }
1103
+ // Check for repeated sequences of 2-3 consecutive parts
1104
+ for (let segmentLength = 2; segmentLength <= 3; segmentLength++) {
1105
+ const seen = new Map();
1106
+ for (let i = 0; i <= pathParts.length - segmentLength; i++) {
1107
+ const segment = pathParts.slice(i, i + segmentLength).join('.');
1108
+ const normalizedSegment = segment.replace(/\[\d+\]/g, '[]');
1109
+ const count = (seen.get(normalizedSegment) || 0) + 1;
1110
+ seen.set(normalizedSegment, count);
1111
+ if (count > maxRepetitions) {
1112
+ return true;
1113
+ }
1114
+ }
1115
+ }
1116
+ return false;
1117
+ }
904
1118
  addToTree(pathParts) {
905
1119
  this.scopeTreeManager.addPath(pathParts);
906
1120
  }
907
1121
  setInstantiatedVariables(scopeNode) {
908
1122
  let instantiatedVariables = scopeNode.analysis?.instantiatedVariables ?? [];
909
- for (const [path, equivalentPath] of Object.entries(scopeNode.analysis.isolatedEquivalentVariables ?? {})) {
910
- if (typeof equivalentPath !== 'string') {
911
- continue;
912
- }
913
- if (equivalentPath.startsWith('signature[')) {
914
- const equivalentPathParts = this.splitPath(equivalentPath);
915
- instantiatedVariables.push(equivalentPathParts[0]);
916
- instantiatedVariables.push(path);
1123
+ for (const [path, rawEquivalentPath] of Object.entries(scopeNode.analysis.isolatedEquivalentVariables ?? {})) {
1124
+ // Normalize to array for consistent handling (supports both string and string[])
1125
+ const equivalentPaths = Array.isArray(rawEquivalentPath)
1126
+ ? rawEquivalentPath
1127
+ : rawEquivalentPath
1128
+ ? [rawEquivalentPath]
1129
+ : [];
1130
+ for (const equivalentPath of equivalentPaths) {
1131
+ if (typeof equivalentPath !== 'string') {
1132
+ continue;
1133
+ }
1134
+ if (equivalentPath.startsWith('signature[')) {
1135
+ const equivalentPathParts = this.splitPath(equivalentPath);
1136
+ instantiatedVariables.push(equivalentPathParts[0]);
1137
+ instantiatedVariables.push(path);
1138
+ }
917
1139
  }
918
1140
  const duplicateInstantiated = instantiatedVariables.find((v) => path.split('::cyDuplicateKey')[0] === v.split('::cyDuplicateKey')[0]);
919
1141
  if (duplicateInstantiated) {
920
1142
  instantiatedVariables.push(path);
921
1143
  }
922
1144
  }
923
- instantiatedVariables = instantiatedVariables.filter((varName, index, self) => self.indexOf(varName) === index);
1145
+ const instantiatedSeen = new Set();
1146
+ instantiatedVariables = instantiatedVariables.filter((varName) => {
1147
+ if (instantiatedSeen.has(varName)) {
1148
+ return false;
1149
+ }
1150
+ instantiatedSeen.add(varName);
1151
+ return true;
1152
+ });
924
1153
  scopeNode.instantiatedVariables = instantiatedVariables;
925
1154
  if (!scopeNode.tree || scopeNode.tree.length === 0) {
926
1155
  return;
@@ -932,125 +1161,156 @@ export class ScopeDataStructure {
932
1161
  const parentInstantiatedVariables = [
933
1162
  ...(parentScopeNode.parentInstantiatedVariables ?? []),
934
1163
  ...parentScopeNode.instantiatedVariables.filter((v) => !v.startsWith('signature[') && !v.startsWith('returnValue')),
935
- ].filter((varName, index, self) => !instantiatedVariables.includes(varName) &&
936
- self.indexOf(varName) === index);
937
- scopeNode.parentInstantiatedVariables = parentInstantiatedVariables;
1164
+ ].filter((varName) => !instantiatedSeen.has(varName));
1165
+ const parentInstantiatedSeen = new Set();
1166
+ const dedupedParentInstantiatedVariables = parentInstantiatedVariables.filter((varName) => {
1167
+ if (parentInstantiatedSeen.has(varName)) {
1168
+ return false;
1169
+ }
1170
+ parentInstantiatedSeen.add(varName);
1171
+ return true;
1172
+ });
1173
+ scopeNode.parentInstantiatedVariables = dedupedParentInstantiatedVariables;
938
1174
  }
939
1175
  trackFunctionCalls(scopeNode) {
940
1176
  this.captureFunctionCalls(scopeNode);
941
1177
  this.checkExternalFunctionCalls();
942
1178
  }
943
1179
  determineEquivalenciesAndBuildSchema(scopeNode) {
944
- const { isolatedStructure, isolatedEquivalentVariables } = scopeNode.analysis;
945
- // DEBUG: Log all equivalencies related to useFetcher
946
- if (Object.keys(isolatedEquivalentVariables || {}).some((k) => k.includes('Fetcher') || k.includes('fetcher'))) {
947
- console.log('CodeYam DEBUG determineEquivalenciesAndBuildSchema:', JSON.stringify({
948
- scopeNodeName: scopeNode.name,
949
- fetcherEquivalencies: Object.entries(isolatedEquivalentVariables || {})
950
- .filter(([k, v]) => k.includes('Fetcher') ||
951
- k.includes('fetcher') ||
952
- String(v).includes('Fetcher') ||
953
- String(v).includes('fetcher'))
954
- .reduce((acc, [k, v]) => {
955
- acc[k] = v;
956
- return acc;
957
- }, {}),
958
- }, null, 2));
1180
+ if (!scopeNode.analysis) {
1181
+ return;
959
1182
  }
1183
+ const { isolatedStructure, isolatedEquivalentVariables } = scopeNode.analysis;
1184
+ // Flatten isolatedEquivalentVariables values for allPaths (handles both string and string[])
1185
+ const flattenedEquivValues = Object.values(isolatedEquivalentVariables || {}).flatMap((v) => (Array.isArray(v) ? v : [v]));
960
1186
  const allPaths = Array.from(new Set([
961
1187
  ...Object.keys(isolatedStructure || {}),
962
1188
  ...Object.keys(isolatedEquivalentVariables || {}),
963
- ...Object.values(isolatedEquivalentVariables || {}),
1189
+ ...flattenedEquivValues,
964
1190
  ]));
965
1191
  for (let path in isolatedEquivalentVariables) {
966
- let equivalentValue = isolatedEquivalentVariables?.[path];
967
- if (equivalentValue && this.isValidPath(equivalentValue)) {
968
- path = cleanPath(path.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
969
- equivalentValue = cleanPath(equivalentValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
970
- this.addEquivalency(path, equivalentValue, scopeNode.name, scopeNode, 'original equivalency');
971
- // Propagate equivalencies involving parent-scope variables to those parent scopes.
972
- // This handles patterns like: collected.push({...entity}) where 'collected' is defined
973
- // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
974
- // visible when tracing from the parent scope.
975
- const rootVariable = this.extractRootVariable(path);
976
- const equivalentRootVariable = this.extractRootVariable(equivalentValue);
977
- // Skip propagation for self-referential reassignment patterns like:
978
- // x = x.method().functionCallReturnValue
979
- // where the path IS the variable itself (not a sub-path like x[] or x.prop).
980
- // These create circular references since both sides reference the same variable.
981
- //
982
- // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
983
- // where the path has additional segments beyond the root variable.
984
- const pathIsJustRootVariable = path === rootVariable;
985
- const isSelfReferentialReassignment = pathIsJustRootVariable && rootVariable === equivalentRootVariable;
986
- if (rootVariable &&
987
- !isSelfReferentialReassignment &&
988
- scopeNode.parentInstantiatedVariables?.includes(rootVariable)) {
989
- // Find the parent scope where this variable is defined
990
- for (const parentScopeName of scopeNode.tree || []) {
991
- const parentScope = this.scopeNodes[parentScopeName];
992
- if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
993
- // Add the equivalency to the parent scope as well
994
- this.addEquivalency(path, equivalentValue, scopeNode.name, // The equivalent path's scope remains the child scope
995
- parentScope, // But store it in the parent scope's equivalencies
996
- 'propagated parent-variable equivalency');
997
- break;
1192
+ const rawEquivalentValue = isolatedEquivalentVariables?.[path];
1193
+ // Normalize to array for consistent handling
1194
+ const equivalentValues = Array.isArray(rawEquivalentValue)
1195
+ ? rawEquivalentValue
1196
+ : [rawEquivalentValue];
1197
+ for (let equivalentValue of equivalentValues) {
1198
+ if (equivalentValue && this.isValidPath(equivalentValue)) {
1199
+ // IMPORTANT: DO NOT strip ::cyDuplicateKey:: markers from equivalencies.
1200
+ // These markers are critical for distinguishing variable reassignments.
1201
+ // For example, with:
1202
+ // let fetcher = useFetcher<ConfigData>();
1203
+ // const configData = fetcher.data?.data;
1204
+ // fetcher = useFetcher<SettingsData>();
1205
+ // const settingsData = fetcher.data?.data;
1206
+ //
1207
+ // mergeStatements creates:
1208
+ // fetcher useFetcher<ConfigData>()...
1209
+ // fetcher::cyDuplicateKey1:: useFetcher<SettingsData>()...
1210
+ // configData fetcher.data.data
1211
+ // settingsData fetcher::cyDuplicateKey1::.data.data
1212
+ //
1213
+ // If we strip ::cyDuplicateKey::, settingsData would incorrectly trace
1214
+ // to useFetcher<ConfigData>() instead of useFetcher<SettingsData>().
1215
+ path = cleanPath(path, allPaths);
1216
+ equivalentValue = cleanPath(equivalentValue, allPaths);
1217
+ this.addEquivalency(path, equivalentValue, scopeNode.name, scopeNode, 'original equivalency');
1218
+ // Propagate equivalencies involving parent-scope variables to those parent scopes.
1219
+ // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1220
+ // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1221
+ // visible when tracing from the parent scope.
1222
+ const rootVariable = this.extractRootVariable(path);
1223
+ const equivalentRootVariable = this.extractRootVariable(equivalentValue);
1224
+ // Skip propagation for self-referential reassignment patterns like:
1225
+ // x = x.method().functionCallReturnValue
1226
+ // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1227
+ // These create circular references since both sides reference the same variable.
1228
+ //
1229
+ // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1230
+ // where the path has additional segments beyond the root variable.
1231
+ const pathIsJustRootVariable = path === rootVariable;
1232
+ const isSelfReferentialReassignment = pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1233
+ if (rootVariable &&
1234
+ !isSelfReferentialReassignment &&
1235
+ scopeNode.parentInstantiatedVariables?.includes(rootVariable)) {
1236
+ // Find the parent scope where this variable is defined
1237
+ for (const parentScopeName of scopeNode.tree || []) {
1238
+ const parentScope = this.scopeNodes[parentScopeName];
1239
+ if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1240
+ // Add the equivalency to the parent scope as well
1241
+ this.addEquivalency(path, equivalentValue, scopeNode.name, // The equivalent path's scope remains the child scope
1242
+ parentScope, // But store it in the parent scope's equivalencies
1243
+ 'propagated parent-variable equivalency');
1244
+ break;
1245
+ }
998
1246
  }
999
1247
  }
1000
- }
1001
- // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1002
- // that has sub-properties defined in the isolatedEquivalentVariables.
1003
- // This handles cases like: dataItem={{ structure: completeDataStructure }}
1004
- // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1005
- // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1006
- const isSimpleVariable = !equivalentValue.startsWith('signature[') &&
1007
- !equivalentValue.includes('functionCallReturnValue') &&
1008
- !equivalentValue.includes('.') &&
1009
- !equivalentValue.includes('[');
1010
- if (isSimpleVariable) {
1011
- // Look in current scope and all parent scopes for sub-properties
1012
- const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1013
- for (const scopeName of scopesToCheck) {
1014
- const checkScope = this.scopeNodes[scopeName];
1015
- if (!checkScope?.analysis?.isolatedEquivalentVariables)
1016
- continue;
1017
- for (const [subPath, subValue] of Object.entries(checkScope.analysis.isolatedEquivalentVariables)) {
1018
- // Check if this is a sub-property of the equivalentValue variable
1019
- // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1020
- const matchesDot = subPath.startsWith(equivalentValue + '.');
1021
- const matchesBracket = subPath.startsWith(equivalentValue + '[');
1022
- if (matchesDot || matchesBracket) {
1023
- const subPropertyPath = subPath.substring(equivalentValue.length);
1024
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1025
- const newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1026
- if (newEquivalentValue &&
1027
- this.isValidPath(newEquivalentValue)) {
1028
- this.addEquivalency(newPath, newEquivalentValue, checkScope.name, // Use the scope where the sub-property was found
1029
- scopeNode, 'propagated sub-property equivalency');
1248
+ // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1249
+ // that has sub-properties defined in the isolatedEquivalentVariables.
1250
+ // This handles cases like: dataItem={{ structure: completeDataStructure }}
1251
+ // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1252
+ // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1253
+ const isSimpleVariable = !equivalentValue.startsWith('signature[') &&
1254
+ !equivalentValue.includes('functionCallReturnValue') &&
1255
+ !equivalentValue.includes('.') &&
1256
+ !equivalentValue.includes('[');
1257
+ if (isSimpleVariable) {
1258
+ // Look in current scope and all parent scopes for sub-properties
1259
+ const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1260
+ for (const scopeName of scopesToCheck) {
1261
+ const checkScope = this.scopeNodes[scopeName];
1262
+ if (!checkScope?.analysis?.isolatedEquivalentVariables)
1263
+ continue;
1264
+ for (const [subPath, rawSubValue] of Object.entries(checkScope.analysis.isolatedEquivalentVariables)) {
1265
+ // Normalize to array for consistent handling
1266
+ const subValues = Array.isArray(rawSubValue)
1267
+ ? rawSubValue
1268
+ : rawSubValue
1269
+ ? [rawSubValue]
1270
+ : [];
1271
+ // Check if this is a sub-property of the equivalentValue variable
1272
+ // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1273
+ const matchesDot = subPath.startsWith(equivalentValue + '.');
1274
+ const matchesBracket = subPath.startsWith(equivalentValue + '[');
1275
+ if (matchesDot || matchesBracket) {
1276
+ const subPropertyPath = subPath.substring(equivalentValue.length);
1277
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
1278
+ for (const subValue of subValues) {
1279
+ if (typeof subValue !== 'string')
1280
+ continue;
1281
+ const newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1282
+ if (newEquivalentValue &&
1283
+ this.isValidPath(newEquivalentValue)) {
1284
+ this.addEquivalency(newPath, newEquivalentValue, checkScope.name, // Use the scope where the sub-property was found
1285
+ scopeNode, 'propagated sub-property equivalency');
1286
+ }
1287
+ }
1288
+ }
1289
+ // Also check if equivalentValue itself maps to a functionCallReturnValue
1290
+ // e.g., result = useMemo(...).functionCallReturnValue
1291
+ for (const subValue of subValues) {
1292
+ if (subPath === equivalentValue &&
1293
+ typeof subValue === 'string' &&
1294
+ subValue.endsWith('.functionCallReturnValue')) {
1295
+ this.propagateFunctionCallReturnSubProperties(path, subValue, scopeNode, allPaths);
1296
+ }
1030
1297
  }
1031
- }
1032
- // Also check if equivalentValue itself maps to a functionCallReturnValue
1033
- // e.g., result = useMemo(...).functionCallReturnValue
1034
- if (subPath === equivalentValue &&
1035
- typeof subValue === 'string' &&
1036
- subValue.endsWith('.functionCallReturnValue')) {
1037
- this.propagateFunctionCallReturnSubProperties(path, subValue, scopeNode, allPaths);
1038
1298
  }
1039
1299
  }
1040
1300
  }
1041
- }
1042
- // Handle function call return values by propagating returnValue.* sub-properties
1043
- // from the callback scope to the usage path
1044
- if (equivalentValue.endsWith('.functionCallReturnValue')) {
1045
- this.propagateFunctionCallReturnSubProperties(path, equivalentValue, scopeNode, allPaths);
1046
- // Track which variable receives the return value of each function call
1047
- // This enables generating separate mock data for each call site
1048
- this.trackReceivingVariable(path, equivalentValue);
1049
- }
1050
- // Also track variables that receive destructured properties from function call return values
1051
- // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1052
- if (equivalentValue.includes('.functionCallReturnValue.')) {
1053
- this.trackReceivingVariable(path, equivalentValue);
1301
+ // Handle function call return values by propagating returnValue.* sub-properties
1302
+ // from the callback scope to the usage path
1303
+ if (equivalentValue.endsWith('.functionCallReturnValue')) {
1304
+ this.propagateFunctionCallReturnSubProperties(path, equivalentValue, scopeNode, allPaths);
1305
+ // Track which variable receives the return value of each function call
1306
+ // This enables generating separate mock data for each call site
1307
+ this.trackReceivingVariable(path, equivalentValue);
1308
+ }
1309
+ // Also track variables that receive destructured properties from function call return values
1310
+ // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1311
+ if (equivalentValue.includes('.functionCallReturnValue.')) {
1312
+ this.trackReceivingVariable(path, equivalentValue);
1313
+ }
1054
1314
  }
1055
1315
  }
1056
1316
  }
@@ -1058,7 +1318,7 @@ export class ScopeDataStructure {
1058
1318
  // This eliminates deep call stacks and improves deduplication
1059
1319
  this.batchProcessor = new BatchSchemaProcessor();
1060
1320
  this.batchQueuedSet = new Set();
1061
- for (const key of Array.from(allPaths)) {
1321
+ for (const key of allPaths) {
1062
1322
  let value = isolatedStructure[key] ?? 'unknown';
1063
1323
  if (['null', 'undefined'].includes(value)) {
1064
1324
  value = 'unknown';
@@ -1092,7 +1352,14 @@ export class ScopeDataStructure {
1092
1352
  processBatchQueue() {
1093
1353
  if (!this.batchProcessor)
1094
1354
  return;
1355
+ let iterations = 0;
1095
1356
  while (this.batchProcessor.hasWork()) {
1357
+ iterations++;
1358
+ // Safety: detect potential infinite loops
1359
+ if (iterations > 100000) {
1360
+ console.error(`[ScopeDataStructure] processBatchQueue exceeded 100k iterations, possible infinite loop!`);
1361
+ break;
1362
+ }
1096
1363
  const item = this.batchProcessor.getNextWork();
1097
1364
  if (!item)
1098
1365
  break;
@@ -1139,18 +1406,6 @@ export class ScopeDataStructure {
1139
1406
  // Find the FunctionCallInfo that matches this call signature
1140
1407
  const searchKey = getFunctionCallRoot(callSignature);
1141
1408
  const functionCallInfo = this.getExternalFunctionCallsIndex().get(searchKey);
1142
- // DEBUG: Track useFetcher calls
1143
- if (searchKey === 'useFetcher' || callSignature.includes('useFetcher')) {
1144
- console.log('CodeYam DEBUG trackReceivingVariable:', JSON.stringify({
1145
- receivingVariable,
1146
- equivalentValue,
1147
- callSignature,
1148
- searchKey,
1149
- foundFunctionCallInfo: !!functionCallInfo,
1150
- existingRecvVars: functionCallInfo?.receivingVariableNames,
1151
- existingCallSigToVar: functionCallInfo?.callSignatureToVariable,
1152
- }, null, 2));
1153
- }
1154
1409
  if (!functionCallInfo) {
1155
1410
  return;
1156
1411
  }
@@ -1199,8 +1454,15 @@ export class ScopeDataStructure {
1199
1454
  const checkScope = this.scopeNodes[scopeName];
1200
1455
  if (!checkScope?.analysis?.isolatedEquivalentVariables)
1201
1456
  continue;
1202
- const functionRef = checkScope.analysis.isolatedEquivalentVariables[functionName];
1203
- if (typeof functionRef === 'string' && functionRef.endsWith('F')) {
1457
+ const rawFunctionRef = checkScope.analysis.isolatedEquivalentVariables[functionName];
1458
+ // Normalize to array and find first string ending with 'F'
1459
+ const functionRefs = Array.isArray(rawFunctionRef)
1460
+ ? rawFunctionRef
1461
+ : rawFunctionRef
1462
+ ? [rawFunctionRef]
1463
+ : [];
1464
+ const functionRef = functionRefs.find((r) => typeof r === 'string' && r.endsWith('F'));
1465
+ if (typeof functionRef === 'string') {
1204
1466
  callbackScopeName = functionRef.slice(0, -1);
1205
1467
  break;
1206
1468
  }
@@ -1223,22 +1485,32 @@ export class ScopeDataStructure {
1223
1485
  if (!callbackScope.analysis?.isolatedEquivalentVariables)
1224
1486
  return;
1225
1487
  const isolatedVars = callbackScope.analysis.isolatedEquivalentVariables;
1488
+ // Get the first returnValue equivalency (normalize array to single value for these checks)
1489
+ const rawReturnValue = isolatedVars.returnValue;
1490
+ const firstReturnValue = Array.isArray(rawReturnValue)
1491
+ ? rawReturnValue[0]
1492
+ : rawReturnValue;
1226
1493
  // First, check if returnValue is an alias to another variable (e.g., returnValue = intermediate)
1227
1494
  // If so, we need to look for that variable's sub-properties too
1228
- const returnValueAlias = typeof isolatedVars.returnValue === 'string' &&
1229
- !isolatedVars.returnValue.includes('.')
1230
- ? isolatedVars.returnValue
1495
+ const returnValueAlias = typeof firstReturnValue === 'string' && !firstReturnValue.includes('.')
1496
+ ? firstReturnValue
1231
1497
  : undefined;
1232
1498
  // Pattern 3: Object.keys(X).reduce() - the reduce result has the same sub-properties as X
1233
1499
  // When returnValue = "Object.keys(source).reduce(...).functionCallReturnValue", look for source.* sub-properties
1234
1500
  let reduceSourceVar;
1235
- if (typeof isolatedVars.returnValue === 'string') {
1236
- const reduceMatch = isolatedVars.returnValue.match(/^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/);
1501
+ if (typeof firstReturnValue === 'string') {
1502
+ const reduceMatch = firstReturnValue.match(/^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/);
1237
1503
  if (reduceMatch) {
1238
1504
  reduceSourceVar = reduceMatch[1];
1239
1505
  }
1240
1506
  }
1241
- for (const [subPath, subValue] of Object.entries(isolatedVars)) {
1507
+ for (const [subPath, rawSubValue] of Object.entries(isolatedVars)) {
1508
+ // Normalize to array for consistent handling
1509
+ const subValues = Array.isArray(rawSubValue)
1510
+ ? rawSubValue
1511
+ : rawSubValue
1512
+ ? [rawSubValue]
1513
+ : [];
1242
1514
  // Check for direct returnValue.* sub-properties
1243
1515
  const isReturnValueSub = subPath.startsWith('returnValue.') ||
1244
1516
  subPath.startsWith('returnValue[');
@@ -1250,33 +1522,36 @@ export class ScopeDataStructure {
1250
1522
  const isReduceSourceSub = reduceSourceVar &&
1251
1523
  (subPath.startsWith(reduceSourceVar + '.') ||
1252
1524
  subPath.startsWith(reduceSourceVar + '['));
1253
- if (typeof subValue !== 'string' ||
1254
- (!isReturnValueSub && !isAliasSub && !isReduceSourceSub))
1255
- continue;
1256
- // Convert alias/reduceSource paths to returnValue paths
1257
- let effectiveSubPath = subPath;
1258
- if (isAliasSub && !isReturnValueSub) {
1259
- // Replace the alias prefix with returnValue
1260
- effectiveSubPath =
1261
- 'returnValue' + subPath.substring(returnValueAlias.length);
1262
- }
1263
- else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
1264
- // Replace the reduce source prefix with returnValue
1265
- effectiveSubPath =
1266
- 'returnValue' + subPath.substring(reduceSourceVar.length);
1267
- }
1268
- const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
1269
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1270
- let newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1271
- // Resolve variable references through parent scope equivalencies
1272
- const resolved = this.resolveVariableThroughParentScopes(newEquivalentValue, callbackScope, allPaths);
1273
- newEquivalentValue = resolved.resolvedPath;
1274
- const equivalentScopeName = resolved.scopeName;
1275
- if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
1525
+ if (!isReturnValueSub && !isAliasSub && !isReduceSourceSub)
1276
1526
  continue;
1277
- this.addEquivalency(newPath, newEquivalentValue, equivalentScopeName, scopeNode, 'propagated function call return sub-property equivalency');
1278
- // Ensure the database entry has the usage path
1279
- this.addUsageToEquivalencyDatabaseEntry(newPath, newEquivalentValue, equivalentScopeName, scopeNode.name);
1527
+ for (const subValue of subValues) {
1528
+ if (typeof subValue !== 'string')
1529
+ continue;
1530
+ // Convert alias/reduceSource paths to returnValue paths
1531
+ let effectiveSubPath = subPath;
1532
+ if (isAliasSub && !isReturnValueSub) {
1533
+ // Replace the alias prefix with returnValue
1534
+ effectiveSubPath =
1535
+ 'returnValue' + subPath.substring(returnValueAlias.length);
1536
+ }
1537
+ else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
1538
+ // Replace the reduce source prefix with returnValue
1539
+ effectiveSubPath =
1540
+ 'returnValue' + subPath.substring(reduceSourceVar.length);
1541
+ }
1542
+ const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
1543
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
1544
+ let newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1545
+ // Resolve variable references through parent scope equivalencies
1546
+ const resolved = this.resolveVariableThroughParentScopes(newEquivalentValue, callbackScope, allPaths);
1547
+ newEquivalentValue = resolved.resolvedPath;
1548
+ const equivalentScopeName = resolved.scopeName;
1549
+ if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
1550
+ continue;
1551
+ this.addEquivalency(newPath, newEquivalentValue, equivalentScopeName, scopeNode, 'propagated function call return sub-property equivalency');
1552
+ // Ensure the database entry has the usage path
1553
+ this.addUsageToEquivalencyDatabaseEntry(newPath, newEquivalentValue, equivalentScopeName, scopeNode.name);
1554
+ }
1280
1555
  }
1281
1556
  }
1282
1557
  /**
@@ -1308,7 +1583,14 @@ export class ScopeDataStructure {
1308
1583
  const parentScope = this.scopeNodes[parentScopeName];
1309
1584
  if (!parentScope?.analysis?.isolatedEquivalentVariables)
1310
1585
  continue;
1311
- const rootEquiv = parentScope.analysis.isolatedEquivalentVariables[rootVar];
1586
+ const rawRootEquiv = parentScope.analysis.isolatedEquivalentVariables[rootVar];
1587
+ // Normalize to array and use first string value
1588
+ const rootEquivs = Array.isArray(rawRootEquiv)
1589
+ ? rawRootEquiv
1590
+ : rawRootEquiv
1591
+ ? [rawRootEquiv]
1592
+ : [];
1593
+ const rootEquiv = rootEquivs.find((r) => typeof r === 'string');
1312
1594
  if (typeof rootEquiv === 'string') {
1313
1595
  return {
1314
1596
  resolvedPath: cleanPath(rootEquiv + restOfPath, allPaths),
@@ -1502,9 +1784,21 @@ export class ScopeDataStructure {
1502
1784
  const remainingPath = this.joinPathParts(remainingPathParts);
1503
1785
  if (relevantSubPathParts.every((part, i) => part === schemaPathParts[i]) &&
1504
1786
  equivalentValue.scopeNodeName === scopeNode.name) {
1787
+ // DEBUG
1505
1788
  continue;
1506
1789
  }
1507
1790
  const newEquivalentPath = this.joinPathParts([schemaPath, remainingPath]);
1791
+ // PERF: Detect repeated patterns in paths to prevent exponential blowup
1792
+ // Paths like `signature[0].attributes.properties[].attributes.properties[]...`
1793
+ // indicate recursive type structures that cause exponential schema explosion
1794
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
1795
+ if (traceId && debugLevel > 0) {
1796
+ console.info('Debug: skipping path with excessive pattern repetition', {
1797
+ path: newEquivalentPath,
1798
+ });
1799
+ }
1800
+ continue;
1801
+ }
1508
1802
  if (!equivalentScopeNode) {
1509
1803
  if (traceId) {
1510
1804
  console.info('Debug Propagation: missing equivalent scope info', {
@@ -1632,6 +1926,8 @@ export class ScopeDataStructure {
1632
1926
  return;
1633
1927
  }
1634
1928
  const usageScopeNode = this.getScopeOrFunctionCallInfo(usageEquivalency.scopeNodeName);
1929
+ if (!usageScopeNode)
1930
+ continue;
1635
1931
  // Guard against infinite recursion by tracking which paths we've already
1636
1932
  // added from addComplexSourcePathVariables
1637
1933
  if (this.visitedTracker.checkAndMarkComplexSourceVisited(usageScopeNode.name, newUsageEquivalentPath)) {
@@ -1680,6 +1976,8 @@ export class ScopeDataStructure {
1680
1976
  continue;
1681
1977
  }
1682
1978
  const usageScopeNode = this.getScopeOrFunctionCallInfo(usageEquivalency.scopeNodeName);
1979
+ if (!usageScopeNode)
1980
+ continue;
1683
1981
  // This is put in place to avoid propagating array functions like 'filter' through complex equivalencies
1684
1982
  // but may cause problems if the funtion call is not on a known object (e.g. string or array)
1685
1983
  if (newUsageEquivalentPath.endsWith(')') ||
@@ -1776,9 +2074,70 @@ export class ScopeDataStructure {
1776
2074
  // Update inverted index
1777
2075
  this.intermediatesOrderIndex.set(pathId, databaseEntry);
1778
2076
  if (intermediateIndex === 0) {
1779
- const isValidSourceCandidate = pathInfo.schemaPath.startsWith('signature[') ||
2077
+ let isValidSourceCandidate = pathInfo.schemaPath.startsWith('signature[') ||
1780
2078
  pathInfo.schemaPath.includes('functionCallReturnValue');
1781
- if (isValidSourceCandidate) {
2079
+ // Check if path STARTS with a spread pattern like [...var]
2080
+ // This handles cases like [...files][][0] or [...files].sort(...).functionCallReturnValue[][0]
2081
+ // where the spread source variable needs to be resolved to a signature path.
2082
+ // We do this REGARDLESS of isValidSourceCandidate because even paths containing
2083
+ // functionCallReturnValue may need spread resolution to trace back to the signature.
2084
+ const spreadMatch = pathInfo.schemaPath.match(/^\[\.\.\.(\w+)\]/);
2085
+ if (spreadMatch) {
2086
+ const spreadVar = spreadMatch[1];
2087
+ const spreadPattern = spreadMatch[0]; // The full [...var] match
2088
+ const scopeNode = this.scopeNodes[pathInfo.scopeNodeName];
2089
+ if (scopeNode?.equivalencies) {
2090
+ // Follow the equivalency chain to find a signature path
2091
+ // e.g., files (cyScope1) → files (root) → signature[0].files
2092
+ const resolveToSignature = (varName, currentScopeName, visited) => {
2093
+ const visitKey = `${currentScopeName}::${varName}`;
2094
+ if (visited.has(visitKey))
2095
+ return null;
2096
+ visited.add(visitKey);
2097
+ const currentScope = this.scopeNodes[currentScopeName];
2098
+ if (!currentScope?.equivalencies)
2099
+ return null;
2100
+ const varEquivs = currentScope.equivalencies[varName];
2101
+ if (!varEquivs)
2102
+ return null;
2103
+ // First check if any equivalency directly points to a signature path
2104
+ const signatureEquiv = varEquivs.find((eq) => eq.schemaPath.startsWith('signature['));
2105
+ if (signatureEquiv) {
2106
+ return signatureEquiv;
2107
+ }
2108
+ // Otherwise, follow the chain to other scopes
2109
+ for (const equiv of varEquivs) {
2110
+ // If the equivalency points to the same variable in a different scope,
2111
+ // follow the chain
2112
+ if (equiv.schemaPath === varName &&
2113
+ equiv.scopeNodeName !== currentScopeName) {
2114
+ const result = resolveToSignature(varName, equiv.scopeNodeName, visited);
2115
+ if (result)
2116
+ return result;
2117
+ }
2118
+ }
2119
+ return null;
2120
+ };
2121
+ const signatureEquiv = resolveToSignature(spreadVar, pathInfo.scopeNodeName, new Set());
2122
+ if (signatureEquiv) {
2123
+ // Replace ONLY the [...var] part with the resolved signature path
2124
+ // This preserves any suffix like .sort(...).functionCallReturnValue[][0]
2125
+ const resolvedPath = pathInfo.schemaPath.replace(spreadPattern, signatureEquiv.schemaPath);
2126
+ // Add the resolved path as a source candidate
2127
+ if (!databaseEntry.sourceCandidates.some((sc) => sc.schemaPath === resolvedPath &&
2128
+ sc.scopeNodeName === pathInfo.scopeNodeName)) {
2129
+ databaseEntry.sourceCandidates.push({
2130
+ scopeNodeName: pathInfo.scopeNodeName,
2131
+ schemaPath: resolvedPath,
2132
+ });
2133
+ }
2134
+ isValidSourceCandidate = true;
2135
+ }
2136
+ }
2137
+ }
2138
+ if (isValidSourceCandidate &&
2139
+ !databaseEntry.sourceCandidates.some((sc) => sc.schemaPath === pathInfo.schemaPath &&
2140
+ sc.scopeNodeName === pathInfo.scopeNodeName)) {
1782
2141
  databaseEntry.sourceCandidates.push(pathInfo);
1783
2142
  }
1784
2143
  }
@@ -1924,6 +2283,13 @@ export class ScopeDataStructure {
1924
2283
  delete scopeNode.schema[key];
1925
2284
  }
1926
2285
  }
2286
+ // Ensure parameter-to-signature equivalencies are fully propagated.
2287
+ // When a parameter variable (e.g., `node`) is equivalenced to `signature[N]`,
2288
+ // all sub-paths of that variable should also appear under `signature[N]`.
2289
+ // This handles cases where the sub-path was added to the schema via a propagation
2290
+ // chain that already included the variable↔signature equivalency, causing the
2291
+ // cycle detection to prevent the reverse mapping.
2292
+ this.propagateParameterToSignaturePaths(scopeNode);
1927
2293
  fillInSchemaGapsAndUnknowns(scopeNode, fillInUnknowns);
1928
2294
  if (final) {
1929
2295
  for (const manager of this.equivalencyManagers) {
@@ -1935,6 +2301,85 @@ export class ScopeDataStructure {
1935
2301
  ensureSchemaConsistency(scopeNode.schema);
1936
2302
  }
1937
2303
  }
2304
+ /**
2305
+ * For each equivalency where a simple variable maps to signature[N],
2306
+ * ensure all sub-paths of that variable are reflected under signature[N].
2307
+ */
2308
+ propagateParameterToSignaturePaths(scopeNode) {
2309
+ // Helper: check if a type is a concrete scalar that cannot have sub-properties.
2310
+ const SCALAR_TYPES = new Set([
2311
+ 'string',
2312
+ 'number',
2313
+ 'boolean',
2314
+ 'bigint',
2315
+ 'symbol',
2316
+ 'void',
2317
+ 'never',
2318
+ ]);
2319
+ const isDefinitelyScalar = (type) => {
2320
+ const parts = type.split('|').map((s) => s.trim());
2321
+ const base = parts.filter((s) => s !== 'undefined' && s !== 'null');
2322
+ return base.length > 0 && base.every((b) => SCALAR_TYPES.has(b));
2323
+ };
2324
+ // Find variable → signature[N] equivalencies
2325
+ for (const [varName, equivalencies] of Object.entries(scopeNode.equivalencies)) {
2326
+ // Only process simple variable names (no dots, brackets, or parens)
2327
+ if (varName.includes('.') ||
2328
+ varName.includes('[') ||
2329
+ varName.includes('(')) {
2330
+ continue;
2331
+ }
2332
+ for (const equiv of equivalencies) {
2333
+ if (equiv.scopeNodeName === scopeNode.name &&
2334
+ equiv.schemaPath.startsWith('signature[')) {
2335
+ const signaturePath = equiv.schemaPath;
2336
+ const varPrefix = varName + '.';
2337
+ const varBracketPrefix = varName + '[';
2338
+ // Find all schema keys starting with the variable
2339
+ for (const key in scopeNode.schema) {
2340
+ if (key.startsWith(varPrefix) || key.startsWith(varBracketPrefix)) {
2341
+ const suffix = key.slice(varName.length);
2342
+ const sigKey = signaturePath + suffix;
2343
+ // Only add if the signature path doesn't already exist
2344
+ if (!scopeNode.schema[sigKey]) {
2345
+ // Check if this path represents variable conflation:
2346
+ // When a standalone variable (e.g., showWorkoutForm from useState)
2347
+ // appears as a sub-property of a scalar-typed ancestor (e.g.,
2348
+ // activity_type = "string"), it's from scope conflation, not real
2349
+ // property access. Block these while allowing legitimate built-in
2350
+ // accesses like string.length or string.slice.
2351
+ let isConflatedPath = false;
2352
+ let checkPos = signaturePath.length;
2353
+ while (true) {
2354
+ checkPos = sigKey.indexOf('.', checkPos + 1);
2355
+ if (checkPos === -1)
2356
+ break;
2357
+ const ancestorPath = sigKey.substring(0, checkPos);
2358
+ const ancestorType = scopeNode.schema[ancestorPath];
2359
+ if (ancestorType && isDefinitelyScalar(ancestorType)) {
2360
+ // Ancestor is scalar — check if the immediate sub-property
2361
+ // is also a standalone variable (indicating conflation)
2362
+ const afterDot = sigKey.substring(checkPos + 1);
2363
+ const nextSep = afterDot.search(/[.\[]/);
2364
+ const subPropName = nextSep === -1
2365
+ ? afterDot
2366
+ : afterDot.substring(0, nextSep);
2367
+ if (scopeNode.schema[subPropName] !== undefined) {
2368
+ isConflatedPath = true;
2369
+ break;
2370
+ }
2371
+ }
2372
+ }
2373
+ if (!isConflatedPath) {
2374
+ scopeNode.schema[sigKey] = scopeNode.schema[key];
2375
+ }
2376
+ }
2377
+ }
2378
+ }
2379
+ }
2380
+ }
2381
+ }
2382
+ }
1938
2383
  filterAndConvertSchema({ filterPath, newPath, schema, }) {
1939
2384
  const filterPathParts = this.splitPath(filterPath);
1940
2385
  return Object.keys(schema).reduce((acc, key) => {
@@ -1994,6 +2439,10 @@ export class ScopeDataStructure {
1994
2439
  path,
1995
2440
  ...this.splitPath(key).slice(equivalentValueSchemaPathParts.length),
1996
2441
  ]);
2442
+ // PERF: Skip keys with repeated function-call signature patterns
2443
+ // to prevent recursive type expansion (e.g., string.localeCompare returns string)
2444
+ if (this.hasExcessivePatternRepetition(newKey))
2445
+ continue;
1997
2446
  resolvedSchema[newKey] = value;
1998
2447
  }
1999
2448
  }
@@ -2015,6 +2464,9 @@ export class ScopeDataStructure {
2015
2464
  if (!subSchema)
2016
2465
  continue;
2017
2466
  for (const resolvedKey in subSchema) {
2467
+ // PERF: Skip keys with repeated function-call signature patterns
2468
+ if (this.hasExcessivePatternRepetition(resolvedKey))
2469
+ continue;
2018
2470
  if (!resolvedSchema[resolvedKey] ||
2019
2471
  subSchema[resolvedKey] === 'unknown') {
2020
2472
  resolvedSchema[resolvedKey] = subSchema[resolvedKey];
@@ -2117,7 +2569,12 @@ export class ScopeDataStructure {
2117
2569
  return acc;
2118
2570
  }, {});
2119
2571
  }
2572
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
2573
+ // during this "getter" method. See comment in getFunctionSignature.
2574
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
2575
+ this.onlyEquivalencies = true;
2120
2576
  this.validateSchema(scopeNode, true, fillInUnknowns);
2577
+ this.onlyEquivalencies = wasOnlyEquivalencies;
2121
2578
  const { schema } = scopeNode;
2122
2579
  // For root scope, merge in external function call schemas
2123
2580
  // This ensures that imported objects used as method call targets (like logger.error())
@@ -2146,9 +2603,22 @@ export class ScopeDataStructure {
2146
2603
  }
2147
2604
  }
2148
2605
  }
2149
- return mergedSchema;
2606
+ return this.filterDuplicateKeys(mergedSchema);
2150
2607
  }
2151
- return schema;
2608
+ return this.filterDuplicateKeys(schema);
2609
+ }
2610
+ /**
2611
+ * Filter out ::cyDuplicateKey:: entries from a schema.
2612
+ * These are internal markers for tracking variable reassignments
2613
+ * and should not appear in output schemas or LLM prompts.
2614
+ */
2615
+ filterDuplicateKeys(schema) {
2616
+ return Object.entries(schema).reduce((acc, [key, value]) => {
2617
+ if (!key.includes('::cyDuplicateKey')) {
2618
+ acc[key] = value;
2619
+ }
2620
+ return acc;
2621
+ }, {});
2152
2622
  }
2153
2623
  getEquivalencies(scopeName) {
2154
2624
  const scopeNode = this.getScopeOrFunctionCallInfo(scopeName);
@@ -2170,18 +2640,204 @@ export class ScopeDataStructure {
2170
2640
  if (!scopeNode) {
2171
2641
  return {};
2172
2642
  }
2173
- const entries = this.equivalencyDatabase.filter((entry) => entry.usages.some((usage) => usage.scopeNodeName === scopeNode.name));
2174
- return entries.reduce((acc, entry) => {
2643
+ // Collect all descendant scope names (including the scope itself)
2644
+ // This ensures we include external calls from nested scopes like cyScope2
2645
+ const getAllDescendantScopeNames = (node) => {
2646
+ const names = new Set([node.name]);
2647
+ for (const child of node.children) {
2648
+ for (const name of getAllDescendantScopeNames(child)) {
2649
+ names.add(name);
2650
+ }
2651
+ }
2652
+ return names;
2653
+ };
2654
+ const treeNode = this.scopeTreeManager.findNode(scopeNode.name);
2655
+ const descendantScopeNames = treeNode
2656
+ ? getAllDescendantScopeNames(treeNode)
2657
+ : new Set([scopeNode.name]);
2658
+ // Get all external function calls made from this scope or any descendant scope
2659
+ // This allows us to include prop equivalencies from JSX components
2660
+ // that were rendered in nested scopes (e.g., FileTableRow called from cyScope2)
2661
+ const externalCallsFromScope = this.externalFunctionCalls.filter((efc) => descendantScopeNames.has(efc.callScope));
2662
+ const externalCallNames = new Set(externalCallsFromScope.map((efc) => efc.name));
2663
+ // Helper to check if a usage belongs to this scope (directly, via descendant, or via external call)
2664
+ const usageMatchesScope = (usage) => descendantScopeNames.has(usage.scopeNodeName) ||
2665
+ externalCallNames.has(usage.scopeNodeName);
2666
+ const entries = this.equivalencyDatabase.filter((entry) => entry.usages.some(usageMatchesScope));
2667
+ // Helper to resolve a source candidate through equivalency chains to find signature paths
2668
+ const resolveToSignature = (source, visited) => {
2669
+ const visitKey = `${source.scopeNodeName}::${source.schemaPath}`;
2670
+ if (visited.has(visitKey))
2671
+ return [];
2672
+ visited.add(visitKey);
2673
+ // If already a signature path, return as-is
2674
+ if (source.schemaPath.startsWith('signature[')) {
2675
+ return [source];
2676
+ }
2677
+ const currentScope = this.scopeNodes[source.scopeNodeName];
2678
+ if (!currentScope?.equivalencies)
2679
+ return [source];
2680
+ // Check for direct equivalencies FIRST (full path match)
2681
+ // This ensures paths like "useMemo(...).functionCallReturnValue" follow to "cyScope1::returnValue"
2682
+ // before prefix matching tries "useMemo(...)" which goes to the useMemo scope
2683
+ const directEquivs = currentScope.equivalencies[source.schemaPath];
2684
+ if (directEquivs?.length > 0) {
2685
+ const results = [];
2686
+ for (const equiv of directEquivs) {
2687
+ const resolved = resolveToSignature({
2688
+ scopeNodeName: equiv.scopeNodeName,
2689
+ schemaPath: equiv.schemaPath,
2690
+ }, visited);
2691
+ results.push(...resolved);
2692
+ }
2693
+ if (results.length > 0)
2694
+ return results;
2695
+ }
2696
+ // Handle spread patterns like [...items].sort().functionCallReturnValue
2697
+ // Extract the spread variable and resolve it through the equivalency chain
2698
+ const spreadMatch = source.schemaPath.match(/^\[\.\.\.(\w+)\]/);
2699
+ if (spreadMatch) {
2700
+ const spreadVar = spreadMatch[1];
2701
+ const spreadPattern = spreadMatch[0];
2702
+ const varEquivs = currentScope.equivalencies[spreadVar];
2703
+ if (varEquivs?.length > 0) {
2704
+ const results = [];
2705
+ for (const equiv of varEquivs) {
2706
+ // Follow the variable equivalency and then resolve from there
2707
+ const resolvedVar = resolveToSignature({
2708
+ scopeNodeName: equiv.scopeNodeName,
2709
+ schemaPath: equiv.schemaPath,
2710
+ }, visited);
2711
+ // For each resolved variable path, create the full path with array element suffix
2712
+ for (const rv of resolvedVar) {
2713
+ if (rv.schemaPath.startsWith('signature[')) {
2714
+ // Get the suffix after the spread pattern
2715
+ let suffix = source.schemaPath.slice(spreadPattern.length);
2716
+ // Clean the suffix: strip array method chains like .sort(...).functionCallReturnValue[]
2717
+ // These don't change the data identity, just transform it.
2718
+ // Keep only the final element access parts like [0], [1], etc.
2719
+ // Pattern: strip everything from a method call up through functionCallReturnValue[]
2720
+ suffix = suffix.replace(/\.\w+\([^)]*\)\.functionCallReturnValue\[\]/g, '');
2721
+ // Also handle simpler case without nested parens
2722
+ suffix = suffix.replace(/\.sort\(\w*\(\)\)\.functionCallReturnValue\[\]/g, '');
2723
+ // Add [] to indicate array element access from the spread
2724
+ const resolvedPath = rv.schemaPath + '[]' + suffix;
2725
+ results.push({
2726
+ scopeNodeName: rv.scopeNodeName,
2727
+ schemaPath: resolvedPath,
2728
+ });
2729
+ }
2730
+ }
2731
+ }
2732
+ if (results.length > 0)
2733
+ return results;
2734
+ }
2735
+ }
2736
+ // Try to find prefix equivalencies that can resolve this path
2737
+ // For path like "cyScope3().signature[0][0]", check "cyScope3().signature[0]", etc.
2738
+ const pathParts = this.splitPath(source.schemaPath);
2739
+ for (let i = pathParts.length - 1; i > 0; i--) {
2740
+ const prefix = this.joinPathParts(pathParts.slice(0, i));
2741
+ const suffix = this.joinPathParts(pathParts.slice(i));
2742
+ const prefixEquivs = currentScope.equivalencies[prefix];
2743
+ if (prefixEquivs?.length > 0) {
2744
+ const results = [];
2745
+ for (const equiv of prefixEquivs) {
2746
+ const newPath = this.joinPathParts([equiv.schemaPath, suffix]);
2747
+ const resolved = resolveToSignature({ scopeNodeName: equiv.scopeNodeName, schemaPath: newPath }, visited);
2748
+ results.push(...resolved);
2749
+ }
2750
+ if (results.length > 0)
2751
+ return results;
2752
+ }
2753
+ }
2754
+ return [source];
2755
+ };
2756
+ const acc = entries.reduce((result, entry) => {
2175
2757
  var _a;
2176
2758
  if (entry.sourceCandidates.length === 0)
2177
- return acc;
2178
- const usages = entry.usages.filter((u) => u.scopeNodeName === scopeNode.name);
2759
+ return result;
2760
+ const usages = entry.usages.filter(usageMatchesScope);
2179
2761
  for (const usage of usages) {
2180
- acc[_a = usage.schemaPath] || (acc[_a] = []);
2181
- acc[usage.schemaPath].push(...entry.sourceCandidates);
2762
+ result[_a = usage.schemaPath] || (result[_a] = []);
2763
+ // Resolve each source candidate through the equivalency chain
2764
+ for (const source of entry.sourceCandidates) {
2765
+ const resolvedSources = resolveToSignature(source, new Set());
2766
+ result[usage.schemaPath].push(...resolvedSources);
2767
+ }
2182
2768
  }
2183
- return acc;
2769
+ return result;
2184
2770
  }, {});
2771
+ // Post-processing: enrich useState-backed sources with co-located external
2772
+ // function calls. When a useState value resolves to a setter variable that
2773
+ // lives in the same scope as a fetch/API call, that fetch is a data source.
2774
+ this.enrichUseStateSourcesWithCoLocatedCalls(acc);
2775
+ return acc;
2776
+ }
2777
+ /**
2778
+ * For each source that ends at a useState path, check if the setter was called
2779
+ * from a scope that also contains external function calls (like fetch).
2780
+ * If so, add those external calls as additional source candidates.
2781
+ */
2782
+ enrichUseStateSourcesWithCoLocatedCalls(acc) {
2783
+ const rootScopeName = this.scopeTreeManager.getRootName();
2784
+ const rootScope = this.scopeNodes[rootScopeName];
2785
+ if (!rootScope)
2786
+ return;
2787
+ // Collect all descendants for each scope node
2788
+ const getAllDescendants = (node) => {
2789
+ const names = new Set([node.name]);
2790
+ for (const child of node.children) {
2791
+ for (const name of getAllDescendants(child)) {
2792
+ names.add(name);
2793
+ }
2794
+ }
2795
+ return names;
2796
+ };
2797
+ for (const [usagePath, sources] of Object.entries(acc)) {
2798
+ const additionalSources = [];
2799
+ for (const source of sources) {
2800
+ // Check if this source is a useState-related terminal path
2801
+ // (e.g., useState(X).functionCallReturnValue[1] or useState(X).signature[0])
2802
+ if (!source.schemaPath.match(/^useState\([^)]*\)\./))
2803
+ continue;
2804
+ // Find the useState call from the source path
2805
+ const useStateCallMatch = source.schemaPath.match(/^(useState\([^)]*\))\./);
2806
+ if (!useStateCallMatch)
2807
+ continue;
2808
+ const useStateCall = useStateCallMatch[1];
2809
+ // Look in the root scope for the useState value equivalency
2810
+ // which tells us where the setter was called from
2811
+ const valuePath = `${useStateCall}.functionCallReturnValue[0]`;
2812
+ const valueEquivs = rootScope.equivalencies[valuePath];
2813
+ if (!valueEquivs)
2814
+ continue;
2815
+ for (const equiv of valueEquivs) {
2816
+ // Find the scope where the setter was called
2817
+ const setterScopeName = equiv.scopeNodeName;
2818
+ const setterScopeTree = this.scopeTreeManager.findNode(setterScopeName);
2819
+ if (!setterScopeTree)
2820
+ continue;
2821
+ // Get all descendant scope names from the setter scope
2822
+ const relatedScopes = getAllDescendants(setterScopeTree);
2823
+ // Find external function calls in those scopes whose return values
2824
+ // are actually consumed (assigned to a variable). This excludes
2825
+ // fire-and-forget calls like analytics.track() or console.log().
2826
+ const coLocatedCalls = this.externalFunctionCalls.filter((efc) => relatedScopes.has(efc.callScope) &&
2827
+ efc.receivingVariableNames &&
2828
+ efc.receivingVariableNames.length > 0);
2829
+ for (const call of coLocatedCalls) {
2830
+ additionalSources.push({
2831
+ scopeNodeName: call.callScope,
2832
+ schemaPath: `${call.callSignature}.functionCallReturnValue`,
2833
+ });
2834
+ }
2835
+ }
2836
+ }
2837
+ if (additionalSources.length > 0) {
2838
+ acc[usagePath].push(...additionalSources);
2839
+ }
2840
+ }
2185
2841
  }
2186
2842
  getUsageEquivalencies(functionName) {
2187
2843
  const scopeNode = this.getScopeOrFunctionCallInfo(functionName);
@@ -2214,11 +2870,12 @@ export class ScopeDataStructure {
2214
2870
  return acc;
2215
2871
  }, {});
2216
2872
  const equivalencies = this.getEquivalencies(functionName);
2873
+ const scopeName = functionName ?? this.scopeTreeManager.getRootName();
2217
2874
  for (const equivalenceKey in equivalencies ?? {}) {
2218
2875
  for (const equivalenceValue of equivalencies[equivalenceKey]) {
2219
2876
  const schemaPath = equivalenceValue.schemaPath;
2220
2877
  if (schemaPath.startsWith('signature[') &&
2221
- equivalenceValue.scopeNodeName === functionName &&
2878
+ equivalenceValue.scopeNodeName === scopeName &&
2222
2879
  !signatureInSchema[schemaPath]) {
2223
2880
  signatureInSchema[schemaPath] = 'unknown';
2224
2881
  }
@@ -2226,9 +2883,180 @@ export class ScopeDataStructure {
2226
2883
  }
2227
2884
  const tempScopeNode = this.createTempScopeNode(functionName ?? this.scopeTreeManager.getRootName(), signatureInSchema, equivalencies);
2228
2885
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
2229
- return tempScopeNode.schema;
2886
+ // After validateSchema has filled in types, propagate nested paths from
2887
+ // variables to their signature equivalents.
2888
+ // e.g., workouts[].activity_type -> signature[0].workouts[].activity_type
2889
+ //
2890
+ // Build a map of variable names that are equivalent to signature paths
2891
+ // e.g., { 'workouts': 'signature[0].workouts' }
2892
+ const variableToSignatureMap = {};
2893
+ for (const equivalenceKey in equivalencies ?? {}) {
2894
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
2895
+ const schemaPath = equivalenceValue.schemaPath;
2896
+ // Track which variables map to signature paths
2897
+ // equivalenceKey is the variable name (e.g., 'workouts')
2898
+ // schemaPath is where it comes from (e.g., 'signature[0].workouts')
2899
+ if (schemaPath.startsWith('signature[') &&
2900
+ equivalenceValue.scopeNodeName === scopeName) {
2901
+ variableToSignatureMap[equivalenceKey] = schemaPath;
2902
+ }
2903
+ }
2904
+ }
2905
+ // Enrich schema with deeply nested paths from internal function call scopes.
2906
+ // When a function call like traverse(tree) exists, and traverse's scope has
2907
+ // signature[0].children[path][entityName] (from propagateParameterToSignaturePaths),
2908
+ // we need to map those paths back to the argument variable (tree) in this scope.
2909
+ // This handles cases where cycle detection prevented the equivalency chain from
2910
+ // propagating deep paths during Phase 2 batch queue processing.
2911
+ for (const equivalenceKey in equivalencies ?? {}) {
2912
+ // Look for keys matching function call pattern: funcName(...).signature[N]
2913
+ const funcCallMatch = equivalenceKey.match(/^([^(]+)\(.*?\)\.(signature\[\d+\])$/);
2914
+ if (!funcCallMatch)
2915
+ continue;
2916
+ const calledFunctionName = funcCallMatch[1];
2917
+ const signatureParam = funcCallMatch[2]; // e.g., "signature[0]"
2918
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
2919
+ if (equivalenceValue.scopeNodeName !== scopeName)
2920
+ continue;
2921
+ const targetVariable = equivalenceValue.schemaPath;
2922
+ // Get the called function's schema (includes propagated parameter paths)
2923
+ const childSchema = this.getSchema({
2924
+ scopeName: calledFunctionName,
2925
+ });
2926
+ if (!childSchema)
2927
+ continue;
2928
+ // Map child function's signature paths to parent variable paths
2929
+ const sigPrefix = signatureParam + '.';
2930
+ const sigBracketPrefix = signatureParam + '[';
2931
+ for (const childKey in childSchema) {
2932
+ let suffix = null;
2933
+ if (childKey.startsWith(sigPrefix)) {
2934
+ suffix = childKey.slice(signatureParam.length);
2935
+ }
2936
+ else if (childKey.startsWith(sigBracketPrefix)) {
2937
+ suffix = childKey.slice(signatureParam.length);
2938
+ }
2939
+ if (suffix !== null) {
2940
+ const parentKey = targetVariable + suffix;
2941
+ if (!schema[parentKey]) {
2942
+ schema[parentKey] = childSchema[childKey];
2943
+ }
2944
+ }
2945
+ }
2946
+ }
2947
+ }
2948
+ // Helper: check if a type is a concrete scalar that cannot have sub-properties.
2949
+ // e.g., "string", "number | undefined", "boolean | null" are scalar.
2950
+ // "object", "array", "function", "unknown", "Workout", etc. are NOT scalar.
2951
+ const SCALAR_TYPES = new Set([
2952
+ 'string',
2953
+ 'number',
2954
+ 'boolean',
2955
+ 'bigint',
2956
+ 'symbol',
2957
+ 'void',
2958
+ 'never',
2959
+ ]);
2960
+ const isDefinitelyScalarType = (type) => {
2961
+ const parts = type.split('|').map((s) => s.trim());
2962
+ const base = parts.filter((s) => s !== 'undefined' && s !== 'null');
2963
+ return base.length > 0 && base.every((b) => SCALAR_TYPES.has(b));
2964
+ };
2965
+ // Propagate nested paths from variables to their signature equivalents
2966
+ // e.g., if workouts = signature[0].workouts, then workouts[].title becomes
2967
+ // signature[0].workouts[].title
2968
+ for (const schemaKey in schema) {
2969
+ // Skip keys that already start with signature[
2970
+ if (schemaKey.startsWith('signature['))
2971
+ continue;
2972
+ // Check if this key starts with a variable that maps to a signature path
2973
+ for (const [variableName, signaturePath] of Object.entries(variableToSignatureMap)) {
2974
+ // Check if schemaKey starts with variableName followed by a property accessor
2975
+ // e.g., 'workouts[]' starts with 'workouts'
2976
+ if (schemaKey === variableName ||
2977
+ schemaKey.startsWith(variableName + '.') ||
2978
+ schemaKey.startsWith(variableName + '[')) {
2979
+ // Transform the path: replace the variable prefix with the signature path
2980
+ const suffix = schemaKey.slice(variableName.length);
2981
+ const signatureKey = signaturePath + suffix;
2982
+ // Add to schema if not already present
2983
+ if (!tempScopeNode.schema[signatureKey]) {
2984
+ // Check if this path represents variable conflation:
2985
+ // When a standalone variable (e.g., showWorkoutForm from useState)
2986
+ // appears as a sub-property of a scalar-typed ancestor (e.g.,
2987
+ // activity_type = "string"), it's from scope conflation, not real
2988
+ // property access. Block these while allowing legitimate built-in
2989
+ // accesses like string.length or string.slice.
2990
+ let isConflatedPath = false;
2991
+ let checkPos = signaturePath.length;
2992
+ while (true) {
2993
+ checkPos = signatureKey.indexOf('.', checkPos + 1);
2994
+ if (checkPos === -1)
2995
+ break;
2996
+ const ancestorPath = signatureKey.substring(0, checkPos);
2997
+ const ancestorType = tempScopeNode.schema[ancestorPath];
2998
+ if (ancestorType && isDefinitelyScalarType(ancestorType)) {
2999
+ // Ancestor is scalar — check if the immediate sub-property
3000
+ // is also a standalone variable (indicating conflation)
3001
+ const afterDot = signatureKey.substring(checkPos + 1);
3002
+ const nextSep = afterDot.search(/[.\[]/);
3003
+ const subPropName = nextSep === -1 ? afterDot : afterDot.substring(0, nextSep);
3004
+ if (schema[subPropName] !== undefined) {
3005
+ isConflatedPath = true;
3006
+ break;
3007
+ }
3008
+ }
3009
+ }
3010
+ if (!isConflatedPath) {
3011
+ tempScopeNode.schema[signatureKey] = schema[schemaKey];
3012
+ }
3013
+ }
3014
+ }
3015
+ }
3016
+ }
3017
+ // Post-process: filter out conflated signature paths.
3018
+ // During phase 2 scope analysis, useState(false) conflation can create
3019
+ // bad paths like signature[0].mockWorkouts[].activity_type.showWorkoutForm
3020
+ // directly in scopeNode.schema. These flow through signatureInSchema into
3021
+ // tempScopeNode.schema without any guard. Filter them out here by checking:
3022
+ // 1. An ancestor in the path has a concrete scalar type (string, number, boolean, etc.)
3023
+ // 2. The immediate sub-property of that scalar ancestor is also a standalone
3024
+ // variable in the schema (indicating conflation, not a real property access)
3025
+ for (const key of Object.keys(tempScopeNode.schema)) {
3026
+ if (!key.startsWith('signature['))
3027
+ continue;
3028
+ // Walk through the path looking for scalar-typed ancestors
3029
+ let pos = 0;
3030
+ while (true) {
3031
+ pos = key.indexOf('.', pos + 1);
3032
+ if (pos === -1)
3033
+ break;
3034
+ const ancestorPath = key.substring(0, pos);
3035
+ const ancestorType = tempScopeNode.schema[ancestorPath];
3036
+ if (ancestorType && isDefinitelyScalarType(ancestorType)) {
3037
+ // Found a scalar ancestor — check if the sub-property name
3038
+ // is a standalone variable in the getSchema() result
3039
+ const afterDot = key.substring(pos + 1);
3040
+ const nextSep = afterDot.search(/[.\[]/);
3041
+ const subPropName = nextSep === -1 ? afterDot : afterDot.substring(0, nextSep);
3042
+ if (schema[subPropName] !== undefined) {
3043
+ delete tempScopeNode.schema[key];
3044
+ break;
3045
+ }
3046
+ }
3047
+ }
3048
+ }
3049
+ return this.filterDuplicateKeys(tempScopeNode.schema);
2230
3050
  }
2231
3051
  getReturnValue({ functionName, fillInUnknowns, }) {
3052
+ // Trigger finalization on all managers to apply any pending updates
3053
+ // (e.g., ref type propagation to external function call schemas)
3054
+ const rootScope = this.scopeNodes[this.scopeTreeManager.getRootName()];
3055
+ if (rootScope) {
3056
+ for (const manager of this.equivalencyManagers) {
3057
+ manager.finalize(rootScope, this);
3058
+ }
3059
+ }
2232
3060
  const scopeName = functionName ?? this.scopeTreeManager.getRootName();
2233
3061
  const scopeNode = this.scopeNodes[scopeName];
2234
3062
  let schema = {};
@@ -2239,7 +3067,8 @@ export class ScopeDataStructure {
2239
3067
  });
2240
3068
  }
2241
3069
  else {
2242
- for (const externalFunctionCall of this.externalFunctionCalls) {
3070
+ // Use getExternalFunctionCalls() which cleans cyScope from schemas
3071
+ for (const externalFunctionCall of this.getExternalFunctionCalls()) {
2243
3072
  const functionNameParts = this.splitPath(functionName).map((p) => this.functionOrScopeName(p));
2244
3073
  const nameParts = this.splitPath(externalFunctionCall.name).map((p) => this.functionOrScopeName(p));
2245
3074
  if (functionNameParts.every((part, index) => part === nameParts[index])) {
@@ -2260,14 +3089,27 @@ export class ScopeDataStructure {
2260
3089
  // Include function paths even if their return value wasn't captured
2261
3090
  // This ensures methods like onAuthStateChange are included in the schema
2262
3091
  // But exclude signature entries (they should only be included via functionCallReturnValue paths)
2263
- (schema[key] === 'function' && key.indexOf('signature[') === -1))
3092
+ // Also exclude bare function call signatures - paths that are JUST a call like
3093
+ // "useCustomSizes(projectSlug)" should not be included as return values.
3094
+ // These represent "the function exists" not actual return data, and including
3095
+ // them causes nested path bugs in dependencySchemas.
3096
+ (schema[key] === 'function' &&
3097
+ key.indexOf('signature[') === -1 &&
3098
+ // Exclude bare call signatures: function calls with no dots OUTSIDE parentheses
3099
+ // e.g., "useCustomSizes(projectSlug)" is bare (exclude)
3100
+ // e.g., "loadProject({nested.property})" is bare - dots are inside args (exclude)
3101
+ // e.g., "getSupabase().auth.method()" has dots outside - method chain (include)
3102
+ !this.isBareCallSignature(key)))
2264
3103
  .reduce((acc, key) => {
2265
3104
  acc[key] = schema[key];
2266
3105
  const keyParts = this.splitPath(key);
2267
3106
  for (const path in schema) {
2268
3107
  const pathParts = this.splitPath(path);
2269
3108
  if (pathParts.every((p, i) => keyParts[i] === p)) {
2270
- acc[path] = schema[path];
3109
+ // Also exclude bare call signatures from prefix paths
3110
+ if (!this.isBareCallSignature(path)) {
3111
+ acc[path] = schema[path];
3112
+ }
2271
3113
  }
2272
3114
  }
2273
3115
  return acc;
@@ -2275,12 +3117,68 @@ export class ScopeDataStructure {
2275
3117
  // Replace cyScope placeholders with actual callback text
2276
3118
  const resolvedSchema = this.replaceCyScopePlaceholders(returnValueSchema);
2277
3119
  const tempScopeNode = this.createTempScopeNode(scopeName, resolvedSchema);
3120
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
3121
+ // during this "getter" method. See comment in getFunctionSignature.
3122
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
3123
+ this.onlyEquivalencies = true;
2278
3124
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
2279
- return tempScopeNode.schema;
3125
+ this.onlyEquivalencies = wasOnlyEquivalencies;
3126
+ // Remove bare call signatures from the return value schema.
3127
+ // fillInSchemaGapsAndUnknowns may add parent paths like "useCustomSizes(projectSlug)"
3128
+ // when it sees "useCustomSizes(projectSlug).functionCallReturnValue". These bare
3129
+ // call signatures represent "the function exists" not actual return data, and
3130
+ // including them causes nested path bugs in dependencySchemas.
3131
+ const resultSchema = tempScopeNode.schema;
3132
+ for (const key of Object.keys(resultSchema)) {
3133
+ if (this.isBareCallSignature(key)) {
3134
+ delete resultSchema[key];
3135
+ }
3136
+ }
3137
+ return resultSchema;
3138
+ }
3139
+ /**
3140
+ * Checks if a schema key is a "bare call signature" - a function call with no
3141
+ * method chain before it and no path segments after it.
3142
+ *
3143
+ * A bare call signature represents "this function exists" rather than actual
3144
+ * return data, and including them causes nested path bugs in dependencySchemas.
3145
+ *
3146
+ * Examples:
3147
+ * - "useCustomSizes(projectSlug)" -> bare (true)
3148
+ * - "loadProject({nested.property})" -> bare (dots are inside args, true)
3149
+ * - "getSupabase().auth.method()" -> not bare (has dots outside parens, false)
3150
+ * - "useProject().functionCallReturnValue" -> not bare (has path after, false)
3151
+ */
3152
+ isBareCallSignature(key) {
3153
+ // Must end with ) and contain ( to be a call
3154
+ if (!key.endsWith(')') || key.indexOf('(') === -1) {
3155
+ return false;
3156
+ }
3157
+ // Check if there are any dots OUTSIDE of parentheses
3158
+ // Strip out content inside balanced parentheses, then check for dots
3159
+ let depth = 0;
3160
+ let hasDotsOutsideParens = false;
3161
+ for (let i = 0; i < key.length; i++) {
3162
+ const char = key[i];
3163
+ if (char === '(') {
3164
+ depth++;
3165
+ }
3166
+ else if (char === ')') {
3167
+ depth--;
3168
+ }
3169
+ else if (char === '.' && depth === 0) {
3170
+ hasDotsOutsideParens = true;
3171
+ break;
3172
+ }
3173
+ }
3174
+ // It's a bare call signature if there are no dots outside parentheses
3175
+ return !hasDotsOutsideParens;
2280
3176
  }
2281
3177
  /**
2282
3178
  * Replaces cyScope placeholder references (e.g., cyScope10()) in schema keys
2283
3179
  * with the actual callback function text from the corresponding scope node.
3180
+ * If the scope text can't be found, uses a generic fallback to avoid leaking
3181
+ * internal cyScope names into stored data.
2284
3182
  */
2285
3183
  replaceCyScopePlaceholders(schema) {
2286
3184
  const cyScopePattern = /cyScope(\d+)\(\)/g;
@@ -2292,10 +3190,10 @@ export class ScopeDataStructure {
2292
3190
  for (const match of matches) {
2293
3191
  const cyScopeName = `cyScope${match[1]}`;
2294
3192
  const scopeText = this.findCyScopeText(cyScopeName);
2295
- if (scopeText) {
2296
- // Replace cyScope10() with the actual callback text
2297
- newKey = newKey.replace(match[0], scopeText);
2298
- }
3193
+ // Always replace cyScope references - use actual text if available,
3194
+ // otherwise use a generic callback placeholder
3195
+ const replacement = scopeText || '() => {}';
3196
+ newKey = newKey.replace(match[0], replacement);
2299
3197
  }
2300
3198
  result[newKey] = value;
2301
3199
  }
@@ -2345,13 +3243,372 @@ export class ScopeDataStructure {
2345
3243
  getEquivalentSignatureVariables() {
2346
3244
  const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
2347
3245
  const equivalentSignatureVariables = {};
3246
+ // Helper to add equivalencies - accumulates into array if multiple values for same key
3247
+ // This is critical for OR expressions like `x = a || b` where x should map to both a and b
3248
+ const addEquivalency = (key, value) => {
3249
+ const existing = equivalentSignatureVariables[key];
3250
+ if (existing === undefined) {
3251
+ // First value - store as string
3252
+ equivalentSignatureVariables[key] = value;
3253
+ }
3254
+ else if (typeof existing === 'string') {
3255
+ if (existing !== value) {
3256
+ // Second different value - convert to array
3257
+ equivalentSignatureVariables[key] = [existing, value];
3258
+ }
3259
+ // Same value - no change needed
3260
+ }
3261
+ else {
3262
+ // Already an array - add if not already present
3263
+ if (!existing.includes(value)) {
3264
+ existing.push(value);
3265
+ }
3266
+ }
3267
+ };
2348
3268
  for (const [path, equivalentValues] of Object.entries(scopeNode.equivalencies)) {
2349
3269
  for (const equivalentValue of equivalentValues) {
3270
+ // Case 1: Props/signature equivalencies (existing behavior)
3271
+ // Maps local variable names to their signature paths
3272
+ // e.g., "propValue" -> "signature[0].prop"
2350
3273
  if (path.startsWith('signature[')) {
2351
- equivalentSignatureVariables[equivalentValue.schemaPath] = path;
3274
+ addEquivalency(equivalentValue.schemaPath, path);
3275
+ }
3276
+ // Case 2: Hook variable equivalencies (new behavior)
3277
+ // The equivalencies are stored as: path = variable name, schemaPath = data source
3278
+ // e.g., path = "debugFetcher", schemaPath = "useFetcher<...>().functionCallReturnValue"
3279
+ // We need to map: "debugFetcher" -> "useFetcher<...>()"
3280
+ // This enables resolving paths like "debugFetcher.state" to
3281
+ // "useFetcher<...>().state" for execution flow validation
3282
+ if (equivalentValue.schemaPath.endsWith('.functionCallReturnValue')) {
3283
+ // Extract the hook call path (everything before .functionCallReturnValue)
3284
+ let hookCallPath = equivalentValue.schemaPath.slice(0, -'.functionCallReturnValue'.length);
3285
+ // Only include if it looks like a hook call (contains parentheses)
3286
+ // and the variable name (path) is a simple identifier (no dots)
3287
+ if (hookCallPath.includes('(') && !path.includes('.')) {
3288
+ // Special case: If hookCallPath is a callback scope (cyScope pattern),
3289
+ // trace through it to find what the callback actually returns.
3290
+ // This handles useState(() => { return prop; }) patterns.
3291
+ const cyScopeMatch = hookCallPath.match(/^(cyScope\d+)\(\)$/);
3292
+ if (cyScopeMatch) {
3293
+ // Use the equivalency database to trace the callback's return value
3294
+ // to its actual source (e.g., viewModeFromUrl -> segments -> params -> useParams)
3295
+ const dbEntry = this.getEquivalenciesDatabaseEntry(scopeNode.name, // Component scope
3296
+ path);
3297
+ if (dbEntry?.sourceCandidates?.length > 0) {
3298
+ // Use the traced source instead of the callback scope
3299
+ hookCallPath = dbEntry.sourceCandidates[0].schemaPath;
3300
+ }
3301
+ }
3302
+ addEquivalency(path, hookCallPath);
3303
+ }
3304
+ }
3305
+ // Case 3: Destructured variables from local variables
3306
+ // e.g., const { scenarios } = currentEntityAnalysis;
3307
+ // This creates: path = "scenarios", schemaPath = "currentEntityAnalysis.scenarios"
3308
+ // We need to map: "scenarios" -> "currentEntityAnalysis.scenarios"
3309
+ // AND resolve transitively if currentEntityAnalysis is itself equivalent to a hook call
3310
+ if (!path.includes('.') && // path is a simple identifier
3311
+ !equivalentValue.schemaPath.startsWith('signature[') && // not a signature path
3312
+ !equivalentValue.schemaPath.endsWith('.functionCallReturnValue') // not already handled above
3313
+ ) {
3314
+ // Skip bare "returnValue" from child scopes — this is the child's return value,
3315
+ // not a meaningful data source path in the parent scope
3316
+ if (equivalentValue.schemaPath === 'returnValue' &&
3317
+ equivalentValue.scopeNodeName !==
3318
+ this.scopeTreeManager.getRootName()) {
3319
+ continue;
3320
+ }
3321
+ // Add equivalency (will accumulate if multiple values for OR expressions)
3322
+ addEquivalency(path, equivalentValue.schemaPath);
3323
+ }
3324
+ // Case 4: Child component prop mappings (Fix 22)
3325
+ // When parent renders <ChildComponent prop={value} />, we get equivalencies like:
3326
+ // path = "ChildComponent().signature[0].prop"
3327
+ // schemaPath = "value" (the variable passed as the prop)
3328
+ // We need to include these so translateChildPathToParent can work.
3329
+ // Pattern: ComponentName().signature[N] or ComponentName().signature[N].propName
3330
+ if (path.includes('().signature[') &&
3331
+ !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable, not a function call
3332
+ ) {
3333
+ addEquivalency(path, equivalentValue.schemaPath);
3334
+ }
3335
+ // Case 5: Destructured function parameters (Fix 25)
3336
+ // When a function has destructured props: function Comp({ propA, propB }: Props)
3337
+ // We get equivalencies like:
3338
+ // path = "propA" (the destructured variable name)
3339
+ // schemaPath = "signature[0].propA" (the signature path)
3340
+ // We need to map: "propA" -> "signature[0].propA"
3341
+ // This enables translateChildPathToParent to resolve child variable paths
3342
+ // to their signature paths when merging execution flows.
3343
+ if (!path.includes('.') && // path is a simple identifier (destructured prop name)
3344
+ equivalentValue.schemaPath.startsWith('signature[') // schemaPath IS a signature path
3345
+ ) {
3346
+ addEquivalency(path, equivalentValue.schemaPath);
3347
+ }
3348
+ // Case 7: Method calls on variables that result in .functionCallReturnValue (Fix 33)
3349
+ // When we have patterns like:
3350
+ // path = "segments" (simple identifier)
3351
+ // schemaPath = "splat.split('/').functionCallReturnValue"
3352
+ // This is a method call on a variable (not a hook call), but we still need to
3353
+ // track it so transitive resolution can resolve `splat` to its actual source.
3354
+ // E.g., if splat -> useParams().functionCallReturnValue['*'], then
3355
+ // segments -> useParams().functionCallReturnValue['*'].split('/').functionCallReturnValue
3356
+ if (!path.includes('.') && // path is a simple identifier
3357
+ equivalentValue.schemaPath.endsWith('.functionCallReturnValue') && // ends with function return
3358
+ equivalentValue.schemaPath.includes('.') // has property access (method call)
3359
+ ) {
3360
+ // Check if this looks like a method call on a variable (not a hook call)
3361
+ // Hook calls look like: hookName() or hookName<T>()
3362
+ // Method calls look like: variable.method() or variable.method<T>()
3363
+ const hookCallPath = equivalentValue.schemaPath.slice(0, -'.functionCallReturnValue'.length);
3364
+ // If it's a method call (contains a dot before the parenthesis), include it
3365
+ const dotBeforeParen = hookCallPath.indexOf('.');
3366
+ const parenPos = hookCallPath.indexOf('(');
3367
+ if (dotBeforeParen !== -1 && dotBeforeParen < parenPos) {
3368
+ // This is a method call like "splat.split('/')", not a hook call
3369
+ addEquivalency(path, equivalentValue.schemaPath);
3370
+ }
2352
3371
  }
2353
3372
  }
2354
3373
  }
3374
+ // Case 6: Collect JSX child prop equivalencies from child scopes (Fix 26)
3375
+ // When a parent component renders <ChildComponent prop={value} />, the JSX
3376
+ // return statement may be in a child scope (e.g., cyScope2). The equivalencies
3377
+ // like ChildComponent().signature[0].prop -> value get stored in that child scope.
3378
+ // But translateChildPathToParent needs to find them from the parent scope's context.
3379
+ // So we collect Case 4 patterns from ALL child scopes that belong to this root scope.
3380
+ const rootName = this.scopeTreeManager.getRootName();
3381
+ for (const [scopeName, childScopeNode] of Object.entries(this.scopeNodes)) {
3382
+ // Skip the root scope (already processed above)
3383
+ if (scopeName === rootName)
3384
+ continue;
3385
+ // Only include scopes that are children of the root (their tree includes root)
3386
+ if (!childScopeNode.tree?.includes(rootName))
3387
+ continue;
3388
+ // Look for Case 4 patterns in the child scope
3389
+ for (const [path, equivalentValues] of Object.entries(childScopeNode.equivalencies || {})) {
3390
+ for (const equivalentValue of equivalentValues) {
3391
+ // Case 4 pattern: ChildComponent().signature[0].propName -> parentVariable
3392
+ if (path.includes('().signature[') &&
3393
+ !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable
3394
+ ) {
3395
+ // Only add if not already present from the root scope
3396
+ // Root scope values take precedence over child scope values
3397
+ if (!(path in equivalentSignatureVariables)) {
3398
+ addEquivalency(path, equivalentValue.schemaPath);
3399
+ }
3400
+ }
3401
+ }
3402
+ }
3403
+ }
3404
+ // Transitive resolution: Resolve variable chains through multiple levels
3405
+ // E.g., analysis → currentEntityAnalysis → useLoaderData().functionCallReturnValue.currentEntityAnalysis
3406
+ // We need multiple passes because resolutions can depend on each other
3407
+ const maxIterations = 5; // Prevent infinite loops
3408
+ // Helper function to resolve a single source path using equivalencies
3409
+ const resolveSourcePath = (sourcePath, equivMap) => {
3410
+ // Extract base variable from the path
3411
+ const dotIndex = sourcePath.indexOf('.');
3412
+ const bracketIndex = sourcePath.indexOf('[');
3413
+ let baseVar;
3414
+ let rest;
3415
+ if (dotIndex === -1 && bracketIndex === -1) {
3416
+ baseVar = sourcePath;
3417
+ rest = '';
3418
+ }
3419
+ else if (dotIndex === -1) {
3420
+ baseVar = sourcePath.slice(0, bracketIndex);
3421
+ rest = sourcePath.slice(bracketIndex);
3422
+ }
3423
+ else if (bracketIndex === -1) {
3424
+ baseVar = sourcePath.slice(0, dotIndex);
3425
+ rest = sourcePath.slice(dotIndex);
3426
+ }
3427
+ else {
3428
+ const firstIndex = Math.min(dotIndex, bracketIndex);
3429
+ baseVar = sourcePath.slice(0, firstIndex);
3430
+ rest = sourcePath.slice(firstIndex);
3431
+ }
3432
+ // Look up the base variable in equivalencies
3433
+ if (baseVar in equivMap && equivMap[baseVar] !== sourcePath) {
3434
+ const baseResolved = equivMap[baseVar];
3435
+ // Skip if baseResolved is an array (handle later)
3436
+ if (Array.isArray(baseResolved))
3437
+ return null;
3438
+ // If it resolves to a signature path, build the full resolved path
3439
+ if (baseResolved.startsWith('signature[') ||
3440
+ baseResolved.includes('()')) {
3441
+ if (baseResolved.endsWith('()')) {
3442
+ return baseResolved + '.functionCallReturnValue' + rest;
3443
+ }
3444
+ return baseResolved + rest;
3445
+ }
3446
+ }
3447
+ return null;
3448
+ };
3449
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
3450
+ let changed = false;
3451
+ for (const [varName, sourcePathOrArray] of Object.entries(equivalentSignatureVariables)) {
3452
+ // Handle arrays (OR expressions) by resolving each element
3453
+ if (Array.isArray(sourcePathOrArray)) {
3454
+ const resolvedArray = [];
3455
+ let arrayChanged = false;
3456
+ for (const sourcePath of sourcePathOrArray) {
3457
+ // Try to resolve this path using transitive resolution
3458
+ const resolved = resolveSourcePath(sourcePath, equivalentSignatureVariables);
3459
+ if (resolved && resolved !== sourcePath) {
3460
+ resolvedArray.push(resolved);
3461
+ arrayChanged = true;
3462
+ }
3463
+ else {
3464
+ resolvedArray.push(sourcePath);
3465
+ }
3466
+ }
3467
+ if (arrayChanged) {
3468
+ equivalentSignatureVariables[varName] = resolvedArray;
3469
+ changed = true;
3470
+ }
3471
+ continue;
3472
+ }
3473
+ const sourcePath = sourcePathOrArray;
3474
+ // Skip if already fully resolved (contains function call syntax)
3475
+ // BUT first check for computed value patterns that need resolution (Fix 28)
3476
+ // AND method call patterns that need base variable resolution (Fix 33)
3477
+ if (sourcePath.includes('()')) {
3478
+ // Fix 28: Handle computed value patterns with dependency arrays
3479
+ // Patterns like `functionName(arg, [dep1, dep2, ...])` are NOT controllable
3480
+ // data sources. We trace through the dependencies to find controllable sources.
3481
+ const bracketStart = sourcePath.indexOf('[');
3482
+ const bracketEnd = sourcePath.lastIndexOf(']');
3483
+ if (bracketStart !== -1 && bracketEnd > bracketStart) {
3484
+ const arrayContent = sourcePath.slice(bracketStart + 1, bracketEnd);
3485
+ const items = arrayContent.split(',').map((s) => s.trim());
3486
+ // Only process if this looks like a dependency array:
3487
+ // multiple items that are all simple identifiers (not numbers or expressions)
3488
+ const isIdentifier = (s) => /^\w+$/.test(s) && !/^\d+$/.test(s);
3489
+ if (items.length > 1 && items.every(isIdentifier)) {
3490
+ // Look for a dependency that's already resolved to a controllable source
3491
+ for (const dep of items) {
3492
+ if (dep in equivalentSignatureVariables) {
3493
+ const resolvedDep = equivalentSignatureVariables[dep];
3494
+ // Use if it's a controllable path (contains hook call)
3495
+ // and is NOT another unresolved computed pattern (has comma-separated deps)
3496
+ const hasCommaInBrackets = resolvedDep.includes('[') &&
3497
+ resolvedDep.includes(',') &&
3498
+ resolvedDep.indexOf(',') > resolvedDep.indexOf('[');
3499
+ if (resolvedDep.includes('()') && !hasCommaInBrackets) {
3500
+ // Computed value is typically an element from an array
3501
+ equivalentSignatureVariables[varName] = resolvedDep + '[]';
3502
+ changed = true;
3503
+ break;
3504
+ }
3505
+ }
3506
+ }
3507
+ }
3508
+ }
3509
+ // Fix 33: Handle method call patterns on variables
3510
+ // Patterns like: "splat.split('/').functionCallReturnValue"
3511
+ // We need to resolve the base variable (splat) to its actual source
3512
+ // Check if this is a method call on a variable (dot before first parenthesis)
3513
+ const dotIndex = sourcePath.indexOf('.');
3514
+ const parenIndex = sourcePath.indexOf('(');
3515
+ if (dotIndex !== -1 &&
3516
+ dotIndex < parenIndex &&
3517
+ !sourcePath.startsWith('use') // Not a hook call like useState()
3518
+ ) {
3519
+ // Extract the base variable (before the first dot)
3520
+ const baseVar = sourcePath.slice(0, dotIndex);
3521
+ const rest = sourcePath.slice(dotIndex); // includes ".method(...).functionCallReturnValue"
3522
+ // Check if the base variable can be resolved
3523
+ if (baseVar in equivalentSignatureVariables &&
3524
+ baseVar !== varName) {
3525
+ const baseResolved = equivalentSignatureVariables[baseVar];
3526
+ // Skip if baseResolved is an array (OR expression)
3527
+ if (Array.isArray(baseResolved))
3528
+ continue;
3529
+ // Only resolve if the base resolved to something useful (contains () or .)
3530
+ if (baseResolved.includes('()') || baseResolved.includes('.')) {
3531
+ const newPath = baseResolved + rest;
3532
+ if (newPath !== equivalentSignatureVariables[varName]) {
3533
+ equivalentSignatureVariables[varName] = newPath;
3534
+ changed = true;
3535
+ }
3536
+ }
3537
+ }
3538
+ }
3539
+ // Fix 38: Handle cyScope lazy initializer return values
3540
+ // When we have viewMode -> cyScope20(), trace through to find what cyScope20 returns.
3541
+ // The lazy initializer's return value should be the controllable data source.
3542
+ // Pattern: cyScopeN() where N is a number
3543
+ const cyScopeMatch = sourcePath.match(/^(cyScope\d+)\(\)$/);
3544
+ if (cyScopeMatch) {
3545
+ const cyScopeName = cyScopeMatch[1];
3546
+ const cyScopeNode = this.scopeNodes[cyScopeName];
3547
+ if (cyScopeNode?.equivalencies) {
3548
+ // Look for returnValue equivalency in the cyScope
3549
+ const returnValueEquivs = cyScopeNode.equivalencies['returnValue'];
3550
+ if (returnValueEquivs && returnValueEquivs.length > 0) {
3551
+ // Get the first return value source
3552
+ const returnSource = returnValueEquivs[0].schemaPath;
3553
+ // If the return source is a simple variable (not a complex path),
3554
+ // resolve varName directly to that variable
3555
+ if (returnSource &&
3556
+ !returnSource.includes('(') &&
3557
+ !returnSource.includes('[')) {
3558
+ // Update varName to point to the return source
3559
+ if (equivalentSignatureVariables[varName] !== returnSource) {
3560
+ equivalentSignatureVariables[varName] = returnSource;
3561
+ changed = true;
3562
+ }
3563
+ }
3564
+ }
3565
+ }
3566
+ }
3567
+ continue;
3568
+ }
3569
+ // Check if the source path starts with a variable that's also in the map
3570
+ const dotIndex = sourcePath.indexOf('.');
3571
+ let baseVar;
3572
+ let rest;
3573
+ if (dotIndex > 0) {
3574
+ // Path has a dot: "a.b.c" -> baseVar="a", rest=".b.c"
3575
+ baseVar = sourcePath.slice(0, dotIndex);
3576
+ rest = sourcePath.slice(dotIndex); // includes the leading dot
3577
+ }
3578
+ else {
3579
+ // Path is a simple identifier: "currentEntityAnalysis" -> baseVar="currentEntityAnalysis", rest=""
3580
+ baseVar = sourcePath;
3581
+ rest = '';
3582
+ }
3583
+ if (baseVar in equivalentSignatureVariables && baseVar !== varName) {
3584
+ // Handle array case (OR expressions) - use first element
3585
+ const rawBaseResolved = equivalentSignatureVariables[baseVar];
3586
+ const baseResolved = Array.isArray(rawBaseResolved)
3587
+ ? rawBaseResolved[0]
3588
+ : rawBaseResolved;
3589
+ if (!baseResolved)
3590
+ continue;
3591
+ // If the base resolves to a hook call, add .functionCallReturnValue
3592
+ if (baseResolved.endsWith('()')) {
3593
+ const newPath = baseResolved + '.functionCallReturnValue' + rest;
3594
+ if (newPath !== equivalentSignatureVariables[varName]) {
3595
+ equivalentSignatureVariables[varName] = newPath;
3596
+ changed = true;
3597
+ }
3598
+ }
3599
+ else if (baseResolved !== sourcePath) {
3600
+ const newPath = baseResolved + rest;
3601
+ if (newPath !== equivalentSignatureVariables[varName]) {
3602
+ equivalentSignatureVariables[varName] = newPath;
3603
+ changed = true;
3604
+ }
3605
+ }
3606
+ }
3607
+ }
3608
+ // Stop if no changes were made in this iteration
3609
+ if (!changed)
3610
+ break;
3611
+ }
2355
3612
  return equivalentSignatureVariables;
2356
3613
  }
2357
3614
  getVariableInfo(variableName, scopeName, final) {
@@ -2383,7 +3640,12 @@ export class ScopeDataStructure {
2383
3640
  return { ...acc, ...filterdSchema };
2384
3641
  }, {});
2385
3642
  const tempScopeNode = this.createTempScopeNode(scopeName ?? this.scopeTreeManager.getRootName(), relevantSchema);
3643
+ // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
3644
+ // during this "getter" method. See comment in getFunctionSignature.
3645
+ const wasOnlyEquivalencies = this.onlyEquivalencies;
3646
+ this.onlyEquivalencies = true;
2386
3647
  this.validateSchema(tempScopeNode, true, final);
3648
+ this.onlyEquivalencies = wasOnlyEquivalencies;
2387
3649
  return {
2388
3650
  name: variableName,
2389
3651
  equivalentTo: equivalents,
@@ -2391,7 +3653,184 @@ export class ScopeDataStructure {
2391
3653
  };
2392
3654
  }
2393
3655
  getExternalFunctionCalls() {
2394
- return this.externalFunctionCalls;
3656
+ // Replace cyScope placeholders in all external function call data
3657
+ // This ensures call signatures and schema paths use actual callback text
3658
+ // instead of internal cyScope names, preventing mock data merge conflicts.
3659
+ const rootScopeName = this.scopeTreeManager.getRootName();
3660
+ const rootSchema = this.scopeNodes[rootScopeName]?.schema ?? {};
3661
+ return this.externalFunctionCalls.map((efc) => {
3662
+ const cleaned = this.cleanCyScopeFromFunctionCallInfo(efc);
3663
+ return this.filterConflatedExternalPaths(cleaned, rootSchema);
3664
+ });
3665
+ }
3666
+ /**
3667
+ * Filters out conflated paths from external function call schemas.
3668
+ *
3669
+ * When multiple useState(false) calls create equivalency conflation during
3670
+ * Phase 1 analysis, standalone boolean state variables (like showWorkoutForm,
3671
+ * showGoalForm) can bleed into external function call schemas as sub-properties
3672
+ * of unrelated data fields (like data[].activity_type.showWorkoutForm).
3673
+ *
3674
+ * Detection: group sub-properties by parent path. If 2+ sub-properties of
3675
+ * the same parent all match standalone root scope variable names, treat them
3676
+ * as conflation artifacts and remove them.
3677
+ */
3678
+ filterConflatedExternalPaths(efc, rootSchema) {
3679
+ // Build a set of top-level root scope variable names (simple names, no dots/brackets)
3680
+ const topLevelRootVars = new Set();
3681
+ for (const key of Object.keys(rootSchema)) {
3682
+ if (!key.includes('.') && !key.includes('[')) {
3683
+ topLevelRootVars.add(key);
3684
+ }
3685
+ }
3686
+ if (topLevelRootVars.size === 0)
3687
+ return efc;
3688
+ // Group sub-property matches by their parent path.
3689
+ // For a path like "...data[].activity_type.showWorkoutForm",
3690
+ // parent = "...data[].activity_type", child = "showWorkoutForm"
3691
+ const parentToConflatedKeys = new Map();
3692
+ for (const key of Object.keys(efc.schema)) {
3693
+ const lastDot = key.lastIndexOf('.');
3694
+ if (lastDot === -1)
3695
+ continue;
3696
+ const parent = key.substring(0, lastDot);
3697
+ const child = key.substring(lastDot + 1);
3698
+ // Skip array access or function call patterns
3699
+ if (child.includes('[') || child.includes('('))
3700
+ continue;
3701
+ // Only consider paths inside array element chains (contains []).
3702
+ // Direct children of functionCallReturnValue are legitimate destructured
3703
+ // return values, not conflation. Conflation happens deeper in the chain
3704
+ // when array element fields get corrupted sub-properties.
3705
+ if (!parent.includes('['))
3706
+ continue;
3707
+ if (topLevelRootVars.has(child)) {
3708
+ if (!parentToConflatedKeys.has(parent)) {
3709
+ parentToConflatedKeys.set(parent, []);
3710
+ }
3711
+ parentToConflatedKeys.get(parent).push(key);
3712
+ }
3713
+ }
3714
+ // Only filter when 2+ sub-properties of the same parent match root scope vars.
3715
+ // This threshold avoids false positives from coincidental name matches.
3716
+ const keysToRemove = new Set();
3717
+ const parentsToRestore = new Set();
3718
+ for (const [parent, conflatedKeys] of parentToConflatedKeys) {
3719
+ if (conflatedKeys.length >= 2) {
3720
+ for (const key of conflatedKeys) {
3721
+ keysToRemove.add(key);
3722
+ }
3723
+ parentsToRestore.add(parent);
3724
+ }
3725
+ }
3726
+ if (keysToRemove.size === 0)
3727
+ return efc;
3728
+ // Create a new schema without the conflated paths
3729
+ const newSchema = {};
3730
+ for (const [key, value] of Object.entries(efc.schema)) {
3731
+ if (keysToRemove.has(key))
3732
+ continue;
3733
+ // Restore parent type: if it was changed to "object" because of conflated
3734
+ // sub-properties, and now all those sub-properties are removed, change it
3735
+ // back to "unknown" (we don't know the original type)
3736
+ if (parentsToRestore.has(key) && value === 'object') {
3737
+ // Check if there are any remaining sub-properties
3738
+ const hasRemainingSubProps = Object.keys(efc.schema).some((k) => !keysToRemove.has(k) &&
3739
+ k !== key &&
3740
+ (k.startsWith(key + '.') || k.startsWith(key + '[')));
3741
+ newSchema[key] = hasRemainingSubProps ? value : 'unknown';
3742
+ }
3743
+ else {
3744
+ newSchema[key] = value;
3745
+ }
3746
+ }
3747
+ return { ...efc, schema: newSchema };
3748
+ }
3749
+ /**
3750
+ * Cleans cyScope placeholder references from a FunctionCallInfo.
3751
+ * Replaces cyScopeN() with the actual callback text in:
3752
+ * - callSignature
3753
+ * - allCallSignatures
3754
+ * - schema keys
3755
+ */
3756
+ cleanCyScopeFromFunctionCallInfo(efc) {
3757
+ const cyScopePattern = /cyScope\d+\(\)/g;
3758
+ // Check if any cleaning is needed
3759
+ const hasCyScope = cyScopePattern.test(efc.callSignature) ||
3760
+ (efc.allCallSignatures &&
3761
+ efc.allCallSignatures.some((sig) => /cyScope\d+\(\)/.test(sig))) ||
3762
+ (efc.schema &&
3763
+ Object.keys(efc.schema).some((key) => /cyScope\d+\(\)/.test(key)));
3764
+ if (!hasCyScope) {
3765
+ return efc;
3766
+ }
3767
+ // Create cleaned copy
3768
+ const cleaned = { ...efc };
3769
+ // Clean callSignature
3770
+ cleaned.callSignature = this.replaceCyScopeInString(efc.callSignature);
3771
+ // Clean allCallSignatures
3772
+ if (efc.allCallSignatures) {
3773
+ cleaned.allCallSignatures = efc.allCallSignatures.map((sig) => this.replaceCyScopeInString(sig));
3774
+ }
3775
+ // Clean schema keys
3776
+ if (efc.schema) {
3777
+ cleaned.schema = this.replaceCyScopePlaceholders(efc.schema);
3778
+ }
3779
+ // Clean callSignatureToVariable keys
3780
+ if (efc.callSignatureToVariable) {
3781
+ cleaned.callSignatureToVariable = Object.entries(efc.callSignatureToVariable).reduce((acc, [key, value]) => {
3782
+ acc[this.replaceCyScopeInString(key)] = value;
3783
+ return acc;
3784
+ }, {});
3785
+ }
3786
+ return cleaned;
3787
+ }
3788
+ /**
3789
+ * Replaces cyScope placeholder references in a single string.
3790
+ * If the scope text can't be found, uses a generic fallback to avoid leaking
3791
+ * internal cyScope names into stored data.
3792
+ *
3793
+ * Handles two patterns:
3794
+ * 1. Function call style: cyScope7() - matched by cyScope(\d+)\(\)
3795
+ * 2. Scope name style: parentName____cyScopeXX or cyScopeXX - matched by (\w+____)?cyScope([0-9A-Fa-f]+)
3796
+ */
3797
+ replaceCyScopeInString(str) {
3798
+ let result = str;
3799
+ // Pattern 1: Function call style - cyScope7()
3800
+ const functionCallPattern = /cyScope(\d+)\(\)/g;
3801
+ const functionCallMatches = [...str.matchAll(functionCallPattern)];
3802
+ for (const match of functionCallMatches) {
3803
+ const cyScopeName = `cyScope${match[1]}`;
3804
+ const scopeText = this.findCyScopeText(cyScopeName);
3805
+ // Always replace cyScope references - use actual text if available,
3806
+ // otherwise use a generic callback placeholder
3807
+ const replacement = scopeText || '() => {}';
3808
+ result = result.replace(match[0], replacement);
3809
+ }
3810
+ // Pattern 2: Scope name style - parentName____cyScopeXX or just cyScopeXX
3811
+ // This handles hex-encoded scope IDs like cyScope1F
3812
+ const scopeNamePattern = /(\w+____)?cyScope([0-9A-Fa-f]+)/g;
3813
+ const scopeNameMatches = [...result.matchAll(scopeNamePattern)];
3814
+ for (const match of scopeNameMatches) {
3815
+ const fullMatch = match[0];
3816
+ const prefix = match[1] || ''; // e.g., "getTitleColor____"
3817
+ const cyScopeId = match[2]; // e.g., "1F"
3818
+ const cyScopeName = `cyScope${cyScopeId}`;
3819
+ // Try to find the scope text, checking both with and without prefix
3820
+ let scopeText = this.findCyScopeText(cyScopeName);
3821
+ if (!scopeText && prefix) {
3822
+ // Try looking up with the full prefixed name
3823
+ scopeText = this.findCyScopeText(`${prefix}${cyScopeName}`);
3824
+ }
3825
+ if (scopeText) {
3826
+ result = result.replace(fullMatch, scopeText);
3827
+ }
3828
+ else {
3829
+ // Replace with a generic identifier to avoid leaking internal names
3830
+ result = result.replace(fullMatch, 'callback');
3831
+ }
3832
+ }
3833
+ return result;
2395
3834
  }
2396
3835
  getEnvironmentVariables() {
2397
3836
  return this.environmentVariables;
@@ -2417,12 +3856,116 @@ export class ScopeDataStructure {
2417
3856
  }
2418
3857
  }
2419
3858
  }
3859
+ /**
3860
+ * Add conditional effects from AST analysis.
3861
+ * Called during scope analysis to collect all setter calls inside conditionals.
3862
+ */
3863
+ addConditionalEffects(effects) {
3864
+ // Add effects, avoiding duplicates based on effect stateVariable and condition paths
3865
+ for (const effect of effects) {
3866
+ const exists = this.rawConditionalEffects.some((existing) => {
3867
+ // Same effect target (stateVariable + value)
3868
+ const sameEffect = existing.effect.stateVariable === effect.effect.stateVariable &&
3869
+ existing.effect.value === effect.effect.value;
3870
+ if (!sameEffect)
3871
+ return false;
3872
+ // Same condition(s)
3873
+ if (existing.condition && effect.condition) {
3874
+ return (existing.condition.path === effect.condition.path &&
3875
+ existing.condition.requiredValue === effect.condition.requiredValue);
3876
+ }
3877
+ if (existing.conditions && effect.conditions) {
3878
+ if (existing.conditions.length !== effect.conditions.length)
3879
+ return false;
3880
+ return existing.conditions.every((ec, i) => {
3881
+ const newCond = effect.conditions[i];
3882
+ return (ec.path === newCond.path &&
3883
+ ec.requiredValue === newCond.requiredValue);
3884
+ });
3885
+ }
3886
+ return false;
3887
+ });
3888
+ if (!exists) {
3889
+ this.rawConditionalEffects.push(effect);
3890
+ }
3891
+ }
3892
+ }
3893
+ /**
3894
+ * Get conditional effects collected during analysis.
3895
+ */
3896
+ getConditionalEffects() {
3897
+ return this.rawConditionalEffects;
3898
+ }
3899
+ /**
3900
+ * Add compound conditionals from AST analysis.
3901
+ * Called during scope analysis to collect grouped conditions (e.g., a && b && c).
3902
+ */
3903
+ addCompoundConditionals(compounds) {
3904
+ // Add compounds, avoiding duplicates based on chainId
3905
+ for (const compound of compounds) {
3906
+ const exists = this.rawCompoundConditionals.some((existing) => existing.chainId === compound.chainId);
3907
+ if (!exists) {
3908
+ this.rawCompoundConditionals.push(compound);
3909
+ }
3910
+ }
3911
+ }
3912
+ /**
3913
+ * Get compound conditionals collected during analysis.
3914
+ */
3915
+ getCompoundConditionals() {
3916
+ return this.rawCompoundConditionals;
3917
+ }
3918
+ /**
3919
+ * Add child boundary gating conditions from AST analysis.
3920
+ * These track which conditions must be true for a child component to render.
3921
+ */
3922
+ addChildBoundaryGatingConditions(conditions) {
3923
+ for (const [childName, usages] of Object.entries(conditions)) {
3924
+ if (!this.rawChildBoundaryGatingConditions[childName]) {
3925
+ this.rawChildBoundaryGatingConditions[childName] = [];
3926
+ }
3927
+ // Add usages, avoiding duplicates
3928
+ for (const usage of usages) {
3929
+ const exists = this.rawChildBoundaryGatingConditions[childName].some((existing) => existing.path === usage.path &&
3930
+ existing.conditionType === usage.conditionType &&
3931
+ existing.isNegated === usage.isNegated);
3932
+ if (!exists) {
3933
+ this.rawChildBoundaryGatingConditions[childName].push(usage);
3934
+ }
3935
+ }
3936
+ }
3937
+ }
3938
+ /**
3939
+ * Get enriched child boundary gating conditions with source tracing.
3940
+ * Similar to getEnrichedConditionalUsages but for gating conditions.
3941
+ */
3942
+ getEnrichedChildBoundaryGatingConditions() {
3943
+ const enriched = {};
3944
+ const rootScopeName = this.scopeTreeManager.getTree().name;
3945
+ for (const [childName, usages] of Object.entries(this.rawChildBoundaryGatingConditions)) {
3946
+ enriched[childName] = usages.map((usage) => {
3947
+ // Try to trace this path back to a data source
3948
+ const explanation = this.explainPath(rootScopeName, usage.path);
3949
+ let sourceDataPath;
3950
+ if (explanation.source) {
3951
+ sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
3952
+ }
3953
+ return {
3954
+ ...usage,
3955
+ sourceDataPath,
3956
+ };
3957
+ });
3958
+ }
3959
+ return enriched;
3960
+ }
2420
3961
  /**
2421
3962
  * Get enriched conditional usages with source tracing.
2422
3963
  * Uses explainPath to trace each local variable back to its data source.
3964
+ * Preserves all fields from the raw conditional usages including derivedFrom.
2423
3965
  */
2424
3966
  getEnrichedConditionalUsages() {
2425
3967
  const enriched = {};
3968
+ console.log(`[getEnrichedConditionalUsages] Processing ${Object.keys(this.rawConditionalUsages).length} conditional paths: [${Object.keys(this.rawConditionalUsages).join(', ')}]`);
2426
3969
  for (const [path, usages] of Object.entries(this.rawConditionalUsages)) {
2427
3970
  // Try to trace this path back to a data source
2428
3971
  // First, try the root scope
@@ -2430,9 +3973,47 @@ export class ScopeDataStructure {
2430
3973
  const explanation = this.explainPath(rootScopeName, path);
2431
3974
  let sourceDataPath;
2432
3975
  if (explanation.source) {
2433
- // Build the full data path: scopeName.path
2434
- sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
3976
+ const { scope, path: sourcePath } = explanation.source;
3977
+ // Build initial path — avoid redundant prefix when path already contains the scope call
3978
+ let fullPath;
3979
+ if (sourcePath.startsWith(`${scope}(`)) {
3980
+ fullPath = sourcePath;
3981
+ }
3982
+ else {
3983
+ fullPath = `${scope}.${sourcePath}`;
3984
+ }
3985
+ sourceDataPath = fullPath;
3986
+ console.log(`[getEnrichedConditionalUsages] "${path}" explainPath → scope="${scope}", sourcePath="${sourcePath}" → sourceDataPath="${sourceDataPath}"`);
3987
+ }
3988
+ else {
3989
+ console.log(`[getEnrichedConditionalUsages] "${path}" explainPath → no source found`);
3990
+ }
3991
+ // If explainPath didn't find a useful external source (e.g., it traced to
3992
+ // useState or just to the component scope itself), check sourceEquivalencies
3993
+ // for an external function call source like a fetch call
3994
+ const hasExternalSource = sourceDataPath?.includes('.functionCallReturnValue');
3995
+ if (!hasExternalSource) {
3996
+ console.log(`[getEnrichedConditionalUsages] "${path}" no external source (sourceDataPath="${sourceDataPath}"), checking sourceEquivalencies fallback...`);
3997
+ const sourceEquiv = this.getSourceEquivalencies();
3998
+ const returnValueKey = `returnValue.${path}`;
3999
+ const sources = sourceEquiv[returnValueKey];
4000
+ if (sources) {
4001
+ console.log(`[getEnrichedConditionalUsages] "${path}" sourceEquivalencies["${returnValueKey}"] has ${sources.length} sources: [${sources.map((s) => s.schemaPath).join(', ')}]`);
4002
+ const externalSource = sources.find((s) => s.schemaPath.includes('.functionCallReturnValue') &&
4003
+ !s.schemaPath.startsWith('useState('));
4004
+ if (externalSource) {
4005
+ console.log(`[getEnrichedConditionalUsages] "${path}" sourceEquivalencies fallback found external source: "${externalSource.schemaPath}"`);
4006
+ sourceDataPath = externalSource.schemaPath;
4007
+ }
4008
+ else {
4009
+ console.log(`[getEnrichedConditionalUsages] "${path}" sourceEquivalencies fallback found no external function call source`);
4010
+ }
4011
+ }
4012
+ else {
4013
+ console.log(`[getEnrichedConditionalUsages] "${path}" sourceEquivalencies["${returnValueKey}"] not found`);
4014
+ }
2435
4015
  }
4016
+ console.log(`[getEnrichedConditionalUsages] "${path}" FINAL sourceDataPath="${sourceDataPath ?? '(none)'}" (${usages.length} usages)`);
2436
4017
  enriched[path] = usages.map((usage) => ({
2437
4018
  ...usage,
2438
4019
  sourceDataPath,
@@ -2440,69 +4021,435 @@ export class ScopeDataStructure {
2440
4021
  }
2441
4022
  return enriched;
2442
4023
  }
4024
+ /**
4025
+ * Add JSX rendering usages from AST analysis.
4026
+ * These track arrays rendered via .map() and strings interpolated in JSX.
4027
+ */
4028
+ addJsxRenderingUsages(usages) {
4029
+ // Add usages, avoiding duplicates based on path and renderingType
4030
+ for (const usage of usages) {
4031
+ const exists = this.rawJsxRenderingUsages.some((existing) => existing.path === usage.path &&
4032
+ existing.renderingType === usage.renderingType);
4033
+ if (!exists) {
4034
+ this.rawJsxRenderingUsages.push(usage);
4035
+ }
4036
+ }
4037
+ }
4038
+ /**
4039
+ * Get JSX rendering usages collected during analysis.
4040
+ */
4041
+ getJsxRenderingUsages() {
4042
+ return this.rawJsxRenderingUsages;
4043
+ }
2443
4044
  toSerializable() {
2444
- // Helper to convert ScopeVariable to SerializableScopeVariable
4045
+ // Helper to clean cyScope and cyDuplicateKey from a string for output
4046
+ const cleanCyScope = (str) => this.replaceCyScopeInString(str).replace(/::cyDuplicateKey\d+::/g, '');
4047
+ // Helper to convert ScopeVariable to SerializableScopeVariable (with cyScope cleaned)
2445
4048
  const toSerializableVariable = (vars) => vars.map((v) => ({
2446
- scopeNodeName: v.scopeNodeName,
2447
- schemaPath: v.schemaPath,
4049
+ scopeNodeName: cleanCyScope(v.scopeNodeName),
4050
+ schemaPath: cleanCyScope(v.schemaPath),
2448
4051
  }));
4052
+ // Helper to clean cyScope from all keys in a schema
4053
+ const cleanSchemaKeys = (schema) => {
4054
+ return Object.entries(schema).reduce((acc, [key, value]) => {
4055
+ acc[cleanCyScope(key)] = value;
4056
+ return acc;
4057
+ }, {});
4058
+ };
2449
4059
  // Helper to get function result for a given function name
2450
4060
  const getFunctionResult = (functionName) => {
2451
4061
  return {
2452
- signature: this.getFunctionSignature({ functionName }) ?? {},
2453
- signatureWithUnknowns: this.getFunctionSignature({ functionName, fillInUnknowns: true }) ??
2454
- {},
2455
- returnValue: this.getReturnValue({ functionName }) ?? {},
2456
- returnValueWithUnknowns: this.getReturnValue({ functionName, fillInUnknowns: true }) ?? {},
4062
+ signature: cleanSchemaKeys(this.getFunctionSignature({ functionName }) ?? {}),
4063
+ signatureWithUnknowns: cleanSchemaKeys(this.getFunctionSignature({ functionName, fillInUnknowns: true }) ??
4064
+ {}),
4065
+ returnValue: cleanSchemaKeys(this.getReturnValue({ functionName }) ?? {}),
4066
+ returnValueWithUnknowns: cleanSchemaKeys(this.getReturnValue({ functionName, fillInUnknowns: true }) ?? {}),
2457
4067
  usageEquivalencies: Object.entries(this.getUsageEquivalencies(functionName) ?? {}).reduce((acc, [key, vars]) => {
2458
- acc[key] = toSerializableVariable(vars);
4068
+ // Clean cyScope from the key as well as variable properties
4069
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
2459
4070
  return acc;
2460
4071
  }, {}),
2461
4072
  sourceEquivalencies: Object.entries(this.getSourceEquivalencies(functionName) ?? {}).reduce((acc, [key, vars]) => {
2462
- acc[key] = toSerializableVariable(vars);
4073
+ // Clean cyScope from the key as well as variable properties
4074
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
2463
4075
  return acc;
2464
4076
  }, {}),
2465
4077
  environmentVariables: this.getEnvironmentVariables(),
2466
4078
  };
2467
4079
  };
2468
- // Convert external function calls
2469
- const externalFunctionCalls = this.externalFunctionCalls.map((efc) => ({
2470
- name: efc.name,
2471
- callSignature: efc.callSignature,
2472
- callScope: efc.callScope,
2473
- schema: efc.schema,
2474
- equivalencies: efc.equivalencies
2475
- ? Object.entries(efc.equivalencies).reduce((acc, [key, vars]) => {
2476
- acc[key] = toSerializableVariable(vars);
2477
- return acc;
2478
- }, {})
2479
- : undefined,
2480
- allCallSignatures: efc.allCallSignatures,
2481
- receivingVariableNames: efc.receivingVariableNames,
2482
- callSignatureToVariable: efc.callSignatureToVariable,
2483
- }));
4080
+ // Convert external function calls - use getExternalFunctionCalls() which cleans cyScope
4081
+ const cleanedExternalCalls = this.getExternalFunctionCalls();
4082
+ // Get root scope schema for building per-variable return value schemas
4083
+ const rootScopeName = this.scopeTreeManager.getRootName();
4084
+ const rootScope = this.scopeNodes[rootScopeName];
4085
+ const rootSchema = rootScope?.schema ?? {};
4086
+ const externalFunctionCalls = cleanedExternalCalls.map((efc) => {
4087
+ // Build perVariableSchemas from perCallSignatureSchemas when available.
4088
+ // This preserves distinct schemas per variable when the same function is called
4089
+ // multiple times with DIFFERENT call signatures (e.g., different type parameters).
4090
+ //
4091
+ // When field accesses happen in child scopes (like JSX expressions), the
4092
+ // rootSchema doesn't contain the detailed paths - they end up in child scope
4093
+ // schemas. Using perCallSignatureSchemas ensures we get the correct schema
4094
+ // for each call, regardless of where field accesses occur.
4095
+ let perVariableSchemas;
4096
+ // Use perCallSignatureSchemas only when:
4097
+ // 1. It exists and has distinct entries for different call signatures
4098
+ // 2. The number of distinct call signatures >= number of receiving variables
4099
+ //
4100
+ // This prevents using it when all calls have the same signature (e.g., useFetcher() x 2)
4101
+ // because in that case, perCallSignatureSchemas only has one entry.
4102
+ const numCallSignatures = efc.perCallSignatureSchemas
4103
+ ? Object.keys(efc.perCallSignatureSchemas).length
4104
+ : 0;
4105
+ const numReceivingVars = efc.receivingVariableNames?.length ?? 0;
4106
+ const hasDistinctSchemas = numCallSignatures >= numReceivingVars && numCallSignatures > 1;
4107
+ // CASE 1: Multiple call signatures with distinct schemas - use indexed variable names
4108
+ if (hasDistinctSchemas &&
4109
+ efc.perCallSignatureSchemas &&
4110
+ efc.callSignatureToVariable) {
4111
+ perVariableSchemas = {};
4112
+ // Build a reverse map: variable -> array of call signatures (in order)
4113
+ // This handles the case where the same variable name is reused for different calls
4114
+ const varToCallSigs = {};
4115
+ for (const [callSig, varName] of Object.entries(efc.callSignatureToVariable)) {
4116
+ if (!varToCallSigs[varName]) {
4117
+ varToCallSigs[varName] = [];
4118
+ }
4119
+ varToCallSigs[varName].push(callSig);
4120
+ }
4121
+ // Track how many times each variable name has been seen
4122
+ const varNameCounts = {};
4123
+ // For each receiving variable, get its original schema from perCallSignatureSchemas
4124
+ for (const varName of efc.receivingVariableNames ?? []) {
4125
+ const occurrence = varNameCounts[varName] ?? 0;
4126
+ varNameCounts[varName] = occurrence + 1;
4127
+ const callSigs = varToCallSigs[varName];
4128
+ // Use the nth call signature for the nth occurrence of this variable
4129
+ const callSig = callSigs?.[occurrence];
4130
+ if (callSig && efc.perCallSignatureSchemas[callSig]) {
4131
+ // Use indexed key if this variable name is reused (e.g., fetcher, fetcher[1])
4132
+ const key = occurrence === 0 ? varName : `${varName}[${occurrence}]`;
4133
+ // Clone the schema to avoid shared references
4134
+ perVariableSchemas[key] = {
4135
+ ...efc.perCallSignatureSchemas[callSig],
4136
+ };
4137
+ }
4138
+ }
4139
+ // Only include if we have entries for ALL receiving variables
4140
+ if (Object.keys(perVariableSchemas).length < numReceivingVars) {
4141
+ // Not all variables have schemas - fall back to rootSchema extraction
4142
+ perVariableSchemas = undefined;
4143
+ }
4144
+ else {
4145
+ // Also check that at least one schema is non-empty
4146
+ // Bug fix: perCallSignatureSchemas may have entries but with empty schemas {}
4147
+ // In this case, we should fall through to Fallback which uses rootSchema
4148
+ const hasNonEmptySchema = Object.values(perVariableSchemas).some((schema) => Object.keys(schema).length > 0);
4149
+ if (!hasNonEmptySchema) {
4150
+ perVariableSchemas = undefined;
4151
+ }
4152
+ }
4153
+ }
4154
+ // CASE 2: Single call signature with single variable - use perCallSignatureSchemas directly
4155
+ // This handles parameterized calls like useFetcher<ConfigData>() where each is a separate efc entry
4156
+ if (!perVariableSchemas &&
4157
+ efc.perCallSignatureSchemas &&
4158
+ numCallSignatures === 1 &&
4159
+ numReceivingVars === 1) {
4160
+ const varName = efc.receivingVariableNames[0];
4161
+ const callSig = Object.keys(efc.perCallSignatureSchemas)[0];
4162
+ const schema = efc.perCallSignatureSchemas[callSig];
4163
+ if (schema && Object.keys(schema).length > 0) {
4164
+ perVariableSchemas = { [varName]: { ...schema } };
4165
+ }
4166
+ }
4167
+ // CASE 3: Extract from efc.schema when perCallSignatureSchemas is missing or empty
4168
+ // This handles two scenarios:
4169
+ // 1. Parameterized calls that create SEPARATE efc entries (no perCallSignatureSchemas)
4170
+ // 2. Destructuring where perCallSignatureSchemas exists but has EMPTY schemas
4171
+ //
4172
+ // When useFetcher<ConfigData>() and useFetcher<SettingsData>() are called, they create separate
4173
+ // efc entries because getFunctionCallRoot preserves type parameters. Each entry has its own
4174
+ // `schema` field, but due to variable reassignment, the schema may be contaminated with paths
4175
+ // from other calls (the tracer attributes field accesses to ALL equivalencies).
4176
+ //
4177
+ // Solution: Filter efc.schema to only include paths that match THIS entry's call signature.
4178
+ // The schema paths include the full call signature prefix, so we can filter by it.
4179
+ //
4180
+ // Example: ConfigData entry has paths like:
4181
+ // "useFetcher<{ data: ConfigData | null }>().functionCallReturnValue.data.data.theme"
4182
+ // But also (contaminated):
4183
+ // "useFetcher<{ data: ConfigData | null }>().functionCallReturnValue.data.data.notifications"
4184
+ //
4185
+ // We filter to only keep paths that should belong to THIS call by checking if the
4186
+ // receiving variable's equivalency points to this call's return value.
4187
+ //
4188
+ // BUG FIX: The old condition `!efc.perCallSignatureSchemas` was FALSE when the object
4189
+ // existed (even with empty schemas), causing this case to be skipped. We now also check
4190
+ // if all schemas in perCallSignatureSchemas are empty.
4191
+ const hasNonEmptyPerCallSignatureSchemas = efc.perCallSignatureSchemas &&
4192
+ Object.values(efc.perCallSignatureSchemas).some((schema) => Object.keys(schema).length > 0);
4193
+ // Build the call signature prefix that paths should start with
4194
+ const callSigPrefix = `${efc.callSignature}.functionCallReturnValue`;
4195
+ // Check if efc.schema has variable-specific paths (indicating destructuring).
4196
+ // Destructuring: const { entities, gitStatus } = useLoaderData()
4197
+ // - efc.schema has paths like: useLoaderData().functionCallReturnValue.entities...
4198
+ // Multiple calls: const x = useFetcher(); const y = useFetcher();
4199
+ // - efc.schema has paths like: useFetcher().functionCallReturnValue.data...
4200
+ // CASE 3 should only run for destructuring (variable-specific paths exist).
4201
+ const hasVariableSpecificPaths = (efc.receivingVariableNames ?? []).some((varName) => Object.keys(efc.schema).some((path) => path.startsWith(`${callSigPrefix}.${varName}`)));
4202
+ if (!perVariableSchemas &&
4203
+ !hasNonEmptyPerCallSignatureSchemas &&
4204
+ numReceivingVars >= 1 &&
4205
+ hasVariableSpecificPaths) {
4206
+ // Filter efc.schema to only include paths matching this call signature
4207
+ const filteredSchema = {};
4208
+ for (const [path, type] of Object.entries(efc.schema)) {
4209
+ if (path.startsWith(callSigPrefix) || path === efc.callSignature) {
4210
+ filteredSchema[path] = type;
4211
+ }
4212
+ }
4213
+ // Build perVariableSchemas from the filtered schema
4214
+ // For destructuring, filter paths by variable name
4215
+ if (Object.keys(filteredSchema).length > 0) {
4216
+ perVariableSchemas = {};
4217
+ for (const varName of efc.receivingVariableNames ?? []) {
4218
+ // For destructuring, extract only paths specific to this variable
4219
+ const varSpecificPrefix = `${callSigPrefix}.${varName}`;
4220
+ const varSchema = {};
4221
+ for (const [path, type] of Object.entries(filteredSchema)) {
4222
+ if (path.startsWith(varSpecificPrefix)) {
4223
+ // Transform: useLoaderData().functionCallReturnValue.entities.sha
4224
+ // -> functionCallReturnValue.entities.sha (keep the variable name)
4225
+ const suffix = path.slice(callSigPrefix.length);
4226
+ const returnValuePath = `functionCallReturnValue${suffix}`;
4227
+ varSchema[returnValuePath] = type;
4228
+ }
4229
+ else if (path === efc.callSignature) {
4230
+ // Include the function call type itself
4231
+ varSchema[path] = type;
4232
+ }
4233
+ }
4234
+ if (Object.keys(varSchema).length > 0) {
4235
+ perVariableSchemas[varName] = varSchema;
4236
+ }
4237
+ }
4238
+ // Only include if we have entries
4239
+ if (Object.keys(perVariableSchemas).length === 0) {
4240
+ perVariableSchemas = undefined;
4241
+ }
4242
+ }
4243
+ }
4244
+ // Fallback: extract from root scope schema when perCallSignatureSchemas is not available
4245
+ // or doesn't have distinct entries for each variable.
4246
+ // This works when field accesses are in the root scope.
4247
+ if (!perVariableSchemas &&
4248
+ efc.receivingVariableNames &&
4249
+ efc.receivingVariableNames.length > 0) {
4250
+ perVariableSchemas = {};
4251
+ for (const varName of efc.receivingVariableNames) {
4252
+ const varSchema = {};
4253
+ for (const [path, type] of Object.entries(rootSchema)) {
4254
+ // Check if path starts with this variable name
4255
+ if (path === varName ||
4256
+ path.startsWith(varName + '.') ||
4257
+ path.startsWith(varName + '[')) {
4258
+ // Transform to functionCallReturnValue format
4259
+ // e.g., userFetcher.data.id -> functionCallReturnValue.data.id
4260
+ const suffix = path.slice(varName.length);
4261
+ const returnValuePath = `functionCallReturnValue${suffix}`;
4262
+ varSchema[returnValuePath] = type;
4263
+ }
4264
+ }
4265
+ if (Object.keys(varSchema).length > 0) {
4266
+ // Clean the variable name when using as key in output
4267
+ perVariableSchemas[cleanCyScope(varName)] = varSchema;
4268
+ }
4269
+ }
4270
+ // Only include if we have any entries
4271
+ if (Object.keys(perVariableSchemas).length === 0) {
4272
+ perVariableSchemas = undefined;
4273
+ }
4274
+ }
4275
+ // Enrich the schema with inferred types by applying fillInSchemaGapsAndUnknowns.
4276
+ // This ensures the serialized schema has the same type inference as getReturnValue().
4277
+ // Without this, evidence like "entities[].analyses: array" becomes "unknown".
4278
+ const enrichedSchema = { ...efc.schema };
4279
+ const tempScopeNode = {
4280
+ name: efc.name,
4281
+ schema: enrichedSchema,
4282
+ equivalencies: efc.equivalencies ?? {},
4283
+ };
4284
+ fillInSchemaGapsAndUnknowns(tempScopeNode, true);
4285
+ return {
4286
+ name: efc.name,
4287
+ callSignature: efc.callSignature,
4288
+ callScope: efc.callScope,
4289
+ schema: enrichedSchema,
4290
+ equivalencies: efc.equivalencies
4291
+ ? Object.entries(efc.equivalencies).reduce((acc, [key, vars]) => {
4292
+ // Clean cyScope from the key as well as variable properties
4293
+ acc[cleanCyScope(key)] = toSerializableVariable(vars);
4294
+ return acc;
4295
+ }, {})
4296
+ : undefined,
4297
+ allCallSignatures: efc.allCallSignatures,
4298
+ receivingVariableNames: efc.receivingVariableNames?.map(cleanCyScope),
4299
+ callSignatureToVariable: efc.callSignatureToVariable
4300
+ ? Object.fromEntries(Object.entries(efc.callSignatureToVariable).map(([k, v]) => [
4301
+ k,
4302
+ cleanCyScope(v),
4303
+ ]))
4304
+ : undefined,
4305
+ perVariableSchemas,
4306
+ };
4307
+ });
4308
+ // POST-PROCESSING: Deduplicate schemas across parameterized calls to same base function
4309
+ // When useFetcher<ConfigData>() and useFetcher<SettingsData>() are called, they create
4310
+ // separate entries. Due to variable reassignment, BOTH entries may have ALL fields.
4311
+ // We deduplicate by assigning each field to ONLY ONE entry based on order of appearance.
4312
+ //
4313
+ // Strategy: Fields that appear first in order belong to the first entry,
4314
+ // fields that appear later belong to later entries (split evenly).
4315
+ const deduplicateParameterizedEntries = (entries) => {
4316
+ // Group entries by base function name (without type parameters)
4317
+ const groups = new Map();
4318
+ for (const entry of entries) {
4319
+ // Extract base function name by stripping type parameters
4320
+ // e.g., "useFetcher<{ data: ConfigData | null }>" -> "useFetcher"
4321
+ const baseName = entry.name.replace(/<.*>$/, '');
4322
+ const group = groups.get(baseName) || [];
4323
+ group.push(entry);
4324
+ groups.set(baseName, group);
4325
+ }
4326
+ // Process groups with multiple parameterized entries
4327
+ for (const [, group] of groups) {
4328
+ if (group.length <= 1)
4329
+ continue;
4330
+ // Check if these are parameterized calls (have type parameters in name)
4331
+ const hasTypeParams = group.every((e) => e.name.includes('<'));
4332
+ if (!hasTypeParams)
4333
+ continue;
4334
+ // Collect ALL unique field suffixes across all entries (in order of first appearance)
4335
+ // Field suffix is the path after functionCallReturnValue, e.g., ".data.data.theme"
4336
+ const allFieldSuffixes = [];
4337
+ for (const entry of group) {
4338
+ if (!entry.perVariableSchemas)
4339
+ continue;
4340
+ for (const varSchema of Object.values(entry.perVariableSchemas)) {
4341
+ for (const path of Object.keys(varSchema)) {
4342
+ // Skip the base "functionCallReturnValue" entry
4343
+ if (path === 'functionCallReturnValue')
4344
+ continue;
4345
+ // Extract field suffix
4346
+ const match = path.match(/functionCallReturnValue(.+)/);
4347
+ if (!match)
4348
+ continue;
4349
+ const fieldSuffix = match[1];
4350
+ if (!allFieldSuffixes.includes(fieldSuffix)) {
4351
+ allFieldSuffixes.push(fieldSuffix);
4352
+ }
4353
+ }
4354
+ }
4355
+ }
4356
+ // Assign fields to entries: split evenly based on order
4357
+ // First N/2 fields go to first entry, remaining go to second entry
4358
+ const fieldToEntryMap = new Map();
4359
+ const fieldsPerEntry = Math.ceil(allFieldSuffixes.length / group.length);
4360
+ for (let i = 0; i < allFieldSuffixes.length; i++) {
4361
+ const fieldSuffix = allFieldSuffixes[i];
4362
+ const entryIdx = Math.min(Math.floor(i / fieldsPerEntry), group.length - 1);
4363
+ fieldToEntryMap.set(fieldSuffix, entryIdx);
4364
+ }
4365
+ // Filter each entry's perVariableSchemas to only include its assigned fields
4366
+ for (let i = 0; i < group.length; i++) {
4367
+ const entry = group[i];
4368
+ if (!entry.perVariableSchemas)
4369
+ continue;
4370
+ const filteredPerVarSchemas = {};
4371
+ for (const [varName, varSchema] of Object.entries(entry.perVariableSchemas)) {
4372
+ const filteredVarSchema = {};
4373
+ for (const [path, type] of Object.entries(varSchema)) {
4374
+ // Always keep the base functionCallReturnValue
4375
+ if (path === 'functionCallReturnValue') {
4376
+ filteredVarSchema[path] = type;
4377
+ continue;
4378
+ }
4379
+ // Extract field suffix
4380
+ const match = path.match(/functionCallReturnValue(.+)/);
4381
+ if (!match) {
4382
+ // Keep non-field paths
4383
+ filteredVarSchema[path] = type;
4384
+ continue;
4385
+ }
4386
+ const fieldSuffix = match[1];
4387
+ // Only include if this entry owns this field
4388
+ if (fieldToEntryMap.get(fieldSuffix) === i) {
4389
+ filteredVarSchema[path] = type;
4390
+ }
4391
+ }
4392
+ if (Object.keys(filteredVarSchema).length > 0) {
4393
+ filteredPerVarSchemas[varName] = filteredVarSchema;
4394
+ }
4395
+ }
4396
+ entry.perVariableSchemas =
4397
+ Object.keys(filteredPerVarSchemas).length > 0
4398
+ ? filteredPerVarSchemas
4399
+ : undefined;
4400
+ }
4401
+ }
4402
+ return entries;
4403
+ };
4404
+ // Apply deduplication
4405
+ const deduplicatedExternalFunctionCalls = deduplicateParameterizedEntries(externalFunctionCalls);
4406
+ // IMPORTANT: Get equivalent signature variables BEFORE calling getFunctionResult
4407
+ // because getFunctionResult calls validateSchema which may remove equivalencies
4408
+ // during the finalize step (e.g., cleanNonObjectFunctions removes method call
4409
+ // equivalencies like `segments -> splat.split('/').functionCallReturnValue`).
4410
+ // Fix 33: Move this call before any schema validation to preserve method call chains.
4411
+ const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
2484
4412
  // Get root function result
2485
4413
  const rootFunction = getFunctionResult();
2486
- // Get results for each external function
4414
+ // Get results for each external function (use cleaned calls for consistency)
2487
4415
  const functionResults = {};
2488
- for (const efc of this.externalFunctionCalls) {
4416
+ for (const efc of cleanedExternalCalls) {
2489
4417
  functionResults[efc.name] = getFunctionResult(efc.name);
2490
4418
  }
2491
- // Get equivalent signature variables
2492
- const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
2493
4419
  const environmentVariables = this.getEnvironmentVariables();
2494
4420
  // Get enriched conditional usages with source tracing
2495
4421
  const enrichedConditionalUsages = this.getEnrichedConditionalUsages();
2496
4422
  const conditionalUsages = Object.keys(enrichedConditionalUsages).length > 0
2497
4423
  ? enrichedConditionalUsages
2498
4424
  : undefined;
4425
+ // Get conditional effects (setter calls inside conditionals)
4426
+ const conditionalEffects = this.rawConditionalEffects.length > 0
4427
+ ? this.rawConditionalEffects
4428
+ : undefined;
4429
+ // Get compound conditionals (grouped conditions that must all be true)
4430
+ const compoundConditionals = this.rawCompoundConditionals.length > 0
4431
+ ? this.rawCompoundConditionals
4432
+ : undefined;
4433
+ // Get child boundary gating conditions
4434
+ const enrichedGatingConditions = this.getEnrichedChildBoundaryGatingConditions();
4435
+ const childBoundaryGatingConditions = Object.keys(enrichedGatingConditions).length > 0
4436
+ ? enrichedGatingConditions
4437
+ : undefined;
4438
+ // Get JSX rendering usages (arrays via .map(), strings via interpolation)
4439
+ const jsxRenderingUsages = this.rawJsxRenderingUsages.length > 0
4440
+ ? this.rawJsxRenderingUsages
4441
+ : undefined;
2499
4442
  return {
2500
- externalFunctionCalls,
4443
+ externalFunctionCalls: deduplicatedExternalFunctionCalls,
2501
4444
  rootFunction,
2502
4445
  functionResults,
2503
4446
  equivalentSignatureVariables,
2504
4447
  environmentVariables,
2505
4448
  conditionalUsages,
4449
+ conditionalEffects,
4450
+ compoundConditionals,
4451
+ childBoundaryGatingConditions,
4452
+ jsxRenderingUsages,
2506
4453
  };
2507
4454
  }
2508
4455
  // ═══════════════════════════════════════════════════════════════════════════