@codeyam/codeyam-cli 0.1.0-staging.1669d45 → 0.1.0-staging.1a2737b

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 (654) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +19 -19
  4. package/analyzer-template/packages/ai/index.ts +16 -2
  5. package/analyzer-template/packages/ai/package.json +2 -2
  6. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +110 -52
  7. package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
  8. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +98 -9
  9. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +139 -23
  10. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.ts +10 -17
  11. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +6 -126
  12. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +656 -28
  13. package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
  14. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +94 -7
  15. package/analyzer-template/packages/ai/src/lib/completionCall.ts +198 -34
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +1331 -254
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +5 -1
  18. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +205 -0
  19. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +10 -2
  20. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
  21. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +54 -3
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +124 -17
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
  25. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +140 -14
  26. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
  27. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
  28. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +393 -97
  29. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
  30. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  31. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +183 -0
  32. package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
  33. package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
  34. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +58 -3
  35. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +936 -7
  36. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +35 -6
  37. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +515 -6
  38. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +1 -1
  39. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +1540 -75
  40. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
  41. package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +51 -3
  42. package/analyzer-template/packages/ai/src/lib/mergeJsonTypeDefinitions.ts +5 -0
  43. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +90 -96
  44. package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
  45. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +10 -7
  46. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
  47. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
  48. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +44 -7
  49. package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
  50. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +179 -45
  51. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +26 -4
  52. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +114 -2
  53. package/analyzer-template/packages/analyze/index.ts +2 -0
  54. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +65 -59
  55. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
  56. package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
  57. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  58. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
  59. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
  60. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
  61. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
  62. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
  63. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
  64. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +99 -22
  65. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +19 -4
  66. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +6 -0
  67. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
  68. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
  69. package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
  70. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +14 -12
  71. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1315 -0
  72. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +193 -76
  73. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +87 -25
  74. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +269 -22
  75. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +118 -10
  76. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +647 -73
  77. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
  78. package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
  79. package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
  80. package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
  81. package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
  82. package/analyzer-template/packages/aws/package.json +10 -10
  83. package/analyzer-template/packages/database/package.json +1 -1
  84. package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +1 -1
  85. package/analyzer-template/packages/database/src/lib/analysisToDb.ts +1 -1
  86. package/analyzer-template/packages/database/src/lib/branchToDb.ts +1 -1
  87. package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +1 -1
  88. package/analyzer-template/packages/database/src/lib/commitToDb.ts +1 -1
  89. package/analyzer-template/packages/database/src/lib/fileToDb.ts +1 -1
  90. package/analyzer-template/packages/database/src/lib/kysely/db.ts +14 -1
  91. package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
  92. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +1 -1
  93. package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
  94. package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
  95. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
  96. package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
  97. package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
  98. package/analyzer-template/packages/database/src/lib/loadCommits.ts +28 -0
  99. package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
  100. package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
  101. package/analyzer-template/packages/database/src/lib/projectToDb.ts +1 -1
  102. package/analyzer-template/packages/database/src/lib/saveFiles.ts +1 -1
  103. package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +1 -1
  104. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +7 -14
  105. package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +1 -1
  106. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +1 -1
  107. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -1
  108. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +1 -1
  109. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -1
  110. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +1 -1
  111. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -1
  112. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +1 -1
  113. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -1
  114. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +1 -1
  115. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -1
  116. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +1 -1
  117. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -1
  118. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -0
  119. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  120. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +11 -1
  121. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  122. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  123. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +1 -0
  124. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
  125. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
  126. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  127. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +1 -1
  128. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
  129. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
  130. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  131. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  132. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +2 -0
  133. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
  134. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
  135. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
  136. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  137. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
  138. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  139. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
  140. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
  141. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
  142. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
  143. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
  144. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
  145. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  146. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +22 -1
  147. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  148. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
  149. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  150. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
  151. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  152. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
  153. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
  154. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -1
  155. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +1 -1
  156. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -1
  157. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +1 -1
  158. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -1
  159. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +1 -1
  160. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -1
  161. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +2 -2
  162. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  163. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +5 -4
  164. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  165. package/analyzer-template/packages/github/dist/types/index.d.ts +1 -1
  166. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  167. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  168. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +25 -1
  169. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  170. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts +2 -0
  171. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts.map +1 -1
  172. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  173. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  174. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +56 -6
  175. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  176. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  177. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  178. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
  179. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  180. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
  181. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
  182. package/analyzer-template/packages/github/package.json +1 -1
  183. package/analyzer-template/packages/types/index.ts +1 -0
  184. package/analyzer-template/packages/types/src/types/Analysis.ts +25 -0
  185. package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
  186. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +7 -0
  187. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +70 -6
  188. package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
  189. package/analyzer-template/packages/utils/dist/types/index.d.ts +1 -1
  190. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  191. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  192. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +25 -1
  193. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  194. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts +2 -0
  195. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts.map +1 -1
  196. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  197. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  198. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +56 -6
  199. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  200. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  201. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  202. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  203. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +93 -2
  204. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  205. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
  206. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  207. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
  208. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
  209. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +108 -2
  210. package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
  211. package/analyzer-template/playwright/capture.ts +20 -8
  212. package/analyzer-template/playwright/captureStatic.ts +1 -1
  213. package/analyzer-template/project/analyzeBaselineCommit.ts +5 -0
  214. package/analyzer-template/project/analyzeRegularCommit.ts +5 -0
  215. package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
  216. package/analyzer-template/project/constructMockCode.ts +436 -44
  217. package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
  218. package/analyzer-template/project/loadReadyToBeCaptured.ts +65 -41
  219. package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
  220. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +18 -7
  221. package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
  222. package/analyzer-template/project/orchestrateCapture.ts +75 -7
  223. package/analyzer-template/project/reconcileMockDataKeys.ts +152 -9
  224. package/analyzer-template/project/runAnalysis.ts +4 -0
  225. package/analyzer-template/project/start.ts +35 -11
  226. package/analyzer-template/project/writeMockDataTsx.ts +295 -10
  227. package/analyzer-template/project/writeScenarioComponents.ts +237 -32
  228. package/analyzer-template/project/writeSimpleRoot.ts +21 -11
  229. package/analyzer-template/scripts/comboWorkerLoop.cjs +98 -50
  230. package/background/src/lib/local/createLocalAnalyzer.js +1 -1
  231. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  232. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +5 -0
  233. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
  234. package/background/src/lib/virtualized/project/analyzeRegularCommit.js +5 -0
  235. package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
  236. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
  237. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
  238. package/background/src/lib/virtualized/project/constructMockCode.js +359 -14
  239. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  240. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js +73 -1
  241. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js.map +1 -1
  242. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +19 -8
  243. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  244. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js +2 -2
  245. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js.map +1 -1
  246. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +7 -5
  247. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  248. package/background/src/lib/virtualized/project/orchestrateCapture.js +62 -7
  249. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  250. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +126 -9
  251. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  252. package/background/src/lib/virtualized/project/runAnalysis.js +3 -0
  253. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  254. package/background/src/lib/virtualized/project/start.js +32 -11
  255. package/background/src/lib/virtualized/project/start.js.map +1 -1
  256. package/background/src/lib/virtualized/project/writeMockDataTsx.js +251 -6
  257. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  258. package/background/src/lib/virtualized/project/writeScenarioComponents.js +173 -30
  259. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  260. package/background/src/lib/virtualized/project/writeSimpleRoot.js +21 -11
  261. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  262. package/codeyam-cli/scripts/apply-setup.js +180 -0
  263. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  264. package/codeyam-cli/src/cli.js +32 -18
  265. package/codeyam-cli/src/cli.js.map +1 -1
  266. package/codeyam-cli/src/codeyam-cli.js +18 -2
  267. package/codeyam-cli/src/codeyam-cli.js.map +1 -1
  268. package/codeyam-cli/src/commands/analyze.js +4 -2
  269. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  270. package/codeyam-cli/src/commands/baseline.js +2 -0
  271. package/codeyam-cli/src/commands/baseline.js.map +1 -1
  272. package/codeyam-cli/src/commands/debug.js +9 -5
  273. package/codeyam-cli/src/commands/debug.js.map +1 -1
  274. package/codeyam-cli/src/commands/default.js +31 -20
  275. package/codeyam-cli/src/commands/default.js.map +1 -1
  276. package/codeyam-cli/src/commands/detect-universal-mocks.js +2 -0
  277. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +1 -1
  278. package/codeyam-cli/src/commands/init.js +49 -257
  279. package/codeyam-cli/src/commands/init.js.map +1 -1
  280. package/codeyam-cli/src/commands/memory.js +307 -0
  281. package/codeyam-cli/src/commands/memory.js.map +1 -0
  282. package/codeyam-cli/src/commands/recapture.js +2 -0
  283. package/codeyam-cli/src/commands/recapture.js.map +1 -1
  284. package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
  285. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
  286. package/codeyam-cli/src/commands/setup-simulations.js +284 -0
  287. package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
  288. package/codeyam-cli/src/commands/test-startup.js +2 -0
  289. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  290. package/codeyam-cli/src/commands/verify.js +14 -2
  291. package/codeyam-cli/src/commands/verify.js.map +1 -1
  292. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +179 -0
  293. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  294. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +128 -82
  295. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  296. package/codeyam-cli/src/utils/analysisRunner.js +21 -2
  297. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  298. package/codeyam-cli/src/utils/analyzer.js +7 -0
  299. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  300. package/codeyam-cli/src/utils/backgroundServer.js +90 -19
  301. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  302. package/codeyam-cli/src/utils/generateReport.js +2 -2
  303. package/codeyam-cli/src/utils/install-skills.js +77 -38
  304. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  305. package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
  306. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
  307. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  308. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  309. package/codeyam-cli/src/utils/progress.js +7 -0
  310. package/codeyam-cli/src/utils/progress.js.map +1 -1
  311. package/codeyam-cli/src/utils/queue/job.js +5 -0
  312. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  313. package/codeyam-cli/src/utils/queue/manager.js +6 -0
  314. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  315. package/codeyam-cli/src/utils/requireSimulations.js +10 -0
  316. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
  317. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
  318. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
  319. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +230 -0
  320. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
  321. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
  322. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
  323. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
  324. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
  325. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
  326. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
  327. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
  328. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
  329. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +74 -0
  330. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
  331. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +376 -0
  332. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
  333. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +116 -0
  334. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
  335. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
  336. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
  337. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
  338. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
  339. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +116 -0
  340. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
  341. package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
  342. package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
  343. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +44 -0
  344. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
  345. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
  346. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
  347. package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
  348. package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
  349. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
  350. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
  351. package/codeyam-cli/src/utils/rules/index.js +6 -0
  352. package/codeyam-cli/src/utils/rules/index.js.map +1 -0
  353. package/codeyam-cli/src/utils/rules/parser.js +83 -0
  354. package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
  355. package/codeyam-cli/src/utils/rules/pathMatcher.js +18 -0
  356. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
  357. package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
  358. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
  359. package/codeyam-cli/src/utils/rules/staleness.js +137 -0
  360. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
  361. package/codeyam-cli/src/utils/serverState.js +37 -10
  362. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  363. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +21 -42
  364. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  365. package/codeyam-cli/src/utils/simulationGateMiddleware.js +138 -0
  366. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  367. package/codeyam-cli/src/utils/syncMocksMiddleware.js +5 -24
  368. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  369. package/codeyam-cli/src/utils/versionInfo.js +25 -0
  370. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  371. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  372. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  373. package/codeyam-cli/src/webserver/app/lib/database.js +22 -6
  374. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  375. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  376. package/codeyam-cli/src/webserver/backgroundServer.js +50 -0
  377. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  378. package/codeyam-cli/src/webserver/bootstrap.js +51 -0
  379. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -1
  380. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-jNYXRRNI.js +1 -0
  381. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-bwuHPyTa.js +11 -0
  382. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-COi5OvsN.js → EntityTypeBadge-CvzqMxcu.js} +1 -1
  383. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-BwdQv49w.js → EntityTypeIcon-BH0XDim7.js} +1 -1
  384. package/codeyam-cli/src/webserver/build/client/assets/{InlineSpinner-CEleMv_j.js → InlineSpinner-EhOseatT.js} +1 -1
  385. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-D68KarMg.js → InteractivePreview-yjIHlOGa.js} +2 -2
  386. package/codeyam-cli/src/webserver/build/client/assets/{LibraryFunctionPreview-L75Wvqgw.js → LibraryFunctionPreview-Cq5o8jL4.js} +1 -1
  387. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-C53WM8qn.js → LoadingDots-BvMu2i-g.js} +1 -1
  388. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-CrNkmy4i.js → LogViewer-kgBTLoJD.js} +1 -1
  389. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BzPgx-xO.js +11 -0
  390. package/codeyam-cli/src/webserver/build/client/assets/{SafeScreenshot-CQifa1n-.js → SafeScreenshot-CwZrv-Ok.js} +1 -1
  391. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-CyaBFX7l.js → ScenarioViewer-BX2Ny2Qj.js} +3 -13
  392. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-D36O1rzU.js → TruncatedFilePath-CDpEprKa.js} +1 -1
  393. package/codeyam-cli/src/webserver/build/client/assets/_index-BRx8ZGZo.js +11 -0
  394. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-4S4yPfFw.js +27 -0
  395. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DHKuQSmR.js +17 -0
  396. package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
  397. package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
  398. package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-l0sNRNKZ.js +1 -0
  399. package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
  400. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  401. package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
  402. package/codeyam-cli/src/webserver/build/client/assets/book-open-D4IPYH_y.js +6 -0
  403. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-DgTPh8H-.js → chevron-down-CG65viiV.js} +1 -1
  404. package/codeyam-cli/src/webserver/build/client/assets/{chunk-EPOLDU6W-DdQKK6on.js → chunk-JZWAC4HX-DB3aFuEO.js} +12 -12
  405. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-Dmr2bb1R.js → circle-check-igfMr5DY.js} +1 -1
  406. package/codeyam-cli/src/webserver/build/client/assets/copy-Coc4o_8c.js +11 -0
  407. package/codeyam-cli/src/webserver/build/client/assets/{createLucideIcon-Do4ZLUYa.js → createLucideIcon-D1zB-pYc.js} +1 -1
  408. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-JTAjQ54M.js +1 -0
  409. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CbdFyxZh.js → entity._sha._-B0h9AqE6.js} +12 -12
  410. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha.scenarios._scenarioId.fullscreen-B4iCfs5M.js → entity._sha.scenarios._scenarioId.fullscreen-DjLxr2JB.js} +1 -1
  411. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.create-scenario-wDWZZO1W.js → entity._sha_.create-scenario-CtYowLOt.js} +1 -1
  412. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-BMbl7MeQ.js → entity._sha_.edit._scenarioId-PePWg17F.js} +1 -1
  413. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-5wRKRIH9.js → entry.client-I-Wo99C_.js} +1 -1
  414. package/codeyam-cli/src/webserver/build/client/assets/{fileTableUtils-DD3SDH7t.js → fileTableUtils-9sMMAiWJ.js} +1 -1
  415. package/codeyam-cli/src/webserver/build/client/assets/files-Co65J0s3.js +1 -0
  416. package/codeyam-cli/src/webserver/build/client/assets/{git-zXjT7J0G.js → git-BdHOxVfg.js} +8 -8
  417. package/codeyam-cli/src/webserver/build/client/assets/globals-BSZfYCkU.css +1 -0
  418. package/codeyam-cli/src/webserver/build/client/assets/{index-DLbXwndH.js → index-CUM5iXwc.js} +1 -1
  419. package/codeyam-cli/src/webserver/build/client/assets/{index-gPZ-lad1.js → index-_417gcQW.js} +1 -1
  420. package/codeyam-cli/src/webserver/build/client/assets/labs-BK0C1H1T.js +1 -0
  421. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BsPXJ81F.js → loader-circle-TzRHMVog.js} +1 -1
  422. package/codeyam-cli/src/webserver/build/client/assets/manifest-040dab1c.js +1 -0
  423. package/codeyam-cli/src/webserver/build/client/assets/memory-UIDVz141.js +92 -0
  424. package/codeyam-cli/src/webserver/build/client/assets/pause-hjzB7t2z.js +11 -0
  425. package/codeyam-cli/src/webserver/build/client/assets/root-D1WadSdf.js +62 -0
  426. package/codeyam-cli/src/webserver/build/client/assets/{search-P2FKIUql.js → search-DcAwD_Ln.js} +1 -1
  427. package/codeyam-cli/src/webserver/build/client/assets/settings-CclxrcPK.js +1 -0
  428. package/codeyam-cli/src/webserver/build/client/assets/{simulations-L18M6-kN.js → simulations-DVNJVQgD.js} +1 -1
  429. package/codeyam-cli/src/webserver/build/client/assets/terminal-DbEAHMbA.js +11 -0
  430. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-BDz7kbVA.js → triangle-alert-CAD5b1o_.js} +1 -1
  431. package/codeyam-cli/src/webserver/build/client/assets/{useCustomSizes-29dDmbH8.js → useCustomSizes-BqgrAzs3.js} +1 -1
  432. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-BUm0UVJm.js → useLastLogLine-DAFqfEDH.js} +1 -1
  433. package/codeyam-cli/src/webserver/build/client/assets/{useReportContext-CkIOKTrZ.js → useReportContext-DZlYx2c4.js} +1 -1
  434. package/codeyam-cli/src/webserver/build/client/assets/{useToast-KKw5kTn-.js → useToast-ihdMtlf6.js} +1 -1
  435. package/codeyam-cli/src/webserver/build/server/assets/index-B3dE0r28.js +1 -0
  436. package/codeyam-cli/src/webserver/build/server/assets/server-build-DYbfdxa3.js +273 -0
  437. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  438. package/codeyam-cli/src/webserver/build-info.json +5 -5
  439. package/codeyam-cli/templates/{codeyam:debug.md → codeyam-debug.md} +48 -4
  440. package/codeyam-cli/templates/codeyam-diagnose.md +481 -0
  441. package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
  442. package/codeyam-cli/templates/codeyam-memory.md +396 -0
  443. package/codeyam-cli/templates/codeyam-new-rule.md +13 -0
  444. package/codeyam-cli/templates/{codeyam:setup.md → codeyam-setup.md} +13 -1
  445. package/codeyam-cli/templates/{codeyam:sim.md → codeyam-sim.md} +1 -1
  446. package/codeyam-cli/templates/{codeyam:test.md → codeyam-test.md} +1 -1
  447. package/codeyam-cli/templates/{codeyam:verify.md → codeyam-verify.md} +1 -1
  448. package/codeyam-cli/templates/rule-notification-hook.py +56 -0
  449. package/codeyam-cli/templates/rule-reflection-hook.py +627 -0
  450. package/codeyam-cli/templates/rules-instructions.md +132 -0
  451. package/package.json +18 -15
  452. package/packages/ai/index.js +7 -3
  453. package/packages/ai/index.js.map +1 -1
  454. package/packages/ai/src/lib/analyzeScope.js +91 -30
  455. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  456. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  457. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  458. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +78 -8
  459. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  460. package/packages/ai/src/lib/astScopes/methodSemantics.js +109 -23
  461. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  462. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
  463. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
  464. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +1 -102
  465. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  466. package/packages/ai/src/lib/astScopes/processExpression.js +518 -28
  467. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  468. package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
  469. package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
  470. package/packages/ai/src/lib/completionCall.js +161 -30
  471. package/packages/ai/src/lib/completionCall.js.map +1 -1
  472. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1061 -174
  473. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  474. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +5 -1
  475. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  476. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +179 -0
  477. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -1
  478. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +7 -1
  479. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  480. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  481. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  482. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  483. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  484. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +52 -3
  485. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  486. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +106 -13
  487. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  488. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
  489. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
  490. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +122 -12
  491. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  492. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
  493. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  494. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  495. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  496. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +333 -86
  497. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  498. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  499. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  500. package/packages/ai/src/lib/dataStructureChunking.js +130 -0
  501. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  502. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  503. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  504. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  505. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  506. package/packages/ai/src/lib/generateEntityDataStructure.js +46 -2
  507. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  508. package/packages/ai/src/lib/generateEntityScenarioData.js +734 -8
  509. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  510. package/packages/ai/src/lib/generateEntityScenarios.js +26 -2
  511. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  512. package/packages/ai/src/lib/generateExecutionFlows.js +376 -4
  513. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  514. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1124 -59
  515. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -1
  516. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  517. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  518. package/packages/ai/src/lib/isolateScopes.js +39 -3
  519. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  520. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
  521. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
  522. package/packages/ai/src/lib/mergeStatements.js +70 -51
  523. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  524. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
  525. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
  526. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +10 -4
  527. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  528. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  529. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  530. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +30 -7
  531. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  532. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  533. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  534. package/packages/ai/src/lib/resolvePathToControllable.js +155 -41
  535. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -1
  536. package/packages/ai/src/lib/worker/SerializableDataStructure.js +7 -0
  537. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  538. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +94 -1
  539. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  540. package/packages/analyze/index.js +1 -0
  541. package/packages/analyze/index.js.map +1 -1
  542. package/packages/analyze/src/lib/FileAnalyzer.js +60 -36
  543. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  544. package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
  545. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  546. package/packages/analyze/src/lib/analysisContext.js +30 -5
  547. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  548. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  549. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  550. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  551. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  552. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  553. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  554. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  555. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  556. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  557. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  558. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  559. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  560. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  561. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  562. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +72 -10
  563. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  564. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +17 -4
  565. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  566. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
  567. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  568. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  569. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  570. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
  571. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  572. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  573. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  574. package/packages/analyze/src/lib/files/getImportedExports.js +11 -7
  575. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  576. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
  577. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
  578. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +164 -68
  579. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -1
  580. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +75 -21
  581. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  582. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +185 -20
  583. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  584. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +57 -9
  585. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
  586. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +542 -53
  587. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  588. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  589. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  590. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  591. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  592. package/packages/analyze/src/lib/index.js +1 -0
  593. package/packages/analyze/src/lib/index.js.map +1 -1
  594. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  595. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  596. package/packages/database/src/lib/analysisBranchToDb.js +1 -1
  597. package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
  598. package/packages/database/src/lib/analysisToDb.js +1 -1
  599. package/packages/database/src/lib/analysisToDb.js.map +1 -1
  600. package/packages/database/src/lib/branchToDb.js +1 -1
  601. package/packages/database/src/lib/branchToDb.js.map +1 -1
  602. package/packages/database/src/lib/commitBranchToDb.js +1 -1
  603. package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
  604. package/packages/database/src/lib/commitToDb.js +1 -1
  605. package/packages/database/src/lib/commitToDb.js.map +1 -1
  606. package/packages/database/src/lib/fileToDb.js +1 -1
  607. package/packages/database/src/lib/fileToDb.js.map +1 -1
  608. package/packages/database/src/lib/kysely/db.js +11 -1
  609. package/packages/database/src/lib/kysely/db.js.map +1 -1
  610. package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
  611. package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  612. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  613. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  614. package/packages/database/src/lib/loadAnalyses.js +45 -2
  615. package/packages/database/src/lib/loadAnalyses.js.map +1 -1
  616. package/packages/database/src/lib/loadAnalysis.js +8 -0
  617. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  618. package/packages/database/src/lib/loadBranch.js +11 -1
  619. package/packages/database/src/lib/loadBranch.js.map +1 -1
  620. package/packages/database/src/lib/loadCommit.js +7 -0
  621. package/packages/database/src/lib/loadCommit.js.map +1 -1
  622. package/packages/database/src/lib/loadCommits.js +22 -1
  623. package/packages/database/src/lib/loadCommits.js.map +1 -1
  624. package/packages/database/src/lib/loadEntities.js +23 -4
  625. package/packages/database/src/lib/loadEntities.js.map +1 -1
  626. package/packages/database/src/lib/loadEntityBranches.js +9 -0
  627. package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
  628. package/packages/database/src/lib/projectToDb.js +1 -1
  629. package/packages/database/src/lib/projectToDb.js.map +1 -1
  630. package/packages/database/src/lib/saveFiles.js +1 -1
  631. package/packages/database/src/lib/saveFiles.js.map +1 -1
  632. package/packages/database/src/lib/scenarioToDb.js +1 -1
  633. package/packages/database/src/lib/scenarioToDb.js.map +1 -1
  634. package/packages/database/src/lib/updateCommitMetadata.js +5 -4
  635. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  636. package/packages/types/index.js.map +1 -1
  637. package/packages/utils/src/lib/fs/rsyncCopy.js +93 -2
  638. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  639. package/packages/utils/src/lib/safeFileName.js +29 -3
  640. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  641. package/scripts/finalize-analyzer.cjs +8 -76
  642. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-vauWK972.js +0 -1
  643. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-DzJRkCkr.js +0 -11
  644. package/codeyam-cli/src/webserver/build/client/assets/_index-Be83mo_j.js +0 -11
  645. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-BN6wu6Y-.js +0 -37
  646. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-Bn6aCAy_.js +0 -1
  647. package/codeyam-cli/src/webserver/build/client/assets/files-DKyMFI90.js +0 -1
  648. package/codeyam-cli/src/webserver/build/client/assets/globals-DTTQ3gY7.css +0 -1
  649. package/codeyam-cli/src/webserver/build/client/assets/manifest-22590fcf.js +0 -1
  650. package/codeyam-cli/src/webserver/build/client/assets/root-BsAarjAM.js +0 -57
  651. package/codeyam-cli/src/webserver/build/client/assets/settings-B2eDuBj8.js +0 -1
  652. package/codeyam-cli/src/webserver/build/server/assets/index-BND5I5fv.js +0 -1
  653. package/codeyam-cli/src/webserver/build/server/assets/server-build-CFXnd7MG.js +0 -228
  654. package/codeyam-cli/templates/codeyam:diagnose.md +0 -625
@@ -82,6 +82,8 @@
82
82
  import { ScopeAnalysis } from '~codeyam/types';
83
83
  import { EquivalencyManager } from './equivalencyManagers/EquivalencyManager';
84
84
  import fillInSchemaGapsAndUnknowns from './helpers/fillInSchemaGapsAndUnknowns';
85
+ import { clearCleanKnownObjectFunctionsCache } from './helpers/cleanKnownObjectFunctions';
86
+ import { clearCleanNonObjectFunctionsCache } from './helpers/cleanNonObjectFunctions';
85
87
 
86
88
  /**
87
89
  * Patterns that indicate recursive type structures in schema paths.
@@ -150,7 +152,7 @@ export interface ScopeInfo {
150
152
  [childComponentName: string]: Array<{
151
153
  path: string;
152
154
  conditionType: 'truthiness' | 'comparison';
153
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
155
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
154
156
  isNegated?: boolean;
155
157
  }>;
156
158
  };
@@ -332,6 +334,19 @@ export function resetScopeDataStructureMetrics() {
332
334
  followEquivalenciesEarlyExitPhase1Count = 0;
333
335
  followEquivalenciesWithWorkCount = 0;
334
336
  addEquivalencyCallCount = 0;
337
+
338
+ // Clear module-level caches to prevent unbounded memory growth across entities
339
+ const knownObjectCache = clearCleanKnownObjectFunctionsCache();
340
+ const nonObjectCache = clearCleanNonObjectFunctionsCache();
341
+ if (knownObjectCache.count > 0 || nonObjectCache.count > 0) {
342
+ const totalBytes =
343
+ knownObjectCache.estimatedBytes + nonObjectCache.estimatedBytes;
344
+ console.log('CodeYam: Cleared analysis caches', {
345
+ knownObjectCache: `${knownObjectCache.count} entries, ${(knownObjectCache.estimatedBytes / 1024).toFixed(1)}KB`,
346
+ nonObjectCache: `${nonObjectCache.count} entries, ${(nonObjectCache.estimatedBytes / 1024).toFixed(1)}KB`,
347
+ totalKB: `${(totalBytes / 1024).toFixed(1)}KB`,
348
+ });
349
+ }
335
350
  }
336
351
 
337
352
  // Performance: Pre-computed Sets for equivalency reason filtering (O(1) vs O(n))
@@ -382,6 +397,7 @@ const SILENTLY_IGNORED_EQUIVALENCY_REASONS = new Set([
382
397
  'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
383
398
  'transformed non-object function equivalency - Array.from() equivalency',
384
399
  'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
400
+ // 'transformed non-object function equivalency - Explicit array deconstruction equivalency value',
385
401
  ]);
386
402
 
387
403
  export class ScopeDataStructure {
@@ -409,7 +425,7 @@ export class ScopeDataStructure {
409
425
  path: string;
410
426
  conditionType: 'truthiness' | 'comparison' | 'switch';
411
427
  comparedValues?: string[];
412
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
428
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
413
429
  }>
414
430
  > = {};
415
431
 
@@ -436,6 +452,13 @@ export class ScopeDataStructure {
436
452
  import('../astScopes/types').ConditionalUsage[]
437
453
  > = {};
438
454
 
455
+ /**
456
+ * JSX rendering usages collected during AST analysis.
457
+ * Tracks arrays rendered via .map() and strings interpolated in JSX.
458
+ */
459
+ private rawJsxRenderingUsages: import('../astScopes/types').JsxRenderingUsage[] =
460
+ [];
461
+
439
462
  private lastAddToSchemaId = 0;
440
463
  private lastEquivalencyId = 0;
441
464
  private lastEquivalencyDatabaseId = 0;
@@ -777,6 +800,11 @@ export class ScopeDataStructure {
777
800
  return;
778
801
  }
779
802
 
803
+ // PERF: Early exit for paths with repeated function-call signature patterns
804
+ if (this.hasExcessivePatternRepetition(path)) {
805
+ return;
806
+ }
807
+
780
808
  // Update chain metadata for database tracking
781
809
  if (equivalencyValueChain.length > 0) {
782
810
  equivalencyValueChain[equivalencyValueChain.length - 1].addToSchemaId =
@@ -1464,6 +1492,15 @@ export class ScopeDataStructure {
1464
1492
 
1465
1493
  const bestValue = selectBestValue(value1, value2);
1466
1494
 
1495
+ // PERF: Skip paths with repeated function-call signature patterns
1496
+ // to prevent recursive type expansion (e.g., string.localeCompare returns string)
1497
+ if (
1498
+ this.hasExcessivePatternRepetition(schemaPath) ||
1499
+ this.hasExcessivePatternRepetition(equivalentSchemaPath)
1500
+ ) {
1501
+ continue;
1502
+ }
1503
+
1467
1504
  scopeNode.schema[schemaPath] = bestValue;
1468
1505
  equivalentScopeNode.schema[equivalentSchemaPath] = bestValue;
1469
1506
  } else if (
@@ -1477,6 +1514,11 @@ export class ScopeDataStructure {
1477
1514
  ...remainingSchemaPathParts,
1478
1515
  ]);
1479
1516
 
1517
+ // PERF: Skip paths with repeated function-call signature patterns
1518
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
1519
+ continue;
1520
+ }
1521
+
1480
1522
  equivalentScopeNode.schema[newEquivalentPath] =
1481
1523
  scopeNode.schema[schemaPath];
1482
1524
  }
@@ -1596,6 +1638,23 @@ export class ScopeDataStructure {
1596
1638
  }
1597
1639
  }
1598
1640
 
1641
+ // Check for repeated function calls that indicate recursive type expansion.
1642
+ // E.g., localeCompare(b[])...localeCompare(b[]) means string.localeCompare
1643
+ // returns a type that again has localeCompare, causing infinite expansion.
1644
+ // We extract all function call patterns like "funcName(args)" and check if
1645
+ // the same normalized call appears more than once.
1646
+ const funcCallPattern = /(?:^|\.)[^.([]+\([^)]*\)/g;
1647
+ const funcCallMatches = path.match(funcCallPattern);
1648
+ if (funcCallMatches && funcCallMatches.length > 1) {
1649
+ const seen = new Set<string>();
1650
+ for (const match of funcCallMatches) {
1651
+ // Strip leading dot and normalize array indices
1652
+ const normalized = match.replace(/^\./, '').replace(/\[\d+\]/g, '[]');
1653
+ if (seen.has(normalized)) return true;
1654
+ seen.add(normalized);
1655
+ }
1656
+ }
1657
+
1599
1658
  // For longer paths, detect any repeated multi-part segments we haven't explicitly listed
1600
1659
  const pathParts = this.splitPath(path);
1601
1660
  if (pathParts.length <= 6) {
@@ -1628,17 +1687,26 @@ export class ScopeDataStructure {
1628
1687
  private setInstantiatedVariables(scopeNode: ScopeNode) {
1629
1688
  let instantiatedVariables = scopeNode.analysis?.instantiatedVariables ?? [];
1630
1689
 
1631
- for (const [path, equivalentPath] of Object.entries(
1690
+ for (const [path, rawEquivalentPath] of Object.entries(
1632
1691
  scopeNode.analysis.isolatedEquivalentVariables ?? {},
1633
1692
  )) {
1634
- if (typeof equivalentPath !== 'string') {
1635
- continue;
1636
- }
1693
+ // Normalize to array for consistent handling (supports both string and string[])
1694
+ const equivalentPaths = Array.isArray(rawEquivalentPath)
1695
+ ? rawEquivalentPath
1696
+ : rawEquivalentPath
1697
+ ? [rawEquivalentPath]
1698
+ : [];
1699
+
1700
+ for (const equivalentPath of equivalentPaths) {
1701
+ if (typeof equivalentPath !== 'string') {
1702
+ continue;
1703
+ }
1637
1704
 
1638
- if (equivalentPath.startsWith('signature[')) {
1639
- const equivalentPathParts = this.splitPath(equivalentPath);
1640
- instantiatedVariables.push(equivalentPathParts[0]);
1641
- instantiatedVariables.push(path);
1705
+ if (equivalentPath.startsWith('signature[')) {
1706
+ const equivalentPathParts = this.splitPath(equivalentPath);
1707
+ instantiatedVariables.push(equivalentPathParts[0]);
1708
+ instantiatedVariables.push(path);
1709
+ }
1642
1710
  }
1643
1711
 
1644
1712
  const duplicateInstantiated = instantiatedVariables.find(
@@ -1651,9 +1719,14 @@ export class ScopeDataStructure {
1651
1719
  }
1652
1720
  }
1653
1721
 
1654
- instantiatedVariables = instantiatedVariables.filter(
1655
- (varName, index, self) => self.indexOf(varName) === index,
1656
- );
1722
+ const instantiatedSeen = new Set<string>();
1723
+ instantiatedVariables = instantiatedVariables.filter((varName) => {
1724
+ if (instantiatedSeen.has(varName)) {
1725
+ return false;
1726
+ }
1727
+ instantiatedSeen.add(varName);
1728
+ return true;
1729
+ });
1657
1730
 
1658
1731
  scopeNode.instantiatedVariables = instantiatedVariables;
1659
1732
 
@@ -1674,13 +1747,19 @@ export class ScopeDataStructure {
1674
1747
  ...parentScopeNode.instantiatedVariables.filter(
1675
1748
  (v) => !v.startsWith('signature[') && !v.startsWith('returnValue'),
1676
1749
  ),
1677
- ].filter(
1678
- (varName, index, self) =>
1679
- !instantiatedVariables.includes(varName) &&
1680
- self.indexOf(varName) === index,
1681
- );
1750
+ ].filter((varName) => !instantiatedSeen.has(varName));
1751
+
1752
+ const parentInstantiatedSeen = new Set<string>();
1753
+ const dedupedParentInstantiatedVariables =
1754
+ parentInstantiatedVariables.filter((varName) => {
1755
+ if (parentInstantiatedSeen.has(varName)) {
1756
+ return false;
1757
+ }
1758
+ parentInstantiatedSeen.add(varName);
1759
+ return true;
1760
+ });
1682
1761
 
1683
- scopeNode.parentInstantiatedVariables = parentInstantiatedVariables;
1762
+ scopeNode.parentInstantiatedVariables = dedupedParentInstantiatedVariables;
1684
1763
  }
1685
1764
 
1686
1765
  private trackFunctionCalls(scopeNode: ScopeNode) {
@@ -1696,172 +1775,198 @@ export class ScopeDataStructure {
1696
1775
  const { isolatedStructure, isolatedEquivalentVariables } =
1697
1776
  scopeNode.analysis;
1698
1777
 
1778
+ // Flatten isolatedEquivalentVariables values for allPaths (handles both string and string[])
1779
+ const flattenedEquivValues = Object.values(
1780
+ isolatedEquivalentVariables || {},
1781
+ ).flatMap((v) => (Array.isArray(v) ? v : [v]));
1782
+
1699
1783
  const allPaths = Array.from(
1700
1784
  new Set([
1701
1785
  ...Object.keys(isolatedStructure || {}),
1702
1786
  ...Object.keys(isolatedEquivalentVariables || {}),
1703
- ...Object.values(isolatedEquivalentVariables || {}),
1787
+ ...flattenedEquivValues,
1704
1788
  ]),
1705
1789
  );
1706
1790
 
1707
1791
  for (let path in isolatedEquivalentVariables) {
1708
- let equivalentValue = isolatedEquivalentVariables?.[path];
1709
-
1710
- if (equivalentValue && this.isValidPath(equivalentValue)) {
1711
- // IMPORTANT: DO NOT strip ::cyDuplicateKey:: markers from equivalencies.
1712
- // These markers are critical for distinguishing variable reassignments.
1713
- // For example, with:
1714
- // let fetcher = useFetcher<ConfigData>();
1715
- // const configData = fetcher.data?.data;
1716
- // fetcher = useFetcher<SettingsData>();
1717
- // const settingsData = fetcher.data?.data;
1718
- //
1719
- // mergeStatements creates:
1720
- // fetcher useFetcher<ConfigData>()...
1721
- // fetcher::cyDuplicateKey1:: useFetcher<SettingsData>()...
1722
- // configData fetcher.data.data
1723
- // settingsData → fetcher::cyDuplicateKey1::.data.data
1724
- //
1725
- // If we strip ::cyDuplicateKey::, settingsData would incorrectly trace
1726
- // to useFetcher<ConfigData>() instead of useFetcher<SettingsData>().
1727
- path = cleanPath(path, allPaths);
1728
- equivalentValue = cleanPath(equivalentValue, allPaths);
1729
-
1730
- this.addEquivalency(
1731
- path,
1732
- equivalentValue,
1733
- scopeNode.name,
1734
- scopeNode,
1735
- 'original equivalency',
1736
- );
1792
+ const rawEquivalentValue = isolatedEquivalentVariables?.[path];
1793
+ // Normalize to array for consistent handling
1794
+ const equivalentValues = Array.isArray(rawEquivalentValue)
1795
+ ? rawEquivalentValue
1796
+ : [rawEquivalentValue];
1797
+
1798
+ for (let equivalentValue of equivalentValues) {
1799
+ if (equivalentValue && this.isValidPath(equivalentValue)) {
1800
+ // IMPORTANT: DO NOT strip ::cyDuplicateKey:: markers from equivalencies.
1801
+ // These markers are critical for distinguishing variable reassignments.
1802
+ // For example, with:
1803
+ // let fetcher = useFetcher<ConfigData>();
1804
+ // const configData = fetcher.data?.data;
1805
+ // fetcher = useFetcher<SettingsData>();
1806
+ // const settingsData = fetcher.data?.data;
1807
+ //
1808
+ // mergeStatements creates:
1809
+ // fetcher useFetcher<ConfigData>()...
1810
+ // fetcher::cyDuplicateKey1:: useFetcher<SettingsData>()...
1811
+ // configData fetcher.data.data
1812
+ // settingsData fetcher::cyDuplicateKey1::.data.data
1813
+ //
1814
+ // If we strip ::cyDuplicateKey::, settingsData would incorrectly trace
1815
+ // to useFetcher<ConfigData>() instead of useFetcher<SettingsData>().
1816
+ path = cleanPath(path, allPaths);
1817
+ equivalentValue = cleanPath(equivalentValue, allPaths);
1818
+
1819
+ this.addEquivalency(
1820
+ path,
1821
+ equivalentValue,
1822
+ scopeNode.name,
1823
+ scopeNode,
1824
+ 'original equivalency',
1825
+ );
1737
1826
 
1738
- // Propagate equivalencies involving parent-scope variables to those parent scopes.
1739
- // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1740
- // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1741
- // visible when tracing from the parent scope.
1742
- const rootVariable = this.extractRootVariable(path);
1743
- const equivalentRootVariable =
1744
- this.extractRootVariable(equivalentValue);
1745
-
1746
- // Skip propagation for self-referential reassignment patterns like:
1747
- // x = x.method().functionCallReturnValue
1748
- // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1749
- // These create circular references since both sides reference the same variable.
1750
- //
1751
- // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1752
- // where the path has additional segments beyond the root variable.
1753
- const pathIsJustRootVariable = path === rootVariable;
1754
- const isSelfReferentialReassignment =
1755
- pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1827
+ // Propagate equivalencies involving parent-scope variables to those parent scopes.
1828
+ // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1829
+ // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1830
+ // visible when tracing from the parent scope.
1831
+ const rootVariable = this.extractRootVariable(path);
1832
+ const equivalentRootVariable =
1833
+ this.extractRootVariable(equivalentValue);
1834
+
1835
+ // Skip propagation for self-referential reassignment patterns like:
1836
+ // x = x.method().functionCallReturnValue
1837
+ // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1838
+ // These create circular references since both sides reference the same variable.
1839
+ //
1840
+ // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1841
+ // where the path has additional segments beyond the root variable.
1842
+ const pathIsJustRootVariable = path === rootVariable;
1843
+ const isSelfReferentialReassignment =
1844
+ pathIsJustRootVariable && rootVariable === equivalentRootVariable;
1756
1845
 
1757
- if (
1758
- rootVariable &&
1759
- !isSelfReferentialReassignment &&
1760
- scopeNode.parentInstantiatedVariables?.includes(rootVariable)
1761
- ) {
1762
- // Find the parent scope where this variable is defined
1763
- for (const parentScopeName of scopeNode.tree || []) {
1764
- const parentScope = this.scopeNodes[parentScopeName];
1765
- if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1766
- // Add the equivalency to the parent scope as well
1767
- this.addEquivalency(
1768
- path,
1769
- equivalentValue,
1770
- scopeNode.name, // The equivalent path's scope remains the child scope
1771
- parentScope, // But store it in the parent scope's equivalencies
1772
- 'propagated parent-variable equivalency',
1773
- );
1774
- break;
1846
+ if (
1847
+ rootVariable &&
1848
+ !isSelfReferentialReassignment &&
1849
+ scopeNode.parentInstantiatedVariables?.includes(rootVariable)
1850
+ ) {
1851
+ // Find the parent scope where this variable is defined
1852
+ for (const parentScopeName of scopeNode.tree || []) {
1853
+ const parentScope = this.scopeNodes[parentScopeName];
1854
+ if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1855
+ // Add the equivalency to the parent scope as well
1856
+ this.addEquivalency(
1857
+ path,
1858
+ equivalentValue,
1859
+ scopeNode.name, // The equivalent path's scope remains the child scope
1860
+ parentScope, // But store it in the parent scope's equivalencies
1861
+ 'propagated parent-variable equivalency',
1862
+ );
1863
+ break;
1864
+ }
1775
1865
  }
1776
1866
  }
1777
- }
1778
1867
 
1779
- // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1780
- // that has sub-properties defined in the isolatedEquivalentVariables.
1781
- // This handles cases like: dataItem={{ structure: completeDataStructure }}
1782
- // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1783
- // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1784
- const isSimpleVariable =
1785
- !equivalentValue.startsWith('signature[') &&
1786
- !equivalentValue.includes('functionCallReturnValue') &&
1787
- !equivalentValue.includes('.') &&
1788
- !equivalentValue.includes('[');
1789
-
1790
- if (isSimpleVariable) {
1791
- // Look in current scope and all parent scopes for sub-properties
1792
- const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1793
- for (const scopeName of scopesToCheck) {
1794
- const checkScope = this.scopeNodes[scopeName];
1795
- if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1796
-
1797
- for (const [subPath, subValue] of Object.entries(
1798
- checkScope.analysis.isolatedEquivalentVariables,
1799
- )) {
1800
- // Check if this is a sub-property of the equivalentValue variable
1801
- // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1802
- const matchesDot = subPath.startsWith(equivalentValue + '.');
1803
- const matchesBracket = subPath.startsWith(equivalentValue + '[');
1804
- if (matchesDot || matchesBracket) {
1805
- const subPropertyPath = subPath.substring(
1806
- equivalentValue.length,
1807
- );
1808
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1809
- const newEquivalentValue = cleanPath(
1810
- (subValue as string).replace(/::cyDuplicateKey\d+::/g, ''),
1811
- allPaths,
1868
+ // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1869
+ // that has sub-properties defined in the isolatedEquivalentVariables.
1870
+ // This handles cases like: dataItem={{ structure: completeDataStructure }}
1871
+ // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1872
+ // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1873
+ const isSimpleVariable =
1874
+ !equivalentValue.startsWith('signature[') &&
1875
+ !equivalentValue.includes('functionCallReturnValue') &&
1876
+ !equivalentValue.includes('.') &&
1877
+ !equivalentValue.includes('[');
1878
+
1879
+ if (isSimpleVariable) {
1880
+ // Look in current scope and all parent scopes for sub-properties
1881
+ const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1882
+ for (const scopeName of scopesToCheck) {
1883
+ const checkScope = this.scopeNodes[scopeName];
1884
+ if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1885
+
1886
+ for (const [subPath, rawSubValue] of Object.entries(
1887
+ checkScope.analysis.isolatedEquivalentVariables,
1888
+ )) {
1889
+ // Normalize to array for consistent handling
1890
+ const subValues = Array.isArray(rawSubValue)
1891
+ ? rawSubValue
1892
+ : rawSubValue
1893
+ ? [rawSubValue]
1894
+ : [];
1895
+
1896
+ // Check if this is a sub-property of the equivalentValue variable
1897
+ // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1898
+ const matchesDot = subPath.startsWith(equivalentValue + '.');
1899
+ const matchesBracket = subPath.startsWith(
1900
+ equivalentValue + '[',
1812
1901
  );
1813
-
1814
- if (
1815
- newEquivalentValue &&
1816
- this.isValidPath(newEquivalentValue)
1817
- ) {
1818
- this.addEquivalency(
1819
- newPath,
1820
- newEquivalentValue,
1821
- checkScope.name, // Use the scope where the sub-property was found
1822
- scopeNode,
1823
- 'propagated sub-property equivalency',
1902
+ if (matchesDot || matchesBracket) {
1903
+ const subPropertyPath = subPath.substring(
1904
+ equivalentValue.length,
1824
1905
  );
1906
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
1907
+
1908
+ for (const subValue of subValues) {
1909
+ if (typeof subValue !== 'string') continue;
1910
+ const newEquivalentValue = cleanPath(
1911
+ subValue.replace(/::cyDuplicateKey\d+::/g, ''),
1912
+ allPaths,
1913
+ );
1914
+
1915
+ if (
1916
+ newEquivalentValue &&
1917
+ this.isValidPath(newEquivalentValue)
1918
+ ) {
1919
+ this.addEquivalency(
1920
+ newPath,
1921
+ newEquivalentValue,
1922
+ checkScope.name, // Use the scope where the sub-property was found
1923
+ scopeNode,
1924
+ 'propagated sub-property equivalency',
1925
+ );
1926
+ }
1927
+ }
1825
1928
  }
1826
- }
1827
1929
 
1828
- // Also check if equivalentValue itself maps to a functionCallReturnValue
1829
- // e.g., result = useMemo(...).functionCallReturnValue
1830
- if (
1831
- subPath === equivalentValue &&
1832
- typeof subValue === 'string' &&
1833
- subValue.endsWith('.functionCallReturnValue')
1834
- ) {
1835
- this.propagateFunctionCallReturnSubProperties(
1836
- path,
1837
- subValue,
1838
- scopeNode,
1839
- allPaths,
1840
- );
1930
+ // Also check if equivalentValue itself maps to a functionCallReturnValue
1931
+ // e.g., result = useMemo(...).functionCallReturnValue
1932
+ for (const subValue of subValues) {
1933
+ if (
1934
+ subPath === equivalentValue &&
1935
+ typeof subValue === 'string' &&
1936
+ subValue.endsWith('.functionCallReturnValue')
1937
+ ) {
1938
+ this.propagateFunctionCallReturnSubProperties(
1939
+ path,
1940
+ subValue,
1941
+ scopeNode,
1942
+ allPaths,
1943
+ );
1944
+ }
1945
+ }
1841
1946
  }
1842
1947
  }
1843
1948
  }
1844
- }
1845
1949
 
1846
- // Handle function call return values by propagating returnValue.* sub-properties
1847
- // from the callback scope to the usage path
1848
- if (equivalentValue.endsWith('.functionCallReturnValue')) {
1849
- this.propagateFunctionCallReturnSubProperties(
1850
- path,
1851
- equivalentValue,
1852
- scopeNode,
1853
- allPaths,
1854
- );
1950
+ // Handle function call return values by propagating returnValue.* sub-properties
1951
+ // from the callback scope to the usage path
1952
+ if (equivalentValue.endsWith('.functionCallReturnValue')) {
1953
+ this.propagateFunctionCallReturnSubProperties(
1954
+ path,
1955
+ equivalentValue,
1956
+ scopeNode,
1957
+ allPaths,
1958
+ );
1855
1959
 
1856
- // Track which variable receives the return value of each function call
1857
- // This enables generating separate mock data for each call site
1858
- this.trackReceivingVariable(path, equivalentValue);
1859
- }
1960
+ // Track which variable receives the return value of each function call
1961
+ // This enables generating separate mock data for each call site
1962
+ this.trackReceivingVariable(path, equivalentValue);
1963
+ }
1860
1964
 
1861
- // Also track variables that receive destructured properties from function call return values
1862
- // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1863
- if (equivalentValue.includes('.functionCallReturnValue.')) {
1864
- this.trackReceivingVariable(path, equivalentValue);
1965
+ // Also track variables that receive destructured properties from function call return values
1966
+ // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1967
+ if (equivalentValue.includes('.functionCallReturnValue.')) {
1968
+ this.trackReceivingVariable(path, equivalentValue);
1969
+ }
1865
1970
  }
1866
1971
  }
1867
1972
  }
@@ -2042,9 +2147,18 @@ export class ScopeDataStructure {
2042
2147
  const checkScope = this.scopeNodes[scopeName];
2043
2148
  if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
2044
2149
 
2045
- const functionRef =
2150
+ const rawFunctionRef =
2046
2151
  checkScope.analysis.isolatedEquivalentVariables[functionName];
2047
- if (typeof functionRef === 'string' && functionRef.endsWith('F')) {
2152
+ // Normalize to array and find first string ending with 'F'
2153
+ const functionRefs = Array.isArray(rawFunctionRef)
2154
+ ? rawFunctionRef
2155
+ : rawFunctionRef
2156
+ ? [rawFunctionRef]
2157
+ : [];
2158
+ const functionRef = functionRefs.find(
2159
+ (r) => typeof r === 'string' && r.endsWith('F'),
2160
+ );
2161
+ if (typeof functionRef === 'string') {
2048
2162
  callbackScopeName = functionRef.slice(0, -1);
2049
2163
  break;
2050
2164
  }
@@ -2072,19 +2186,24 @@ export class ScopeDataStructure {
2072
2186
 
2073
2187
  const isolatedVars = callbackScope.analysis.isolatedEquivalentVariables;
2074
2188
 
2189
+ // Get the first returnValue equivalency (normalize array to single value for these checks)
2190
+ const rawReturnValue = isolatedVars.returnValue;
2191
+ const firstReturnValue = Array.isArray(rawReturnValue)
2192
+ ? rawReturnValue[0]
2193
+ : rawReturnValue;
2194
+
2075
2195
  // First, check if returnValue is an alias to another variable (e.g., returnValue = intermediate)
2076
2196
  // If so, we need to look for that variable's sub-properties too
2077
2197
  const returnValueAlias =
2078
- typeof isolatedVars.returnValue === 'string' &&
2079
- !isolatedVars.returnValue.includes('.')
2080
- ? isolatedVars.returnValue
2198
+ typeof firstReturnValue === 'string' && !firstReturnValue.includes('.')
2199
+ ? firstReturnValue
2081
2200
  : undefined;
2082
2201
 
2083
2202
  // Pattern 3: Object.keys(X).reduce() - the reduce result has the same sub-properties as X
2084
2203
  // When returnValue = "Object.keys(source).reduce(...).functionCallReturnValue", look for source.* sub-properties
2085
2204
  let reduceSourceVar: string | undefined;
2086
- if (typeof isolatedVars.returnValue === 'string') {
2087
- const reduceMatch = isolatedVars.returnValue.match(
2205
+ if (typeof firstReturnValue === 'string') {
2206
+ const reduceMatch = firstReturnValue.match(
2088
2207
  /^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/,
2089
2208
  );
2090
2209
  if (reduceMatch) {
@@ -2092,7 +2211,14 @@ export class ScopeDataStructure {
2092
2211
  }
2093
2212
  }
2094
2213
 
2095
- for (const [subPath, subValue] of Object.entries(isolatedVars)) {
2214
+ for (const [subPath, rawSubValue] of Object.entries(isolatedVars)) {
2215
+ // Normalize to array for consistent handling
2216
+ const subValues = Array.isArray(rawSubValue)
2217
+ ? rawSubValue
2218
+ : rawSubValue
2219
+ ? [rawSubValue]
2220
+ : [];
2221
+
2096
2222
  // Check for direct returnValue.* sub-properties
2097
2223
  const isReturnValueSub =
2098
2224
  subPath.startsWith('returnValue.') ||
@@ -2110,57 +2236,59 @@ export class ScopeDataStructure {
2110
2236
  (subPath.startsWith(reduceSourceVar + '.') ||
2111
2237
  subPath.startsWith(reduceSourceVar + '['));
2112
2238
 
2113
- if (
2114
- typeof subValue !== 'string' ||
2115
- (!isReturnValueSub && !isAliasSub && !isReduceSourceSub)
2116
- )
2117
- continue;
2118
-
2119
- // Convert alias/reduceSource paths to returnValue paths
2120
- let effectiveSubPath = subPath;
2121
- if (isAliasSub && !isReturnValueSub) {
2122
- // Replace the alias prefix with returnValue
2123
- effectiveSubPath =
2124
- 'returnValue' + subPath.substring(returnValueAlias!.length);
2125
- } else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
2126
- // Replace the reduce source prefix with returnValue
2127
- effectiveSubPath =
2128
- 'returnValue' + subPath.substring(reduceSourceVar!.length);
2129
- }
2130
- const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
2131
- const newPath = cleanPath(path + subPropertyPath, allPaths);
2132
- let newEquivalentValue = cleanPath(
2133
- subValue.replace(/::cyDuplicateKey\d+::/g, ''),
2134
- allPaths,
2135
- );
2239
+ if (!isReturnValueSub && !isAliasSub && !isReduceSourceSub) continue;
2240
+
2241
+ for (const subValue of subValues) {
2242
+ if (typeof subValue !== 'string') continue;
2243
+
2244
+ // Convert alias/reduceSource paths to returnValue paths
2245
+ let effectiveSubPath = subPath;
2246
+ if (isAliasSub && !isReturnValueSub) {
2247
+ // Replace the alias prefix with returnValue
2248
+ effectiveSubPath =
2249
+ 'returnValue' + subPath.substring(returnValueAlias!.length);
2250
+ } else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
2251
+ // Replace the reduce source prefix with returnValue
2252
+ effectiveSubPath =
2253
+ 'returnValue' + subPath.substring(reduceSourceVar!.length);
2254
+ }
2255
+ const subPropertyPath = effectiveSubPath.substring(
2256
+ 'returnValue'.length,
2257
+ );
2258
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
2259
+ let newEquivalentValue = cleanPath(
2260
+ subValue.replace(/::cyDuplicateKey\d+::/g, ''),
2261
+ allPaths,
2262
+ );
2136
2263
 
2137
- // Resolve variable references through parent scope equivalencies
2138
- const resolved = this.resolveVariableThroughParentScopes(
2139
- newEquivalentValue,
2140
- callbackScope,
2141
- allPaths,
2142
- );
2143
- newEquivalentValue = resolved.resolvedPath;
2144
- const equivalentScopeName = resolved.scopeName;
2264
+ // Resolve variable references through parent scope equivalencies
2265
+ const resolved = this.resolveVariableThroughParentScopes(
2266
+ newEquivalentValue,
2267
+ callbackScope,
2268
+ allPaths,
2269
+ );
2270
+ newEquivalentValue = resolved.resolvedPath;
2271
+ const equivalentScopeName = resolved.scopeName;
2145
2272
 
2146
- if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
2147
- continue;
2273
+ if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
2274
+ continue;
2148
2275
 
2149
- this.addEquivalency(
2150
- newPath,
2151
- newEquivalentValue,
2152
- equivalentScopeName,
2153
- scopeNode,
2154
- 'propagated function call return sub-property equivalency',
2155
- );
2276
+ this.addEquivalency(
2277
+ newPath,
2278
+ newEquivalentValue,
2279
+ equivalentScopeName,
2280
+ scopeNode,
2281
+ 'propagated function call return sub-property equivalency',
2282
+ );
2156
2283
 
2157
- // Ensure the database entry has the usage path
2158
- this.addUsageToEquivalencyDatabaseEntry(
2159
- newPath,
2160
- newEquivalentValue,
2161
- equivalentScopeName,
2162
- scopeNode.name,
2163
- );
2284
+ // Ensure the database entry has the usage path
2285
+ this.addUsageToEquivalencyDatabaseEntry(
2286
+ newPath,
2287
+ newEquivalentValue,
2288
+ equivalentScopeName,
2289
+ scopeNode.name,
2290
+ );
2291
+ }
2164
2292
  }
2165
2293
  }
2166
2294
 
@@ -2200,8 +2328,15 @@ export class ScopeDataStructure {
2200
2328
  const parentScope = this.scopeNodes[parentScopeName];
2201
2329
  if (!parentScope?.analysis?.isolatedEquivalentVariables) continue;
2202
2330
 
2203
- const rootEquiv =
2331
+ const rawRootEquiv =
2204
2332
  parentScope.analysis.isolatedEquivalentVariables[rootVar];
2333
+ // Normalize to array and use first string value
2334
+ const rootEquivs = Array.isArray(rawRootEquiv)
2335
+ ? rawRootEquiv
2336
+ : rawRootEquiv
2337
+ ? [rawRootEquiv]
2338
+ : [];
2339
+ const rootEquiv = rootEquivs.find((r) => typeof r === 'string');
2205
2340
  if (typeof rootEquiv === 'string') {
2206
2341
  return {
2207
2342
  resolvedPath: cleanPath(rootEquiv + restOfPath, allPaths),
@@ -2476,6 +2611,7 @@ export class ScopeDataStructure {
2476
2611
  relevantSubPathParts.every((part, i) => part === schemaPathParts[i]) &&
2477
2612
  equivalentValue.scopeNodeName === scopeNode.name
2478
2613
  ) {
2614
+ // DEBUG
2479
2615
  continue;
2480
2616
  }
2481
2617
 
@@ -2662,6 +2798,8 @@ export class ScopeDataStructure {
2662
2798
  usageEquivalency.scopeNodeName,
2663
2799
  ) as ScopeNode;
2664
2800
 
2801
+ if (!usageScopeNode) continue;
2802
+
2665
2803
  // Guard against infinite recursion by tracking which paths we've already
2666
2804
  // added from addComplexSourcePathVariables
2667
2805
  if (
@@ -2741,6 +2879,8 @@ export class ScopeDataStructure {
2741
2879
  usageEquivalency.scopeNodeName,
2742
2880
  ) as ScopeNode;
2743
2881
 
2882
+ if (!usageScopeNode) continue;
2883
+
2744
2884
  // This is put in place to avoid propagating array functions like 'filter' through complex equivalencies
2745
2885
  // but may cause problems if the funtion call is not on a known object (e.g. string or array)
2746
2886
  if (
@@ -2867,10 +3007,105 @@ export class ScopeDataStructure {
2867
3007
  this.intermediatesOrderIndex.set(pathId, databaseEntry);
2868
3008
 
2869
3009
  if (intermediateIndex === 0) {
2870
- const isValidSourceCandidate =
3010
+ let isValidSourceCandidate =
2871
3011
  pathInfo.schemaPath.startsWith('signature[') ||
2872
3012
  pathInfo.schemaPath.includes('functionCallReturnValue');
2873
- if (isValidSourceCandidate) {
3013
+
3014
+ // Check if path STARTS with a spread pattern like [...var]
3015
+ // This handles cases like [...files][][0] or [...files].sort(...).functionCallReturnValue[][0]
3016
+ // where the spread source variable needs to be resolved to a signature path.
3017
+ // We do this REGARDLESS of isValidSourceCandidate because even paths containing
3018
+ // functionCallReturnValue may need spread resolution to trace back to the signature.
3019
+ const spreadMatch = pathInfo.schemaPath.match(/^\[\.\.\.(\w+)\]/);
3020
+ if (spreadMatch) {
3021
+ const spreadVar = spreadMatch[1];
3022
+ const spreadPattern = spreadMatch[0]; // The full [...var] match
3023
+ const scopeNode = this.scopeNodes[pathInfo.scopeNodeName];
3024
+
3025
+ if (scopeNode?.equivalencies) {
3026
+ // Follow the equivalency chain to find a signature path
3027
+ // e.g., files (cyScope1) → files (root) → signature[0].files
3028
+ const resolveToSignature = (
3029
+ varName: string,
3030
+ currentScopeName: string,
3031
+ visited: Set<string>,
3032
+ ): { schemaPath: string; scopeNodeName: string } | null => {
3033
+ const visitKey = `${currentScopeName}::${varName}`;
3034
+ if (visited.has(visitKey)) return null;
3035
+ visited.add(visitKey);
3036
+
3037
+ const currentScope = this.scopeNodes[currentScopeName];
3038
+ if (!currentScope?.equivalencies) return null;
3039
+
3040
+ const varEquivs = currentScope.equivalencies[varName];
3041
+ if (!varEquivs) return null;
3042
+
3043
+ // First check if any equivalency directly points to a signature path
3044
+ const signatureEquiv = varEquivs.find((eq) =>
3045
+ eq.schemaPath.startsWith('signature['),
3046
+ );
3047
+ if (signatureEquiv) {
3048
+ return signatureEquiv;
3049
+ }
3050
+
3051
+ // Otherwise, follow the chain to other scopes
3052
+ for (const equiv of varEquivs) {
3053
+ // If the equivalency points to the same variable in a different scope,
3054
+ // follow the chain
3055
+ if (
3056
+ equiv.schemaPath === varName &&
3057
+ equiv.scopeNodeName !== currentScopeName
3058
+ ) {
3059
+ const result = resolveToSignature(
3060
+ varName,
3061
+ equiv.scopeNodeName,
3062
+ visited,
3063
+ );
3064
+ if (result) return result;
3065
+ }
3066
+ }
3067
+
3068
+ return null;
3069
+ };
3070
+
3071
+ const signatureEquiv = resolveToSignature(
3072
+ spreadVar,
3073
+ pathInfo.scopeNodeName,
3074
+ new Set(),
3075
+ );
3076
+ if (signatureEquiv) {
3077
+ // Replace ONLY the [...var] part with the resolved signature path
3078
+ // This preserves any suffix like .sort(...).functionCallReturnValue[][0]
3079
+ const resolvedPath = pathInfo.schemaPath.replace(
3080
+ spreadPattern,
3081
+ signatureEquiv.schemaPath,
3082
+ );
3083
+ // Add the resolved path as a source candidate
3084
+ if (
3085
+ !databaseEntry.sourceCandidates.some(
3086
+ (sc) =>
3087
+ sc.schemaPath === resolvedPath &&
3088
+ sc.scopeNodeName === pathInfo.scopeNodeName,
3089
+ )
3090
+ ) {
3091
+ databaseEntry.sourceCandidates.push({
3092
+ scopeNodeName: pathInfo.scopeNodeName,
3093
+ schemaPath: resolvedPath,
3094
+ });
3095
+ }
3096
+ isValidSourceCandidate = true;
3097
+ }
3098
+ }
3099
+ }
3100
+
3101
+ if (
3102
+ isValidSourceCandidate &&
3103
+ !databaseEntry.sourceCandidates.some(
3104
+ (sc) =>
3105
+ sc.schemaPath === pathInfo.schemaPath &&
3106
+ sc.scopeNodeName === pathInfo.scopeNodeName,
3107
+ )
3108
+ ) {
2874
3109
  databaseEntry.sourceCandidates.push(pathInfo);
2875
3110
  }
2876
3111
  } else {
@@ -3098,6 +3333,14 @@ export class ScopeDataStructure {
3098
3333
  }
3099
3334
  }
3100
3335
 
3336
+ // Ensure parameter-to-signature equivalencies are fully propagated.
3337
+ // When a parameter variable (e.g., `node`) is equivalenced to `signature[N]`,
3338
+ // all sub-paths of that variable should also appear under `signature[N]`.
3339
+ // This handles cases where the sub-path was added to the schema via a propagation
3340
+ // chain that already included the variable↔signature equivalency, causing the
3341
+ // cycle detection to prevent the reverse mapping.
3342
+ this.propagateParameterToSignaturePaths(scopeNode);
3343
+
3101
3344
  fillInSchemaGapsAndUnknowns(scopeNode, fillInUnknowns);
3102
3345
 
3103
3346
  if (final) {
@@ -3112,6 +3355,97 @@ export class ScopeDataStructure {
3112
3355
  }
3113
3356
  }
3114
3357
 
3358
+ /**
3359
+ * For each equivalency where a simple variable maps to signature[N],
3360
+ * ensure all sub-paths of that variable are reflected under signature[N].
3361
+ */
3362
+ private propagateParameterToSignaturePaths(scopeNode: ScopeNode) {
3363
+ // Helper: check if a type is a concrete scalar that cannot have sub-properties.
3364
+ const SCALAR_TYPES = new Set([
3365
+ 'string',
3366
+ 'number',
3367
+ 'boolean',
3368
+ 'bigint',
3369
+ 'symbol',
3370
+ 'void',
3371
+ 'never',
3372
+ ]);
3373
+ const isDefinitelyScalar = (type: string): boolean => {
3374
+ const parts = type.split('|').map((s) => s.trim());
3375
+ const base = parts.filter((s) => s !== 'undefined' && s !== 'null');
3376
+ return base.length > 0 && base.every((b) => SCALAR_TYPES.has(b));
3377
+ };
3378
+
3379
+ // Find variable → signature[N] equivalencies
3380
+ for (const [varName, equivalencies] of Object.entries(
3381
+ scopeNode.equivalencies,
3382
+ )) {
3383
+ // Only process simple variable names (no dots, brackets, or parens)
3384
+ if (
3385
+ varName.includes('.') ||
3386
+ varName.includes('[') ||
3387
+ varName.includes('(')
3388
+ ) {
3389
+ continue;
3390
+ }
3391
+
3392
+ for (const equiv of equivalencies) {
3393
+ if (
3394
+ equiv.scopeNodeName === scopeNode.name &&
3395
+ equiv.schemaPath.startsWith('signature[')
3396
+ ) {
3397
+ const signaturePath = equiv.schemaPath;
3398
+ const varPrefix = varName + '.';
3399
+ const varBracketPrefix = varName + '[';
3400
+
3401
+ // Find all schema keys starting with the variable
3402
+ for (const key in scopeNode.schema) {
3403
+ if (key.startsWith(varPrefix) || key.startsWith(varBracketPrefix)) {
3404
+ const suffix = key.slice(varName.length);
3405
+ const sigKey = signaturePath + suffix;
3406
+
3407
+ // Only add if the signature path doesn't already exist
3408
+ if (!scopeNode.schema[sigKey]) {
3409
+ // Check if this path represents variable conflation:
3410
+ // When a standalone variable (e.g., showWorkoutForm from useState)
3411
+ // appears as a sub-property of a scalar-typed ancestor (e.g.,
3412
+ // activity_type = "string"), it's from scope conflation, not real
3413
+ // property access. Block these while allowing legitimate built-in
3414
+ // accesses like string.length or string.slice.
3415
+ let isConflatedPath = false;
3416
+ let checkPos = signaturePath.length;
3417
+ while (true) {
3418
+ checkPos = sigKey.indexOf('.', checkPos + 1);
3419
+ if (checkPos === -1) break;
3420
+ const ancestorPath = sigKey.substring(0, checkPos);
3421
+ const ancestorType = scopeNode.schema[ancestorPath];
3422
+ if (ancestorType && isDefinitelyScalar(ancestorType)) {
3423
+ // Ancestor is scalar — check if the immediate sub-property
3424
+ // is also a standalone variable (indicating conflation)
3425
+ const afterDot = sigKey.substring(checkPos + 1);
3426
+ const nextSep = afterDot.search(/[.\[]/);
3427
+ const subPropName =
3428
+ nextSep === -1
3429
+ ? afterDot
3430
+ : afterDot.substring(0, nextSep);
3431
+ if (scopeNode.schema[subPropName] !== undefined) {
3432
+ isConflatedPath = true;
3433
+ break;
3434
+ }
3435
+ }
3436
+ }
3437
+
3438
+ if (!isConflatedPath) {
3439
+ scopeNode.schema[sigKey] = scopeNode.schema[key];
3440
+ }
3441
+ }
3442
+ }
3443
+ }
3444
+ }
3445
+ }
3446
+ }
3447
+ }
3448
+
3115
3449
  private filterAndConvertSchema({
3116
3450
  filterPath,
3117
3451
  newPath,
@@ -3198,6 +3532,9 @@ export class ScopeDataStructure {
3198
3532
  equivalentValueSchemaPathParts.length,
3199
3533
  ),
3200
3534
  ]);
3535
+ // PERF: Skip keys with repeated function-call signature patterns
3536
+ // to prevent recursive type expansion (e.g., string.localeCompare returns string)
3537
+ if (this.hasExcessivePatternRepetition(newKey)) continue;
3201
3538
  resolvedSchema[newKey] = value;
3202
3539
  }
3203
3540
  }
@@ -3220,6 +3557,8 @@ export class ScopeDataStructure {
3220
3557
  if (!subSchema) continue;
3221
3558
 
3222
3559
  for (const resolvedKey in subSchema) {
3560
+ // PERF: Skip keys with repeated function-call signature patterns
3561
+ if (this.hasExcessivePatternRepetition(resolvedKey)) continue;
3223
3562
  if (
3224
3563
  !resolvedSchema[resolvedKey] ||
3225
3564
  subSchema[resolvedKey] === 'unknown'
@@ -3457,26 +3796,270 @@ export class ScopeDataStructure {
3457
3796
  return {};
3458
3797
  }
3459
3798
 
3799
+ // Collect all descendant scope names (including the scope itself)
3800
+ // This ensures we include external calls from nested scopes like cyScope2
3801
+ const getAllDescendantScopeNames = (
3802
+ node: import('./helpers/ScopeTreeManager').ScopeTreeNode,
3803
+ ): Set<string> => {
3804
+ const names = new Set<string>([node.name]);
3805
+ for (const child of node.children) {
3806
+ for (const name of getAllDescendantScopeNames(child)) {
3807
+ names.add(name);
3808
+ }
3809
+ }
3810
+ return names;
3811
+ };
3812
+
3813
+ const treeNode = this.scopeTreeManager.findNode(scopeNode.name);
3814
+ const descendantScopeNames = treeNode
3815
+ ? getAllDescendantScopeNames(treeNode)
3816
+ : new Set<string>([scopeNode.name]);
3817
+
3818
+ // Get all external function calls made from this scope or any descendant scope
3819
+ // This allows us to include prop equivalencies from JSX components
3820
+ // that were rendered in nested scopes (e.g., FileTableRow called from cyScope2)
3821
+ const externalCallsFromScope = this.externalFunctionCalls.filter((efc) =>
3822
+ descendantScopeNames.has(efc.callScope),
3823
+ );
3824
+ const externalCallNames = new Set(
3825
+ externalCallsFromScope.map((efc) => efc.name),
3826
+ );
3827
+
3828
+ // Helper to check if a usage belongs to this scope (directly, via descendant, or via external call)
3829
+ const usageMatchesScope = (usage: { scopeNodeName: string }) =>
3830
+ descendantScopeNames.has(usage.scopeNodeName) ||
3831
+ externalCallNames.has(usage.scopeNodeName);
3832
+
3460
3833
  const entries = this.equivalencyDatabase.filter((entry) =>
3461
- entry.usages.some((usage) => usage.scopeNodeName === scopeNode.name),
3834
+ entry.usages.some(usageMatchesScope),
3462
3835
  );
3463
- return entries.reduce(
3464
- (acc, entry) => {
3465
- if (entry.sourceCandidates.length === 0) return acc;
3466
- const usages = entry.usages.filter(
3467
- (u) => u.scopeNodeName === scopeNode.name,
3468
- );
3836
+
3837
+ // Helper to resolve a source candidate through equivalency chains to find signature paths
3838
+ const resolveToSignature = (
3839
+ source: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>,
3840
+ visited: Set<string>,
3841
+ ): Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] => {
3842
+ const visitKey = `${source.scopeNodeName}::${source.schemaPath}`;
3843
+ if (visited.has(visitKey)) return [];
3844
+ visited.add(visitKey);
3845
+
3846
+ // If already a signature path, return as-is
3847
+ if (source.schemaPath.startsWith('signature[')) {
3848
+ return [source];
3849
+ }
3850
+
3851
+ const currentScope = this.scopeNodes[source.scopeNodeName];
3852
+ if (!currentScope?.equivalencies) return [source];
3853
+
3854
+ // Check for direct equivalencies FIRST (full path match)
3855
+ // This ensures paths like "useMemo(...).functionCallReturnValue" follow to "cyScope1::returnValue"
3856
+ // before prefix matching tries "useMemo(...)" which goes to the useMemo scope
3857
+ const directEquivs = currentScope.equivalencies[source.schemaPath];
3858
+ if (directEquivs?.length > 0) {
3859
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3860
+ [];
3861
+ for (const equiv of directEquivs) {
3862
+ const resolved = resolveToSignature(
3863
+ {
3864
+ scopeNodeName: equiv.scopeNodeName,
3865
+ schemaPath: equiv.schemaPath,
3866
+ },
3867
+ visited,
3868
+ );
3869
+ results.push(...resolved);
3870
+ }
3871
+ if (results.length > 0) return results;
3872
+ }
3873
+
3874
+ // Handle spread patterns like [...items].sort().functionCallReturnValue
3875
+ // Extract the spread variable and resolve it through the equivalency chain
3876
+ const spreadMatch = source.schemaPath.match(/^\[\.\.\.(\w+)\]/);
3877
+ if (spreadMatch) {
3878
+ const spreadVar = spreadMatch[1];
3879
+ const spreadPattern = spreadMatch[0];
3880
+ const varEquivs = currentScope.equivalencies[spreadVar];
3881
+
3882
+ if (varEquivs?.length > 0) {
3883
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3884
+ [];
3885
+ for (const equiv of varEquivs) {
3886
+ // Follow the variable equivalency and then resolve from there
3887
+ const resolvedVar = resolveToSignature(
3888
+ {
3889
+ scopeNodeName: equiv.scopeNodeName,
3890
+ schemaPath: equiv.schemaPath,
3891
+ },
3892
+ visited,
3893
+ );
3894
+ // For each resolved variable path, create the full path with array element suffix
3895
+ for (const rv of resolvedVar) {
3896
+ if (rv.schemaPath.startsWith('signature[')) {
3897
+ // Get the suffix after the spread pattern
3898
+ let suffix = source.schemaPath.slice(spreadPattern.length);
3899
+
3900
+ // Clean the suffix: strip array method chains like .sort(...).functionCallReturnValue[]
3901
+ // These don't change the data identity, just transform it.
3902
+ // Keep only the final element access parts like [0], [1], etc.
3903
+ // Pattern: strip everything from a method call up through functionCallReturnValue[]
3904
+ suffix = suffix.replace(
3905
+ /\.\w+\([^)]*\)\.functionCallReturnValue\[\]/g,
3906
+ '',
3907
+ );
3908
+ // Also handle simpler case without nested parens
3909
+ suffix = suffix.replace(
3910
+ /\.sort\(\w*\(\)\)\.functionCallReturnValue\[\]/g,
3911
+ '',
3912
+ );
3913
+
3914
+ // Add [] to indicate array element access from the spread
3915
+ const resolvedPath = rv.schemaPath + '[]' + suffix;
3916
+ results.push({
3917
+ scopeNodeName: rv.scopeNodeName,
3918
+ schemaPath: resolvedPath,
3919
+ });
3920
+ }
3921
+ }
3922
+ }
3923
+ if (results.length > 0) return results;
3924
+ }
3925
+ }
3926
+
3927
+ // Try to find prefix equivalencies that can resolve this path
3928
+ // For path like "cyScope3().signature[0][0]", check "cyScope3().signature[0]", etc.
3929
+ const pathParts = this.splitPath(source.schemaPath);
3930
+ for (let i = pathParts.length - 1; i > 0; i--) {
3931
+ const prefix = this.joinPathParts(pathParts.slice(0, i));
3932
+ const suffix = this.joinPathParts(pathParts.slice(i));
3933
+ const prefixEquivs = currentScope.equivalencies[prefix];
3934
+
3935
+ if (prefixEquivs?.length > 0) {
3936
+ const results: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[] =
3937
+ [];
3938
+ for (const equiv of prefixEquivs) {
3939
+ const newPath = this.joinPathParts([equiv.schemaPath, suffix]);
3940
+ const resolved = resolveToSignature(
3941
+ { scopeNodeName: equiv.scopeNodeName, schemaPath: newPath },
3942
+ visited,
3943
+ );
3944
+ results.push(...resolved);
3945
+ }
3946
+ if (results.length > 0) return results;
3947
+ }
3948
+ }
3949
+
3950
+ return [source];
3951
+ };
3952
+
3953
+ const acc = entries.reduce(
3954
+ (result, entry) => {
3955
+ if (entry.sourceCandidates.length === 0) return result;
3956
+ const usages = entry.usages.filter(usageMatchesScope);
3469
3957
  for (const usage of usages) {
3470
- acc[usage.schemaPath] ||= [];
3471
- acc[usage.schemaPath].push(...entry.sourceCandidates);
3958
+ result[usage.schemaPath] ||= [];
3959
+ // Resolve each source candidate through the equivalency chain
3960
+ for (const source of entry.sourceCandidates) {
3961
+ const resolvedSources = resolveToSignature(source, new Set());
3962
+ result[usage.schemaPath].push(...resolvedSources);
3963
+ }
3472
3964
  }
3473
- return acc;
3965
+ return result;
3474
3966
  },
3475
3967
  {} as Record<
3476
3968
  string,
3477
3969
  Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[]
3478
3970
  >,
3479
3971
  );
3972
+
3973
+ // Post-processing: enrich useState-backed sources with co-located external
3974
+ // function calls. When a useState value resolves to a setter variable that
3975
+ // lives in the same scope as a fetch/API call, that fetch is a data source.
3976
+ this.enrichUseStateSourcesWithCoLocatedCalls(acc);
3977
+
3978
+ return acc;
3979
+ }
3980
+
3981
+ /**
3982
+ * For each source that ends at a useState path, check if the setter was called
3983
+ * from a scope that also contains external function calls (like fetch).
3984
+ * If so, add those external calls as additional source candidates.
3985
+ */
3986
+ private enrichUseStateSourcesWithCoLocatedCalls(
3987
+ acc: Record<string, Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[]>,
3988
+ ) {
3989
+ const rootScopeName = this.scopeTreeManager.getRootName();
3990
+ const rootScope = this.scopeNodes[rootScopeName];
3991
+ if (!rootScope) return;
3992
+
3993
+ // Collect all descendants for each scope node
3994
+ const getAllDescendants = (
3995
+ node: import('./helpers/ScopeTreeManager').ScopeTreeNode,
3996
+ ): Set<string> => {
3997
+ const names = new Set<string>([node.name]);
3998
+ for (const child of node.children) {
3999
+ for (const name of getAllDescendants(child)) {
4000
+ names.add(name);
4001
+ }
4002
+ }
4003
+ return names;
4004
+ };
4005
+
4006
+ for (const [usagePath, sources] of Object.entries(acc)) {
4007
+ const additionalSources: Pick<
4008
+ ScopeVariable,
4009
+ 'scopeNodeName' | 'schemaPath'
4010
+ >[] = [];
4011
+
4012
+ for (const source of sources) {
4013
+ // Check if this source is a useState-related terminal path
4014
+ // (e.g., useState(X).functionCallReturnValue[1] or useState(X).signature[0])
4015
+ if (!source.schemaPath.match(/^useState\([^)]*\)\./)) continue;
4016
+
4017
+ // Find the useState call from the source path
4018
+ const useStateCallMatch = source.schemaPath.match(
4019
+ /^(useState\([^)]*\))\./,
4020
+ );
4021
+ if (!useStateCallMatch) continue;
4022
+ const useStateCall = useStateCallMatch[1];
4023
+
4024
+ // Look in the root scope for the useState value equivalency
4025
+ // which tells us where the setter was called from
4026
+ const valuePath = `${useStateCall}.functionCallReturnValue[0]`;
4027
+ const valueEquivs = rootScope.equivalencies[valuePath];
4028
+ if (!valueEquivs) continue;
4029
+
4030
+ for (const equiv of valueEquivs) {
4031
+ // Find the scope where the setter was called
4032
+ const setterScopeName = equiv.scopeNodeName;
4033
+ const setterScopeTree =
4034
+ this.scopeTreeManager.findNode(setterScopeName);
4035
+ if (!setterScopeTree) continue;
4036
+
4037
+ // Get all descendant scope names from the setter scope
4038
+ const relatedScopes = getAllDescendants(setterScopeTree);
4039
+
4040
+ // Find external function calls in those scopes whose return values
4041
+ // are actually consumed (assigned to a variable). This excludes
4042
+ // fire-and-forget calls like analytics.track() or console.log().
4043
+ const coLocatedCalls = this.externalFunctionCalls.filter(
4044
+ (efc) =>
4045
+ relatedScopes.has(efc.callScope) &&
4046
+ efc.receivingVariableNames &&
4047
+ efc.receivingVariableNames.length > 0,
4048
+ );
4049
+
4050
+ for (const call of coLocatedCalls) {
4051
+ additionalSources.push({
4052
+ scopeNodeName: call.callScope,
4053
+ schemaPath: `${call.callSignature}.functionCallReturnValue`,
4054
+ });
4055
+ }
4056
+ }
4057
+ }
4058
+
4059
+ if (additionalSources.length > 0) {
4060
+ acc[usagePath].push(...additionalSources);
4061
+ }
4062
+ }
3480
4063
  }
3481
4064
 
3482
4065
  getUsageEquivalencies(functionName?: string) {
@@ -3581,6 +4164,72 @@ export class ScopeDataStructure {
3581
4164
  }
3582
4165
  }
3583
4166
 
4167
+ // Enrich schema with deeply nested paths from internal function call scopes.
4168
+ // When a function call like traverse(tree) exists, and traverse's scope has
4169
+ // signature[0].children[path][entityName] (from propagateParameterToSignaturePaths),
4170
+ // we need to map those paths back to the argument variable (tree) in this scope.
4171
+ // This handles cases where cycle detection prevented the equivalency chain from
4172
+ // propagating deep paths during Phase 2 batch queue processing.
4173
+ for (const equivalenceKey in equivalencies ?? {}) {
4174
+ // Look for keys matching function call pattern: funcName(...).signature[N]
4175
+ const funcCallMatch = equivalenceKey.match(
4176
+ /^([^(]+)\(.*?\)\.(signature\[\d+\])$/,
4177
+ );
4178
+ if (!funcCallMatch) continue;
4179
+
4180
+ const calledFunctionName = funcCallMatch[1];
4181
+ const signatureParam = funcCallMatch[2]; // e.g., "signature[0]"
4182
+
4183
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
4184
+ if (equivalenceValue.scopeNodeName !== scopeName) continue;
4185
+
4186
+ const targetVariable = equivalenceValue.schemaPath;
4187
+
4188
+ // Get the called function's schema (includes propagated parameter paths)
4189
+ const childSchema = this.getSchema({
4190
+ scopeName: calledFunctionName,
4191
+ });
4192
+ if (!childSchema) continue;
4193
+
4194
+ // Map child function's signature paths to parent variable paths
4195
+ const sigPrefix = signatureParam + '.';
4196
+ const sigBracketPrefix = signatureParam + '[';
4197
+ for (const childKey in childSchema) {
4198
+ let suffix: string | null = null;
4199
+ if (childKey.startsWith(sigPrefix)) {
4200
+ suffix = childKey.slice(signatureParam.length);
4201
+ } else if (childKey.startsWith(sigBracketPrefix)) {
4202
+ suffix = childKey.slice(signatureParam.length);
4203
+ }
4204
+
4205
+ if (suffix !== null) {
4206
+ const parentKey = targetVariable + suffix;
4207
+ if (!schema[parentKey]) {
4208
+ schema[parentKey] = childSchema[childKey];
4209
+ }
4210
+ }
4211
+ }
4212
+ }
4213
+ }
4214
+
4215
+ // Helper: check if a type is a concrete scalar that cannot have sub-properties.
4216
+ // e.g., "string", "number | undefined", "boolean | null" are scalar.
4217
+ // "object", "array", "function", "unknown", "Workout", etc. are NOT scalar.
4218
+ const SCALAR_TYPES = new Set([
4219
+ 'string',
4220
+ 'number',
4221
+ 'boolean',
4222
+ 'bigint',
4223
+ 'symbol',
4224
+ 'void',
4225
+ 'never',
4226
+ ]);
4227
+ const isDefinitelyScalarType = (type: string): boolean => {
4228
+ const parts = type.split('|').map((s) => s.trim());
4229
+ const base = parts.filter((s) => s !== 'undefined' && s !== 'null');
4230
+ return base.length > 0 && base.every((b) => SCALAR_TYPES.has(b));
4231
+ };
4232
+
3584
4233
  // Propagate nested paths from variables to their signature equivalents
3585
4234
  // e.g., if workouts = signature[0].workouts, then workouts[].title becomes
3586
4235
  // signature[0].workouts[].title
@@ -3605,7 +4254,69 @@ export class ScopeDataStructure {
3605
4254
 
3606
4255
  // Add to schema if not already present
3607
4256
  if (!tempScopeNode.schema[signatureKey]) {
3608
- tempScopeNode.schema[signatureKey] = schema[schemaKey];
4257
+ // Check if this path represents variable conflation:
4258
+ // When a standalone variable (e.g., showWorkoutForm from useState)
4259
+ // appears as a sub-property of a scalar-typed ancestor (e.g.,
4260
+ // activity_type = "string"), it's from scope conflation, not real
4261
+ // property access. Block these while allowing legitimate built-in
4262
+ // accesses like string.length or string.slice.
4263
+ let isConflatedPath = false;
4264
+ let checkPos = signaturePath.length;
4265
+ while (true) {
4266
+ checkPos = signatureKey.indexOf('.', checkPos + 1);
4267
+ if (checkPos === -1) break;
4268
+ const ancestorPath = signatureKey.substring(0, checkPos);
4269
+ const ancestorType = tempScopeNode.schema[ancestorPath];
4270
+ if (ancestorType && isDefinitelyScalarType(ancestorType)) {
4271
+ // Ancestor is scalar — check if the immediate sub-property
4272
+ // is also a standalone variable (indicating conflation)
4273
+ const afterDot = signatureKey.substring(checkPos + 1);
4274
+ const nextSep = afterDot.search(/[.\[]/);
4275
+ const subPropName =
4276
+ nextSep === -1 ? afterDot : afterDot.substring(0, nextSep);
4277
+ if (schema[subPropName] !== undefined) {
4278
+ isConflatedPath = true;
4279
+ break;
4280
+ }
4281
+ }
4282
+ }
4283
+
4284
+ if (!isConflatedPath) {
4285
+ tempScopeNode.schema[signatureKey] = schema[schemaKey];
4286
+ }
4287
+ }
4288
+ }
4289
+ }
4290
+ }
4291
+
4292
+ // Post-process: filter out conflated signature paths.
4293
+ // During phase 2 scope analysis, useState(false) conflation can create
4294
+ // bad paths like signature[0].mockWorkouts[].activity_type.showWorkoutForm
4295
+ // directly in scopeNode.schema. These flow through signatureInSchema into
4296
+ // tempScopeNode.schema without any guard. Filter them out here by checking:
4297
+ // 1. An ancestor in the path has a concrete scalar type (string, number, boolean, etc.)
4298
+ // 2. The immediate sub-property of that scalar ancestor is also a standalone
4299
+ // variable in the schema (indicating conflation, not a real property access)
4300
+ for (const key of Object.keys(tempScopeNode.schema)) {
4301
+ if (!key.startsWith('signature[')) continue;
4302
+
4303
+ // Walk through the path looking for scalar-typed ancestors
4304
+ let pos = 0;
4305
+ while (true) {
4306
+ pos = key.indexOf('.', pos + 1);
4307
+ if (pos === -1) break;
4308
+ const ancestorPath = key.substring(0, pos);
4309
+ const ancestorType = tempScopeNode.schema[ancestorPath];
4310
+ if (ancestorType && isDefinitelyScalarType(ancestorType)) {
4311
+ // Found a scalar ancestor — check if the sub-property name
4312
+ // is a standalone variable in the getSchema() result
4313
+ const afterDot = key.substring(pos + 1);
4314
+ const nextSep = afterDot.search(/[.\[]/);
4315
+ const subPropName =
4316
+ nextSep === -1 ? afterDot : afterDot.substring(0, nextSep);
4317
+ if (schema[subPropName] !== undefined) {
4318
+ delete tempScopeNode.schema[key];
4319
+ break;
3609
4320
  }
3610
4321
  }
3611
4322
  }
@@ -3853,10 +4564,32 @@ export class ScopeDataStructure {
3853
4564
  return scopeText;
3854
4565
  }
3855
4566
 
3856
- getEquivalentSignatureVariables() {
4567
+ getEquivalentSignatureVariables(): Record<string, string | string[]> {
3857
4568
  const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
3858
4569
 
3859
- const equivalentSignatureVariables: Record<string, string> = {};
4570
+ const equivalentSignatureVariables: Record<string, string | string[]> = {};
4571
+
4572
+ // Helper to add equivalencies - accumulates into array if multiple values for same key
4573
+ // This is critical for OR expressions like `x = a || b` where x should map to both a and b
4574
+ const addEquivalency = (key: string, value: string) => {
4575
+ const existing = equivalentSignatureVariables[key];
4576
+ if (existing === undefined) {
4577
+ // First value - store as string
4578
+ equivalentSignatureVariables[key] = value;
4579
+ } else if (typeof existing === 'string') {
4580
+ if (existing !== value) {
4581
+ // Second different value - convert to array
4582
+ equivalentSignatureVariables[key] = [existing, value];
4583
+ }
4584
+ // Same value - no change needed
4585
+ } else {
4586
+ // Already an array - add if not already present
4587
+ if (!existing.includes(value)) {
4588
+ existing.push(value);
4589
+ }
4590
+ }
4591
+ };
4592
+
3860
4593
  for (const [path, equivalentValues] of Object.entries(
3861
4594
  scopeNode.equivalencies,
3862
4595
  )) {
@@ -3865,7 +4598,7 @@ export class ScopeDataStructure {
3865
4598
  // Maps local variable names to their signature paths
3866
4599
  // e.g., "propValue" -> "signature[0].prop"
3867
4600
  if (path.startsWith('signature[')) {
3868
- equivalentSignatureVariables[equivalentValue.schemaPath] = path;
4601
+ addEquivalency(equivalentValue.schemaPath, path);
3869
4602
  }
3870
4603
 
3871
4604
  // Case 2: Hook variable equivalencies (new behavior)
@@ -3876,14 +4609,30 @@ export class ScopeDataStructure {
3876
4609
  // "useFetcher<...>().state" for execution flow validation
3877
4610
  if (equivalentValue.schemaPath.endsWith('.functionCallReturnValue')) {
3878
4611
  // Extract the hook call path (everything before .functionCallReturnValue)
3879
- const hookCallPath = equivalentValue.schemaPath.slice(
4612
+ let hookCallPath = equivalentValue.schemaPath.slice(
3880
4613
  0,
3881
4614
  -'.functionCallReturnValue'.length,
3882
4615
  );
3883
4616
  // Only include if it looks like a hook call (contains parentheses)
3884
4617
  // and the variable name (path) is a simple identifier (no dots)
3885
4618
  if (hookCallPath.includes('(') && !path.includes('.')) {
3886
- equivalentSignatureVariables[path] = hookCallPath;
4619
+ // Special case: If hookCallPath is a callback scope (cyScope pattern),
4620
+ // trace through it to find what the callback actually returns.
4621
+ // This handles useState(() => { return prop; }) patterns.
4622
+ const cyScopeMatch = hookCallPath.match(/^(cyScope\d+)\(\)$/);
4623
+ if (cyScopeMatch) {
4624
+ // Use the equivalency database to trace the callback's return value
4625
+ // to its actual source (e.g., viewModeFromUrl -> segments -> params -> useParams)
4626
+ const dbEntry = this.getEquivalenciesDatabaseEntry(
4627
+ scopeNode.name, // Component scope
4628
+ path, // variable name (e.g., viewMode)
4629
+ );
4630
+ if (dbEntry?.sourceCandidates?.length > 0) {
4631
+ // Use the traced source instead of the callback scope
4632
+ hookCallPath = dbEntry.sourceCandidates[0].schemaPath;
4633
+ }
4634
+ }
4635
+ addEquivalency(path, hookCallPath);
3887
4636
  }
3888
4637
  }
3889
4638
 
@@ -3897,10 +4646,17 @@ export class ScopeDataStructure {
3897
4646
  !equivalentValue.schemaPath.startsWith('signature[') && // not a signature path
3898
4647
  !equivalentValue.schemaPath.endsWith('.functionCallReturnValue') // not already handled above
3899
4648
  ) {
3900
- // Only add if we haven't already captured this variable in Case 1 or 2
3901
- if (!(path in equivalentSignatureVariables)) {
3902
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
4649
+ // Skip bare "returnValue" from child scopes this is the child's return value,
4650
+ // not a meaningful data source path in the parent scope
4651
+ if (
4652
+ equivalentValue.schemaPath === 'returnValue' &&
4653
+ equivalentValue.scopeNodeName !==
4654
+ this.scopeTreeManager.getRootName()
4655
+ ) {
4656
+ continue;
3903
4657
  }
4658
+ // Add equivalency (will accumulate if multiple values for OR expressions)
4659
+ addEquivalency(path, equivalentValue.schemaPath);
3904
4660
  }
3905
4661
 
3906
4662
  // Case 4: Child component prop mappings (Fix 22)
@@ -3913,7 +4669,7 @@ export class ScopeDataStructure {
3913
4669
  path.includes('().signature[') &&
3914
4670
  !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable, not a function call
3915
4671
  ) {
3916
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
4672
+ addEquivalency(path, equivalentValue.schemaPath);
3917
4673
  }
3918
4674
 
3919
4675
  // Case 5: Destructured function parameters (Fix 25)
@@ -3928,7 +4684,7 @@ export class ScopeDataStructure {
3928
4684
  !path.includes('.') && // path is a simple identifier (destructured prop name)
3929
4685
  equivalentValue.schemaPath.startsWith('signature[') // schemaPath IS a signature path
3930
4686
  ) {
3931
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
4687
+ addEquivalency(path, equivalentValue.schemaPath);
3932
4688
  }
3933
4689
 
3934
4690
  // Case 7: Method calls on variables that result in .functionCallReturnValue (Fix 33)
@@ -3942,8 +4698,7 @@ export class ScopeDataStructure {
3942
4698
  if (
3943
4699
  !path.includes('.') && // path is a simple identifier
3944
4700
  equivalentValue.schemaPath.endsWith('.functionCallReturnValue') && // ends with function return
3945
- equivalentValue.schemaPath.includes('.') && // has property access (method call)
3946
- !(path in equivalentSignatureVariables) // not already captured
4701
+ equivalentValue.schemaPath.includes('.') // has property access (method call)
3947
4702
  ) {
3948
4703
  // Check if this looks like a method call on a variable (not a hook call)
3949
4704
  // Hook calls look like: hookName() or hookName<T>()
@@ -3957,7 +4712,7 @@ export class ScopeDataStructure {
3957
4712
  const parenPos = hookCallPath.indexOf('(');
3958
4713
  if (dotBeforeParen !== -1 && dotBeforeParen < parenPos) {
3959
4714
  // This is a method call like "splat.split('/')", not a hook call
3960
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
4715
+ addEquivalency(path, equivalentValue.schemaPath);
3961
4716
  }
3962
4717
  }
3963
4718
  }
@@ -3988,8 +4743,9 @@ export class ScopeDataStructure {
3988
4743
  !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable
3989
4744
  ) {
3990
4745
  // Only add if not already present from the root scope
4746
+ // Root scope values take precedence over child scope values
3991
4747
  if (!(path in equivalentSignatureVariables)) {
3992
- equivalentSignatureVariables[path] = equivalentValue.schemaPath;
4748
+ addEquivalency(path, equivalentValue.schemaPath);
3993
4749
  }
3994
4750
  }
3995
4751
  }
@@ -4000,12 +4756,84 @@ export class ScopeDataStructure {
4000
4756
  // E.g., analysis → currentEntityAnalysis → useLoaderData().functionCallReturnValue.currentEntityAnalysis
4001
4757
  // We need multiple passes because resolutions can depend on each other
4002
4758
  const maxIterations = 5; // Prevent infinite loops
4759
+
4760
+ // Helper function to resolve a single source path using equivalencies
4761
+ const resolveSourcePath = (
4762
+ sourcePath: string,
4763
+ equivMap: Record<string, string | string[]>,
4764
+ ): string | null => {
4765
+ // Extract base variable from the path
4766
+ const dotIndex = sourcePath.indexOf('.');
4767
+ const bracketIndex = sourcePath.indexOf('[');
4768
+
4769
+ let baseVar: string;
4770
+ let rest: string;
4771
+
4772
+ if (dotIndex === -1 && bracketIndex === -1) {
4773
+ baseVar = sourcePath;
4774
+ rest = '';
4775
+ } else if (dotIndex === -1) {
4776
+ baseVar = sourcePath.slice(0, bracketIndex);
4777
+ rest = sourcePath.slice(bracketIndex);
4778
+ } else if (bracketIndex === -1) {
4779
+ baseVar = sourcePath.slice(0, dotIndex);
4780
+ rest = sourcePath.slice(dotIndex);
4781
+ } else {
4782
+ const firstIndex = Math.min(dotIndex, bracketIndex);
4783
+ baseVar = sourcePath.slice(0, firstIndex);
4784
+ rest = sourcePath.slice(firstIndex);
4785
+ }
4786
+
4787
+ // Look up the base variable in equivalencies
4788
+ if (baseVar in equivMap && equivMap[baseVar] !== sourcePath) {
4789
+ const baseResolved = equivMap[baseVar];
4790
+ // Skip if baseResolved is an array (handle later)
4791
+ if (Array.isArray(baseResolved)) return null;
4792
+ // If it resolves to a signature path, build the full resolved path
4793
+ if (
4794
+ baseResolved.startsWith('signature[') ||
4795
+ baseResolved.includes('()')
4796
+ ) {
4797
+ if (baseResolved.endsWith('()')) {
4798
+ return baseResolved + '.functionCallReturnValue' + rest;
4799
+ }
4800
+ return baseResolved + rest;
4801
+ }
4802
+ }
4803
+ return null;
4804
+ };
4805
+
4003
4806
  for (let iteration = 0; iteration < maxIterations; iteration++) {
4004
4807
  let changed = false;
4005
4808
 
4006
- for (const [varName, sourcePath] of Object.entries(
4809
+ for (const [varName, sourcePathOrArray] of Object.entries(
4007
4810
  equivalentSignatureVariables,
4008
4811
  )) {
4812
+ // Handle arrays (OR expressions) by resolving each element
4813
+ if (Array.isArray(sourcePathOrArray)) {
4814
+ const resolvedArray: string[] = [];
4815
+ let arrayChanged = false;
4816
+ for (const sourcePath of sourcePathOrArray) {
4817
+ // Try to resolve this path using transitive resolution
4818
+ const resolved = resolveSourcePath(
4819
+ sourcePath,
4820
+ equivalentSignatureVariables,
4821
+ );
4822
+ if (resolved && resolved !== sourcePath) {
4823
+ resolvedArray.push(resolved);
4824
+ arrayChanged = true;
4825
+ } else {
4826
+ resolvedArray.push(sourcePath);
4827
+ }
4828
+ }
4829
+ if (arrayChanged) {
4830
+ equivalentSignatureVariables[varName] = resolvedArray;
4831
+ changed = true;
4832
+ }
4833
+ continue;
4834
+ }
4835
+ const sourcePath = sourcePathOrArray;
4836
+
4009
4837
  // Skip if already fully resolved (contains function call syntax)
4010
4838
  // BUT first check for computed value patterns that need resolution (Fix 28)
4011
4839
  // AND method call patterns that need base variable resolution (Fix 33)
@@ -4067,6 +4895,8 @@ export class ScopeDataStructure {
4067
4895
  baseVar !== varName
4068
4896
  ) {
4069
4897
  const baseResolved = equivalentSignatureVariables[baseVar];
4898
+ // Skip if baseResolved is an array (OR expression)
4899
+ if (Array.isArray(baseResolved)) continue;
4070
4900
  // Only resolve if the base resolved to something useful (contains () or .)
4071
4901
  if (baseResolved.includes('()') || baseResolved.includes('.')) {
4072
4902
  const newPath = baseResolved + rest;
@@ -4078,6 +4908,40 @@ export class ScopeDataStructure {
4078
4908
  }
4079
4909
  }
4080
4910
 
4911
+ // Fix 38: Handle cyScope lazy initializer return values
4912
+ // When we have viewMode -> cyScope20(), trace through to find what cyScope20 returns.
4913
+ // The lazy initializer's return value should be the controllable data source.
4914
+ // Pattern: cyScopeN() where N is a number
4915
+ const cyScopeMatch = sourcePath.match(/^(cyScope\d+)\(\)$/);
4916
+ if (cyScopeMatch) {
4917
+ const cyScopeName = cyScopeMatch[1];
4918
+ const cyScopeNode = this.scopeNodes[cyScopeName];
4919
+
4920
+ if (cyScopeNode?.equivalencies) {
4921
+ // Look for returnValue equivalency in the cyScope
4922
+ const returnValueEquivs =
4923
+ cyScopeNode.equivalencies['returnValue'];
4924
+ if (returnValueEquivs && returnValueEquivs.length > 0) {
4925
+ // Get the first return value source
4926
+ const returnSource = returnValueEquivs[0].schemaPath;
4927
+
4928
+ // If the return source is a simple variable (not a complex path),
4929
+ // resolve varName directly to that variable
4930
+ if (
4931
+ returnSource &&
4932
+ !returnSource.includes('(') &&
4933
+ !returnSource.includes('[')
4934
+ ) {
4935
+ // Update varName to point to the return source
4936
+ if (equivalentSignatureVariables[varName] !== returnSource) {
4937
+ equivalentSignatureVariables[varName] = returnSource;
4938
+ changed = true;
4939
+ }
4940
+ }
4941
+ }
4942
+ }
4943
+ }
4944
+
4081
4945
  continue;
4082
4946
  }
4083
4947
 
@@ -4097,7 +4961,12 @@ export class ScopeDataStructure {
4097
4961
  }
4098
4962
 
4099
4963
  if (baseVar in equivalentSignatureVariables && baseVar !== varName) {
4100
- const baseResolved = equivalentSignatureVariables[baseVar];
4964
+ // Handle array case (OR expressions) - use first element
4965
+ const rawBaseResolved = equivalentSignatureVariables[baseVar];
4966
+ const baseResolved = Array.isArray(rawBaseResolved)
4967
+ ? rawBaseResolved[0]
4968
+ : rawBaseResolved;
4969
+ if (!baseResolved) continue;
4101
4970
  // If the base resolves to a hook call, add .functionCallReturnValue
4102
4971
  if (baseResolved.endsWith('()')) {
4103
4972
  const newPath = baseResolved + '.functionCallReturnValue' + rest;
@@ -4187,9 +5056,109 @@ export class ScopeDataStructure {
4187
5056
  // Replace cyScope placeholders in all external function call data
4188
5057
  // This ensures call signatures and schema paths use actual callback text
4189
5058
  // instead of internal cyScope names, preventing mock data merge conflicts.
4190
- return this.externalFunctionCalls.map((efc) =>
4191
- this.cleanCyScopeFromFunctionCallInfo(efc),
4192
- );
5059
+ const rootScopeName = this.scopeTreeManager.getRootName();
5060
+ const rootSchema = this.scopeNodes[rootScopeName]?.schema ?? {};
5061
+
5062
+ return this.externalFunctionCalls.map((efc) => {
5063
+ const cleaned = this.cleanCyScopeFromFunctionCallInfo(efc);
5064
+ return this.filterConflatedExternalPaths(cleaned, rootSchema);
5065
+ });
5066
+ }
5067
+
5068
+ /**
5069
+ * Filters out conflated paths from external function call schemas.
5070
+ *
5071
+ * When multiple useState(false) calls create equivalency conflation during
5072
+ * Phase 1 analysis, standalone boolean state variables (like showWorkoutForm,
5073
+ * showGoalForm) can bleed into external function call schemas as sub-properties
5074
+ * of unrelated data fields (like data[].activity_type.showWorkoutForm).
5075
+ *
5076
+ * Detection: group sub-properties by parent path. If 2+ sub-properties of
5077
+ * the same parent all match standalone root scope variable names, treat them
5078
+ * as conflation artifacts and remove them.
5079
+ */
5080
+ private filterConflatedExternalPaths(
5081
+ efc: FunctionCallInfo,
5082
+ rootSchema: Record<string, string>,
5083
+ ): FunctionCallInfo {
5084
+ // Build a set of top-level root scope variable names (simple names, no dots/brackets)
5085
+ const topLevelRootVars = new Set<string>();
5086
+ for (const key of Object.keys(rootSchema)) {
5087
+ if (!key.includes('.') && !key.includes('[')) {
5088
+ topLevelRootVars.add(key);
5089
+ }
5090
+ }
5091
+
5092
+ if (topLevelRootVars.size === 0) return efc;
5093
+
5094
+ // Group sub-property matches by their parent path.
5095
+ // For a path like "...data[].activity_type.showWorkoutForm",
5096
+ // parent = "...data[].activity_type", child = "showWorkoutForm"
5097
+ const parentToConflatedKeys = new Map<string, string[]>();
5098
+
5099
+ for (const key of Object.keys(efc.schema)) {
5100
+ const lastDot = key.lastIndexOf('.');
5101
+ if (lastDot === -1) continue;
5102
+
5103
+ const parent = key.substring(0, lastDot);
5104
+ const child = key.substring(lastDot + 1);
5105
+
5106
+ // Skip array access or function call patterns
5107
+ if (child.includes('[') || child.includes('(')) continue;
5108
+
5109
+ // Only consider paths inside array element chains (contains []).
5110
+ // Direct children of functionCallReturnValue are legitimate destructured
5111
+ // return values, not conflation. Conflation happens deeper in the chain
5112
+ // when array element fields get corrupted sub-properties.
5113
+ if (!parent.includes('[')) continue;
5114
+
5115
+ if (topLevelRootVars.has(child)) {
5116
+ if (!parentToConflatedKeys.has(parent)) {
5117
+ parentToConflatedKeys.set(parent, []);
5118
+ }
5119
+ parentToConflatedKeys.get(parent)!.push(key);
5120
+ }
5121
+ }
5122
+
5123
+ // Only filter when 2+ sub-properties of the same parent match root scope vars.
5124
+ // This threshold avoids false positives from coincidental name matches.
5125
+ const keysToRemove = new Set<string>();
5126
+ const parentsToRestore = new Set<string>();
5127
+
5128
+ for (const [parent, conflatedKeys] of parentToConflatedKeys) {
5129
+ if (conflatedKeys.length >= 2) {
5130
+ for (const key of conflatedKeys) {
5131
+ keysToRemove.add(key);
5132
+ }
5133
+ parentsToRestore.add(parent);
5134
+ }
5135
+ }
5136
+
5137
+ if (keysToRemove.size === 0) return efc;
5138
+
5139
+ // Create a new schema without the conflated paths
5140
+ const newSchema: Record<string, string> = {};
5141
+ for (const [key, value] of Object.entries(efc.schema)) {
5142
+ if (keysToRemove.has(key)) continue;
5143
+
5144
+ // Restore parent type: if it was changed to "object" because of conflated
5145
+ // sub-properties, and now all those sub-properties are removed, change it
5146
+ // back to "unknown" (we don't know the original type)
5147
+ if (parentsToRestore.has(key) && value === 'object') {
5148
+ // Check if there are any remaining sub-properties
5149
+ const hasRemainingSubProps = Object.keys(efc.schema).some(
5150
+ (k) =>
5151
+ !keysToRemove.has(k) &&
5152
+ k !== key &&
5153
+ (k.startsWith(key + '.') || k.startsWith(key + '[')),
5154
+ );
5155
+ newSchema[key] = hasRemainingSubProps ? value : 'unknown';
5156
+ } else {
5157
+ newSchema[key] = value;
5158
+ }
5159
+ }
5160
+
5161
+ return { ...efc, schema: newSchema };
4193
5162
  }
4194
5163
 
4195
5164
  /**
@@ -4317,7 +5286,7 @@ export class ScopeDataStructure {
4317
5286
  path: string;
4318
5287
  conditionType: 'truthiness' | 'comparison' | 'switch';
4319
5288
  comparedValues?: string[];
4320
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
5289
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
4321
5290
  }>
4322
5291
  >,
4323
5292
  ): void {
@@ -4482,6 +5451,10 @@ export class ScopeDataStructure {
4482
5451
  getEnrichedConditionalUsages(): Record<string, EnrichedConditionalUsage[]> {
4483
5452
  const enriched: Record<string, EnrichedConditionalUsage[]> = {};
4484
5453
 
5454
+ console.log(
5455
+ `[getEnrichedConditionalUsages] Processing ${Object.keys(this.rawConditionalUsages).length} conditional paths: [${Object.keys(this.rawConditionalUsages).join(', ')}]`,
5456
+ );
5457
+
4485
5458
  for (const [path, usages] of Object.entries(this.rawConditionalUsages)) {
4486
5459
  // Try to trace this path back to a data source
4487
5460
  // First, try the root scope
@@ -4490,10 +5463,69 @@ export class ScopeDataStructure {
4490
5463
 
4491
5464
  let sourceDataPath: string | undefined;
4492
5465
  if (explanation.source) {
4493
- // Build the full data path: scopeName.path
4494
- sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
5466
+ const { scope, path: sourcePath } = explanation.source;
5467
+
5468
+ // Build initial path — avoid redundant prefix when path already contains the scope call
5469
+ let fullPath: string;
5470
+ if (sourcePath.startsWith(`${scope}(`)) {
5471
+ fullPath = sourcePath;
5472
+ } else {
5473
+ fullPath = `${scope}.${sourcePath}`;
5474
+ }
5475
+
5476
+ sourceDataPath = fullPath;
5477
+ console.log(
5478
+ `[getEnrichedConditionalUsages] "${path}" explainPath → scope="${scope}", sourcePath="${sourcePath}" → sourceDataPath="${sourceDataPath}"`,
5479
+ );
5480
+ } else {
5481
+ console.log(
5482
+ `[getEnrichedConditionalUsages] "${path}" explainPath → no source found`,
5483
+ );
5484
+ }
5485
+
5486
+ // If explainPath didn't find a useful external source (e.g., it traced to
5487
+ // useState or just to the component scope itself), check sourceEquivalencies
5488
+ // for an external function call source like a fetch call
5489
+ const hasExternalSource = sourceDataPath?.includes(
5490
+ '.functionCallReturnValue',
5491
+ );
5492
+ if (!hasExternalSource) {
5493
+ console.log(
5494
+ `[getEnrichedConditionalUsages] "${path}" no external source (sourceDataPath="${sourceDataPath}"), checking sourceEquivalencies fallback...`,
5495
+ );
5496
+ const sourceEquiv = this.getSourceEquivalencies();
5497
+ const returnValueKey = `returnValue.${path}`;
5498
+ const sources = sourceEquiv[returnValueKey];
5499
+ if (sources) {
5500
+ console.log(
5501
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies["${returnValueKey}"] has ${sources.length} sources: [${sources.map((s: { schemaPath: string }) => s.schemaPath).join(', ')}]`,
5502
+ );
5503
+ const externalSource = sources.find(
5504
+ (s: { schemaPath: string }) =>
5505
+ s.schemaPath.includes('.functionCallReturnValue') &&
5506
+ !s.schemaPath.startsWith('useState('),
5507
+ );
5508
+ if (externalSource) {
5509
+ console.log(
5510
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies fallback found external source: "${externalSource.schemaPath}"`,
5511
+ );
5512
+ sourceDataPath = externalSource.schemaPath;
5513
+ } else {
5514
+ console.log(
5515
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies fallback found no external function call source`,
5516
+ );
5517
+ }
5518
+ } else {
5519
+ console.log(
5520
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies["${returnValueKey}"] not found`,
5521
+ );
5522
+ }
4495
5523
  }
4496
5524
 
5525
+ console.log(
5526
+ `[getEnrichedConditionalUsages] "${path}" FINAL sourceDataPath="${sourceDataPath ?? '(none)'}" (${usages.length} usages)`,
5527
+ );
5528
+
4497
5529
  enriched[path] = usages.map((usage) => ({
4498
5530
  ...usage,
4499
5531
  sourceDataPath,
@@ -4503,6 +5535,33 @@ export class ScopeDataStructure {
4503
5535
  return enriched;
4504
5536
  }
4505
5537
 
5538
+ /**
5539
+ * Add JSX rendering usages from AST analysis.
5540
+ * These track arrays rendered via .map() and strings interpolated in JSX.
5541
+ */
5542
+ addJsxRenderingUsages(
5543
+ usages: import('../astScopes/types').JsxRenderingUsage[],
5544
+ ): void {
5545
+ // Add usages, avoiding duplicates based on path and renderingType
5546
+ for (const usage of usages) {
5547
+ const exists = this.rawJsxRenderingUsages.some(
5548
+ (existing) =>
5549
+ existing.path === usage.path &&
5550
+ existing.renderingType === usage.renderingType,
5551
+ );
5552
+ if (!exists) {
5553
+ this.rawJsxRenderingUsages.push(usage);
5554
+ }
5555
+ }
5556
+ }
5557
+
5558
+ /**
5559
+ * Get JSX rendering usages collected during analysis.
5560
+ */
5561
+ getJsxRenderingUsages(): import('../astScopes/types').JsxRenderingUsage[] {
5562
+ return this.rawJsxRenderingUsages;
5563
+ }
5564
+
4506
5565
  toSerializable(): SerializableDataStructure {
4507
5566
  // Helper to clean cyScope and cyDuplicateKey from a string for output
4508
5567
  const cleanCyScope = (str: string): string =>
@@ -4814,11 +5873,22 @@ export class ScopeDataStructure {
4814
5873
  }
4815
5874
  }
4816
5875
 
5876
+ // Enrich the schema with inferred types by applying fillInSchemaGapsAndUnknowns.
5877
+ // This ensures the serialized schema has the same type inference as getReturnValue().
5878
+ // Without this, evidence like "entities[].analyses: array" becomes "unknown".
5879
+ const enrichedSchema = { ...efc.schema };
5880
+ const tempScopeNode = {
5881
+ name: efc.name,
5882
+ schema: enrichedSchema,
5883
+ equivalencies: efc.equivalencies ?? {},
5884
+ };
5885
+ fillInSchemaGapsAndUnknowns(tempScopeNode, true);
5886
+
4817
5887
  return {
4818
5888
  name: efc.name,
4819
5889
  callSignature: efc.callSignature,
4820
5890
  callScope: efc.callScope,
4821
- schema: efc.schema,
5891
+ schema: enrichedSchema,
4822
5892
  equivalencies: efc.equivalencies
4823
5893
  ? Object.entries(efc.equivalencies).reduce(
4824
5894
  (acc, [key, vars]) => {
@@ -5003,6 +6073,12 @@ export class ScopeDataStructure {
5003
6073
  ? enrichedGatingConditions
5004
6074
  : undefined;
5005
6075
 
6076
+ // Get JSX rendering usages (arrays via .map(), strings via interpolation)
6077
+ const jsxRenderingUsages =
6078
+ this.rawJsxRenderingUsages.length > 0
6079
+ ? this.rawJsxRenderingUsages
6080
+ : undefined;
6081
+
5006
6082
  return {
5007
6083
  externalFunctionCalls: deduplicatedExternalFunctionCalls,
5008
6084
  rootFunction,
@@ -5013,6 +6089,7 @@ export class ScopeDataStructure {
5013
6089
  conditionalEffects,
5014
6090
  compoundConditionals,
5015
6091
  childBoundaryGatingConditions,
6092
+ jsxRenderingUsages,
5016
6093
  };
5017
6094
  }
5018
6095