@codeyam/codeyam-cli 0.1.0-staging.b8a55ba → 0.1.0-staging.bd4126b

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 (966) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/common/execAsync.ts +1 -1
  3. package/analyzer-template/log.txt +3 -3
  4. package/analyzer-template/package.json +24 -21
  5. package/analyzer-template/packages/ai/index.ts +21 -5
  6. package/analyzer-template/packages/ai/package.json +3 -3
  7. package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
  8. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +226 -24
  9. package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
  10. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +183 -10
  11. package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
  12. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +181 -23
  13. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.ts +10 -17
  14. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.ts +18 -0
  15. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +15 -0
  16. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +181 -1
  17. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +1229 -30
  18. package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
  19. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +265 -6
  20. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
  21. package/analyzer-template/packages/ai/src/lib/completionCall.ts +216 -36
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +2116 -356
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +7 -2
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +296 -35
  25. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +120 -76
  26. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
  27. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
  28. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +54 -3
  29. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +140 -20
  30. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
  31. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +140 -14
  32. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  33. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
  34. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
  35. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +393 -90
  36. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
  37. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  38. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +183 -0
  39. package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
  40. package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
  41. package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
  42. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +74 -7
  43. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +86 -142
  44. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +59 -3
  45. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1421 -88
  46. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +200 -196
  47. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +710 -0
  48. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
  49. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +2484 -0
  50. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
  51. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +5 -5
  52. package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +328 -7
  53. package/analyzer-template/packages/ai/src/lib/mergeJsonTypeDefinitions.ts +5 -0
  54. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +111 -87
  55. package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
  56. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +10 -7
  57. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +1 -1
  58. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -142
  59. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
  60. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
  61. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +110 -6
  62. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +14 -89
  63. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.ts +58 -0
  64. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +11 -11
  65. package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
  66. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +824 -0
  67. package/analyzer-template/packages/ai/src/lib/splitOutsideParentheses.ts +5 -1
  68. package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
  69. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +122 -3
  70. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +114 -2
  71. package/analyzer-template/packages/analyze/index.ts +2 -0
  72. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +79 -59
  73. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
  74. package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
  75. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  76. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
  77. package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
  78. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
  79. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
  80. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
  81. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
  82. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
  83. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
  84. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +466 -270
  85. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +34 -1
  86. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +6 -0
  87. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
  88. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
  89. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
  90. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +31 -15
  91. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +11 -7
  92. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +11 -12
  93. package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
  94. package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
  95. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +14 -12
  96. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1315 -0
  97. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +201 -46
  98. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
  99. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +593 -84
  100. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +28 -62
  101. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +377 -84
  102. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +264 -0
  103. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +35 -129
  104. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +2 -3
  105. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +970 -140
  106. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
  107. package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
  108. package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
  109. package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
  110. package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
  111. package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
  112. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
  113. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
  114. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
  115. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
  116. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
  117. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
  118. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
  119. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  120. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
  121. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
  122. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
  123. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  124. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
  125. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
  126. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
  127. package/analyzer-template/packages/aws/package.json +10 -10
  128. package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
  129. package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
  130. package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
  131. package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
  132. package/analyzer-template/packages/database/package.json +1 -1
  133. package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +1 -1
  134. package/analyzer-template/packages/database/src/lib/analysisToDb.ts +1 -1
  135. package/analyzer-template/packages/database/src/lib/branchToDb.ts +1 -1
  136. package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +1 -1
  137. package/analyzer-template/packages/database/src/lib/commitToDb.ts +1 -1
  138. package/analyzer-template/packages/database/src/lib/fileToDb.ts +1 -1
  139. package/analyzer-template/packages/database/src/lib/kysely/db.ts +14 -1
  140. package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
  141. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +17 -1
  142. package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
  143. package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
  144. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
  145. package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
  146. package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
  147. package/analyzer-template/packages/database/src/lib/loadCommits.ts +28 -0
  148. package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
  149. package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
  150. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +7 -3
  151. package/analyzer-template/packages/database/src/lib/projectToDb.ts +1 -1
  152. package/analyzer-template/packages/database/src/lib/saveFiles.ts +1 -1
  153. package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +1 -1
  154. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +7 -14
  155. package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +1 -1
  156. package/analyzer-template/packages/generate/index.ts +3 -0
  157. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
  158. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
  159. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
  160. package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
  161. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +1 -1
  162. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -1
  163. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +1 -1
  164. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -1
  165. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +1 -1
  166. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -1
  167. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +1 -1
  168. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -1
  169. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +1 -1
  170. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -1
  171. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +1 -1
  172. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -1
  173. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -0
  174. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  175. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +11 -1
  176. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  177. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +1 -18
  178. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  179. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +1 -0
  180. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
  181. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
  182. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  183. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +17 -1
  184. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  185. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  186. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
  187. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
  188. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
  189. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
  190. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  191. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  192. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +2 -6
  193. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  194. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +2 -0
  195. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
  196. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
  197. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
  198. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  199. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
  200. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  201. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
  202. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
  203. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
  204. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
  205. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
  206. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
  207. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  208. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +22 -1
  209. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  210. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
  211. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  212. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
  213. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  214. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
  215. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
  216. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -1
  217. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  218. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +7 -4
  219. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  220. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +1 -1
  221. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -1
  222. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +1 -1
  223. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -1
  224. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +1 -1
  225. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -1
  226. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +2 -2
  227. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  228. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +5 -4
  229. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  230. package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
  231. package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
  232. package/analyzer-template/packages/github/dist/generate/index.js +3 -0
  233. package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
  234. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  235. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  236. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  237. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
  238. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
  239. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  240. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  241. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
  242. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
  243. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  244. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  245. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
  246. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
  247. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
  248. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  249. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
  250. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
  251. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
  252. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
  253. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
  254. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
  255. package/analyzer-template/packages/github/dist/types/index.d.ts +3 -4
  256. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  257. package/analyzer-template/packages/github/dist/types/index.js +0 -1
  258. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  259. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +71 -27
  260. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  261. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts +2 -0
  262. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts.map +1 -1
  263. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
  264. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
  265. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  266. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  267. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +9 -54
  268. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  269. package/analyzer-template/packages/github/dist/types/src/types/Scenario.js +1 -21
  270. package/analyzer-template/packages/github/dist/types/src/types/Scenario.js.map +1 -1
  271. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +153 -5
  272. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  273. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  274. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  275. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts +2 -0
  276. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  277. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
  278. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  279. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
  280. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
  281. package/analyzer-template/packages/github/package.json +1 -1
  282. package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
  283. package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
  284. package/analyzer-template/packages/process/index.ts +2 -0
  285. package/analyzer-template/packages/process/package.json +12 -0
  286. package/analyzer-template/packages/process/tsconfig.json +8 -0
  287. package/analyzer-template/packages/types/index.ts +3 -6
  288. package/analyzer-template/packages/types/src/types/Analysis.ts +87 -27
  289. package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
  290. package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
  291. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +7 -0
  292. package/analyzer-template/packages/types/src/types/Scenario.ts +9 -77
  293. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +181 -5
  294. package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
  295. package/analyzer-template/packages/types/src/types/StatementInfo.ts +2 -0
  296. package/analyzer-template/packages/utils/dist/types/index.d.ts +3 -4
  297. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  298. package/analyzer-template/packages/utils/dist/types/index.js +0 -1
  299. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  300. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +71 -27
  301. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  302. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts +2 -0
  303. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts.map +1 -1
  304. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
  305. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
  306. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  307. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  308. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +9 -54
  309. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  310. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.js +1 -21
  311. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.js.map +1 -1
  312. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +153 -5
  313. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  314. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  315. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  316. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts +2 -0
  317. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  318. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  319. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +93 -2
  320. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  321. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
  322. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  323. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
  324. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
  325. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +108 -2
  326. package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
  327. package/analyzer-template/playwright/capture.ts +57 -26
  328. package/analyzer-template/playwright/captureStatic.ts +1 -1
  329. package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
  330. package/analyzer-template/playwright/waitForServer.ts +21 -6
  331. package/analyzer-template/project/analyzeBaselineCommit.ts +9 -0
  332. package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
  333. package/analyzer-template/project/analyzeFileEntities.ts +4 -0
  334. package/analyzer-template/project/analyzeRegularCommit.ts +9 -0
  335. package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
  336. package/analyzer-template/project/constructMockCode.ts +1229 -179
  337. package/analyzer-template/project/controller/startController.ts +16 -1
  338. package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
  339. package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
  340. package/analyzer-template/project/loadReadyToBeCaptured.ts +65 -41
  341. package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
  342. package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
  343. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +3 -6
  344. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +18 -7
  345. package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
  346. package/analyzer-template/project/orchestrateCapture.ts +81 -9
  347. package/analyzer-template/project/reconcileMockDataKeys.ts +220 -78
  348. package/analyzer-template/project/runAnalysis.ts +11 -0
  349. package/analyzer-template/project/serverOnlyModules.ts +127 -2
  350. package/analyzer-template/project/start.ts +51 -15
  351. package/analyzer-template/project/startScenarioCapture.ts +6 -0
  352. package/analyzer-template/project/writeMockDataTsx.ts +345 -32
  353. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  354. package/analyzer-template/project/writeScenarioComponents.ts +434 -130
  355. package/analyzer-template/project/writeScenarioFiles.ts +26 -0
  356. package/analyzer-template/project/writeSimpleRoot.ts +28 -42
  357. package/analyzer-template/scripts/comboWorkerLoop.cjs +99 -50
  358. package/analyzer-template/scripts/defaultCmd.sh +9 -0
  359. package/analyzer-template/tsconfig.json +2 -1
  360. package/background/src/lib/local/createLocalAnalyzer.js +2 -30
  361. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  362. package/background/src/lib/local/execAsync.js +1 -1
  363. package/background/src/lib/local/execAsync.js.map +1 -1
  364. package/background/src/lib/virtualized/common/execAsync.js +1 -1
  365. package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
  366. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +7 -1
  367. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
  368. package/background/src/lib/virtualized/project/analyzeBranchCommit.js +2 -1
  369. package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
  370. package/background/src/lib/virtualized/project/analyzeFileEntities.js +2 -1
  371. package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
  372. package/background/src/lib/virtualized/project/analyzeRegularCommit.js +7 -1
  373. package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
  374. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
  375. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
  376. package/background/src/lib/virtualized/project/constructMockCode.js +1085 -134
  377. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  378. package/background/src/lib/virtualized/project/controller/startController.js +11 -1
  379. package/background/src/lib/virtualized/project/controller/startController.js.map +1 -1
  380. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js +73 -1
  381. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js.map +1 -1
  382. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js +6 -3
  383. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js.map +1 -1
  384. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +19 -8
  385. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  386. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js +7 -7
  387. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js.map +1 -1
  388. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js +2 -2
  389. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js.map +1 -1
  390. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +3 -2
  391. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  392. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +7 -5
  393. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  394. package/background/src/lib/virtualized/project/orchestrateCapture.js +65 -10
  395. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  396. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +188 -47
  397. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  398. package/background/src/lib/virtualized/project/runAnalysis.js +9 -0
  399. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  400. package/background/src/lib/virtualized/project/serverOnlyModules.js +106 -3
  401. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -1
  402. package/background/src/lib/virtualized/project/start.js +47 -15
  403. package/background/src/lib/virtualized/project/start.js.map +1 -1
  404. package/background/src/lib/virtualized/project/startScenarioCapture.js +7 -0
  405. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  406. package/background/src/lib/virtualized/project/writeMockDataTsx.js +301 -27
  407. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  408. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
  409. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
  410. package/background/src/lib/virtualized/project/writeScenarioComponents.js +334 -107
  411. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  412. package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
  413. package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
  414. package/background/src/lib/virtualized/project/writeSimpleRoot.js +28 -41
  415. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  416. package/codeyam-cli/scripts/apply-setup.js +180 -0
  417. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  418. package/codeyam-cli/src/cli.js +35 -17
  419. package/codeyam-cli/src/cli.js.map +1 -1
  420. package/codeyam-cli/src/codeyam-cli.js +18 -2
  421. package/codeyam-cli/src/codeyam-cli.js.map +1 -1
  422. package/codeyam-cli/src/commands/analyze.js +5 -3
  423. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  424. package/codeyam-cli/src/commands/baseline.js +176 -0
  425. package/codeyam-cli/src/commands/baseline.js.map +1 -0
  426. package/codeyam-cli/src/commands/debug.js +37 -23
  427. package/codeyam-cli/src/commands/debug.js.map +1 -1
  428. package/codeyam-cli/src/commands/default.js +30 -34
  429. package/codeyam-cli/src/commands/default.js.map +1 -1
  430. package/codeyam-cli/src/commands/detect-universal-mocks.js +2 -0
  431. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +1 -1
  432. package/codeyam-cli/src/commands/init.js +49 -257
  433. package/codeyam-cli/src/commands/init.js.map +1 -1
  434. package/codeyam-cli/src/commands/memory.js +307 -0
  435. package/codeyam-cli/src/commands/memory.js.map +1 -0
  436. package/codeyam-cli/src/commands/recapture.js +31 -18
  437. package/codeyam-cli/src/commands/recapture.js.map +1 -1
  438. package/codeyam-cli/src/commands/report.js +46 -1
  439. package/codeyam-cli/src/commands/report.js.map +1 -1
  440. package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
  441. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
  442. package/codeyam-cli/src/commands/setup-simulations.js +284 -0
  443. package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
  444. package/codeyam-cli/src/commands/start.js +8 -12
  445. package/codeyam-cli/src/commands/start.js.map +1 -1
  446. package/codeyam-cli/src/commands/status.js +23 -1
  447. package/codeyam-cli/src/commands/status.js.map +1 -1
  448. package/codeyam-cli/src/commands/test-startup.js +3 -1
  449. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  450. package/codeyam-cli/src/commands/verify.js +14 -2
  451. package/codeyam-cli/src/commands/verify.js.map +1 -1
  452. package/codeyam-cli/src/commands/wipe.js +108 -0
  453. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  454. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +179 -0
  455. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  456. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
  457. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
  458. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +128 -82
  459. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  460. package/codeyam-cli/src/utils/analysisRunner.js +29 -15
  461. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  462. package/codeyam-cli/src/utils/analyzer.js +7 -0
  463. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  464. package/codeyam-cli/src/utils/backgroundServer.js +102 -21
  465. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  466. package/codeyam-cli/src/utils/database.js +91 -5
  467. package/codeyam-cli/src/utils/database.js.map +1 -1
  468. package/codeyam-cli/src/utils/generateReport.js +4 -3
  469. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  470. package/codeyam-cli/src/utils/git.js +79 -0
  471. package/codeyam-cli/src/utils/git.js.map +1 -0
  472. package/codeyam-cli/src/utils/install-skills.js +76 -37
  473. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  474. package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
  475. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
  476. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  477. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  478. package/codeyam-cli/src/utils/progress.js +7 -0
  479. package/codeyam-cli/src/utils/progress.js.map +1 -1
  480. package/codeyam-cli/src/utils/queue/job.js +109 -0
  481. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  482. package/codeyam-cli/src/utils/queue/manager.js +6 -0
  483. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  484. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  485. package/codeyam-cli/src/utils/requireSimulations.js +10 -0
  486. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
  487. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
  488. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
  489. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +230 -0
  490. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
  491. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
  492. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
  493. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
  494. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
  495. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
  496. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
  497. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
  498. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
  499. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +74 -0
  500. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
  501. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +376 -0
  502. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
  503. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +116 -0
  504. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
  505. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
  506. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
  507. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
  508. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
  509. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +116 -0
  510. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
  511. package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
  512. package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
  513. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +44 -0
  514. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
  515. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
  516. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
  517. package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
  518. package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
  519. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
  520. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
  521. package/codeyam-cli/src/utils/rules/index.js +6 -0
  522. package/codeyam-cli/src/utils/rules/index.js.map +1 -0
  523. package/codeyam-cli/src/utils/rules/parser.js +83 -0
  524. package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
  525. package/codeyam-cli/src/utils/rules/pathMatcher.js +18 -0
  526. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
  527. package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
  528. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
  529. package/codeyam-cli/src/utils/rules/staleness.js +137 -0
  530. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
  531. package/codeyam-cli/src/utils/serverState.js +37 -10
  532. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  533. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +21 -42
  534. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  535. package/codeyam-cli/src/utils/simulationGateMiddleware.js +138 -0
  536. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  537. package/codeyam-cli/src/utils/syncMocksMiddleware.js +5 -24
  538. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  539. package/codeyam-cli/src/utils/versionInfo.js +46 -15
  540. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  541. package/codeyam-cli/src/utils/wipe.js +128 -0
  542. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  543. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  544. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  545. package/codeyam-cli/src/webserver/app/lib/database.js +88 -23
  546. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  547. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  548. package/codeyam-cli/src/webserver/backgroundServer.js +50 -0
  549. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  550. package/codeyam-cli/src/webserver/bootstrap.js +51 -0
  551. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -1
  552. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-jNYXRRNI.js +1 -0
  553. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-bwuHPyTa.js +11 -0
  554. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-CzGX-miz.js → EntityTypeBadge-CvzqMxcu.js} +1 -1
  555. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BH0XDim7.js +41 -0
  556. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-EhOseatT.js +34 -0
  557. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-yjIHlOGa.js +25 -0
  558. package/codeyam-cli/src/webserver/build/client/assets/{LibraryFunctionPreview-CBQPrpT0.js → LibraryFunctionPreview-Cq5o8jL4.js} +1 -1
  559. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-D1CdlbrV.js → LoadingDots-BvMu2i-g.js} +1 -1
  560. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-wDPcZNKx.js → LogViewer-kgBTLoJD.js} +1 -1
  561. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BzPgx-xO.js +11 -0
  562. package/codeyam-cli/src/webserver/build/client/assets/{SafeScreenshot-BfmDgXxG.js → SafeScreenshot-CwZrv-Ok.js} +1 -1
  563. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BX2Ny2Qj.js +10 -0
  564. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-6J7zDUD5.js → TruncatedFilePath-CDpEprKa.js} +1 -1
  565. package/codeyam-cli/src/webserver/build/client/assets/_index-BRx8ZGZo.js +11 -0
  566. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-4S4yPfFw.js +27 -0
  567. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DHKuQSmR.js +17 -0
  568. package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
  569. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  570. package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
  571. package/codeyam-cli/src/webserver/build/client/assets/book-open-D4IPYH_y.js +6 -0
  572. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BYimnrHg.js → chevron-down-CG65viiV.js} +1 -1
  573. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-DB3aFuEO.js +51 -0
  574. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-CaVsIRxt.js → circle-check-igfMr5DY.js} +1 -1
  575. package/codeyam-cli/src/webserver/build/client/assets/copy-Coc4o_8c.js +11 -0
  576. package/codeyam-cli/src/webserver/build/client/assets/{createLucideIcon-CgUsG7ib.js → createLucideIcon-D1zB-pYc.js} +1 -1
  577. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
  578. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
  579. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-JTAjQ54M.js +1 -0
  580. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-zUEpfPsu.js → entity._sha._-B0h9AqE6.js} +12 -12
  581. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DjLxr2JB.js +6 -0
  582. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-CtYowLOt.js +6 -0
  583. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-CfLCUi9S.js → entity._sha_.edit._scenarioId-PePWg17F.js} +1 -1
  584. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-DKJyZfAY.js → entry.client-I-Wo99C_.js} +6 -6
  585. package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
  586. package/codeyam-cli/src/webserver/build/client/assets/{fileTableUtils-DAtOlaWE.js → fileTableUtils-9sMMAiWJ.js} +1 -1
  587. package/codeyam-cli/src/webserver/build/client/assets/files-Co65J0s3.js +1 -0
  588. package/codeyam-cli/src/webserver/build/client/assets/{git-D62Lxxmv.js → git-BdHOxVfg.js} +8 -8
  589. package/codeyam-cli/src/webserver/build/client/assets/globals-BSZfYCkU.css +1 -0
  590. package/codeyam-cli/src/webserver/build/client/assets/{index-CzNNiTkw.js → index-CUM5iXwc.js} +1 -1
  591. package/codeyam-cli/src/webserver/build/client/assets/{index-BosqDOlH.js → index-_417gcQW.js} +1 -1
  592. package/codeyam-cli/src/webserver/build/client/assets/labs-BK0C1H1T.js +1 -0
  593. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-CNp9QFCX.js → loader-circle-TzRHMVog.js} +1 -1
  594. package/codeyam-cli/src/webserver/build/client/assets/manifest-040dab1c.js +1 -0
  595. package/codeyam-cli/src/webserver/build/client/assets/memory-UIDVz141.js +92 -0
  596. package/codeyam-cli/src/webserver/build/client/assets/pause-hjzB7t2z.js +11 -0
  597. package/codeyam-cli/src/webserver/build/client/assets/root-D1WadSdf.js +62 -0
  598. package/codeyam-cli/src/webserver/build/client/assets/{search-DDGjYAMJ.js → search-DcAwD_Ln.js} +1 -1
  599. package/codeyam-cli/src/webserver/build/client/assets/settings-CclxrcPK.js +1 -0
  600. package/codeyam-cli/src/webserver/build/client/assets/simulations-DVNJVQgD.js +1 -0
  601. package/codeyam-cli/src/webserver/build/client/assets/terminal-DbEAHMbA.js +11 -0
  602. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-CBc5dE1s.js → triangle-alert-CAD5b1o_.js} +1 -1
  603. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BqgrAzs3.js +1 -0
  604. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-BqPPNjAl.js → useLastLogLine-DAFqfEDH.js} +1 -1
  605. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DZlYx2c4.js +1 -0
  606. package/codeyam-cli/src/webserver/build/client/assets/{useToast-DWHcCcl1.js → useToast-ihdMtlf6.js} +1 -1
  607. package/codeyam-cli/src/webserver/build/server/assets/index-B3dE0r28.js +1 -0
  608. package/codeyam-cli/src/webserver/build/server/assets/server-build-DYbfdxa3.js +273 -0
  609. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  610. package/codeyam-cli/src/webserver/build-info.json +5 -5
  611. package/codeyam-cli/src/webserver/server.js +35 -25
  612. package/codeyam-cli/src/webserver/server.js.map +1 -1
  613. package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam-debug.md} +48 -4
  614. package/codeyam-cli/templates/codeyam-diagnose.md +481 -0
  615. package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
  616. package/codeyam-cli/templates/codeyam-memory.md +396 -0
  617. package/codeyam-cli/templates/codeyam-new-rule.md +13 -0
  618. package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam-setup.md} +151 -4
  619. package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam-sim.md} +1 -1
  620. package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam-test.md} +1 -1
  621. package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam-verify.md} +1 -1
  622. package/codeyam-cli/templates/rule-notification-hook.py +56 -0
  623. package/codeyam-cli/templates/rule-reflection-hook.py +627 -0
  624. package/codeyam-cli/templates/rules-instructions.md +132 -0
  625. package/package.json +20 -17
  626. package/packages/ai/index.js +8 -6
  627. package/packages/ai/index.js.map +1 -1
  628. package/packages/ai/src/lib/analyzeScope.js +179 -13
  629. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  630. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  631. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  632. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +138 -9
  633. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  634. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
  635. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
  636. package/packages/ai/src/lib/astScopes/methodSemantics.js +138 -23
  637. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  638. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
  639. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
  640. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
  641. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
  642. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +7 -0
  643. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  644. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
  645. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  646. package/packages/ai/src/lib/astScopes/processExpression.js +944 -30
  647. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  648. package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
  649. package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
  650. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  651. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  652. package/packages/ai/src/lib/completionCall.js +178 -31
  653. package/packages/ai/src/lib/completionCall.js.map +1 -1
  654. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1672 -206
  655. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  656. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +7 -2
  657. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  658. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +230 -23
  659. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -1
  660. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +77 -55
  661. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  662. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  663. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  664. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  665. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  666. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +52 -3
  667. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  668. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +122 -14
  669. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  670. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
  671. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
  672. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +122 -12
  673. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  674. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  675. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  676. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
  677. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  678. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  679. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  680. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +333 -81
  681. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  682. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  683. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  684. package/packages/ai/src/lib/dataStructureChunking.js +130 -0
  685. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  686. package/packages/ai/src/lib/deepEqual.js +32 -0
  687. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  688. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  689. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  690. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  691. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  692. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
  693. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  694. package/packages/ai/src/lib/generateChangesEntityScenarios.js +78 -120
  695. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  696. package/packages/ai/src/lib/generateEntityDataStructure.js +47 -2
  697. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  698. package/packages/ai/src/lib/generateEntityScenarioData.js +1130 -83
  699. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  700. package/packages/ai/src/lib/generateEntityScenarios.js +177 -163
  701. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  702. package/packages/ai/src/lib/generateExecutionFlows.js +495 -0
  703. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
  704. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
  705. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
  706. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1807 -0
  707. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
  708. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  709. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  710. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -2
  711. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  712. package/packages/ai/src/lib/isolateScopes.js +270 -7
  713. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  714. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
  715. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
  716. package/packages/ai/src/lib/mergeStatements.js +88 -46
  717. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  718. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
  719. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
  720. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +10 -4
  721. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  722. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
  723. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  724. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -100
  725. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  726. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  727. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  728. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +83 -6
  729. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  730. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -70
  731. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  732. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
  733. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
  734. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +9 -9
  735. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  736. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  737. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  738. package/packages/ai/src/lib/resolvePathToControllable.js +677 -0
  739. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
  740. package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
  741. package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
  742. package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
  743. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  744. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +94 -1
  745. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  746. package/packages/analyze/index.js +1 -0
  747. package/packages/analyze/index.js.map +1 -1
  748. package/packages/analyze/src/lib/FileAnalyzer.js +75 -36
  749. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  750. package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
  751. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  752. package/packages/analyze/src/lib/analysisContext.js +30 -5
  753. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  754. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  755. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  756. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  757. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  758. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  759. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  760. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  761. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  762. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  763. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  764. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  765. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  766. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  767. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  768. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  769. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  770. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  771. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  772. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +211 -54
  773. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  774. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +24 -1
  775. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  776. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
  777. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  778. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  779. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  780. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  781. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  782. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
  783. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  784. package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
  785. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  786. package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
  787. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  788. package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
  789. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  790. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  791. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  792. package/packages/analyze/src/lib/files/enums/steps.js +1 -1
  793. package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
  794. package/packages/analyze/src/lib/files/getImportedExports.js +11 -7
  795. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  796. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
  797. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
  798. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +170 -40
  799. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -1
  800. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  801. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  802. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +480 -71
  803. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  804. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
  805. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  806. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +268 -66
  807. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  808. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +144 -0
  809. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
  810. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +27 -98
  811. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  812. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +2 -3
  813. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  814. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +801 -118
  815. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  816. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  817. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  818. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  819. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  820. package/packages/analyze/src/lib/index.js +1 -0
  821. package/packages/analyze/src/lib/index.js.map +1 -1
  822. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  823. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  824. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  825. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  826. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  827. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  828. package/packages/database/src/lib/analysisBranchToDb.js +1 -1
  829. package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
  830. package/packages/database/src/lib/analysisToDb.js +1 -1
  831. package/packages/database/src/lib/analysisToDb.js.map +1 -1
  832. package/packages/database/src/lib/branchToDb.js +1 -1
  833. package/packages/database/src/lib/branchToDb.js.map +1 -1
  834. package/packages/database/src/lib/commitBranchToDb.js +1 -1
  835. package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
  836. package/packages/database/src/lib/commitToDb.js +1 -1
  837. package/packages/database/src/lib/commitToDb.js.map +1 -1
  838. package/packages/database/src/lib/fileToDb.js +1 -1
  839. package/packages/database/src/lib/fileToDb.js.map +1 -1
  840. package/packages/database/src/lib/kysely/db.js +11 -1
  841. package/packages/database/src/lib/kysely/db.js.map +1 -1
  842. package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
  843. package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  844. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  845. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  846. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  847. package/packages/database/src/lib/loadAnalyses.js +45 -2
  848. package/packages/database/src/lib/loadAnalyses.js.map +1 -1
  849. package/packages/database/src/lib/loadAnalysis.js +8 -0
  850. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  851. package/packages/database/src/lib/loadBranch.js +11 -1
  852. package/packages/database/src/lib/loadBranch.js.map +1 -1
  853. package/packages/database/src/lib/loadCommit.js +7 -0
  854. package/packages/database/src/lib/loadCommit.js.map +1 -1
  855. package/packages/database/src/lib/loadCommits.js +22 -1
  856. package/packages/database/src/lib/loadCommits.js.map +1 -1
  857. package/packages/database/src/lib/loadEntities.js +23 -4
  858. package/packages/database/src/lib/loadEntities.js.map +1 -1
  859. package/packages/database/src/lib/loadEntityBranches.js +9 -0
  860. package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
  861. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +7 -4
  862. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  863. package/packages/database/src/lib/projectToDb.js +1 -1
  864. package/packages/database/src/lib/projectToDb.js.map +1 -1
  865. package/packages/database/src/lib/saveFiles.js +1 -1
  866. package/packages/database/src/lib/saveFiles.js.map +1 -1
  867. package/packages/database/src/lib/scenarioToDb.js +1 -1
  868. package/packages/database/src/lib/scenarioToDb.js.map +1 -1
  869. package/packages/database/src/lib/updateCommitMetadata.js +5 -4
  870. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  871. package/packages/generate/index.js +3 -0
  872. package/packages/generate/index.js.map +1 -1
  873. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  874. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  875. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  876. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  877. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  878. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  879. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  880. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  881. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  882. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  883. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  884. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  885. package/packages/process/index.js +3 -0
  886. package/packages/process/index.js.map +1 -0
  887. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  888. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  889. package/packages/process/src/ProcessManager.js.map +1 -0
  890. package/packages/process/src/index.js.map +1 -0
  891. package/packages/process/src/managedExecAsync.js.map +1 -0
  892. package/packages/types/index.js +0 -1
  893. package/packages/types/index.js.map +1 -1
  894. package/packages/types/src/types/Scenario.js +1 -21
  895. package/packages/types/src/types/Scenario.js.map +1 -1
  896. package/packages/utils/src/lib/fs/rsyncCopy.js +93 -2
  897. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  898. package/packages/utils/src/lib/safeFileName.js +29 -3
  899. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  900. package/scripts/finalize-analyzer.cjs +8 -76
  901. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
  902. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -409
  903. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -288
  904. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -495
  905. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
  906. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -120
  907. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  908. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  909. package/analyzer-template/process/README.md +0 -507
  910. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  911. package/background/src/lib/process/ProcessManager.js.map +0 -1
  912. package/background/src/lib/process/index.js.map +0 -1
  913. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  914. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  915. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  916. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js +0 -7
  917. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js.map +0 -1
  918. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-wXL1Z2Aq.js +0 -1
  919. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-CXFKsCOD.js +0 -41
  920. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-D-9pXIaY.js +0 -25
  921. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-4lcOlid-.js +0 -11
  922. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CUxUNEEC.js +0 -15
  923. package/codeyam-cli/src/webserver/build/client/assets/_index-DHImXdXq.js +0 -11
  924. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-2mG6mjVb.js +0 -32
  925. package/codeyam-cli/src/webserver/build/client/assets/chunk-JMJ3UQ3L-BambyYE_.js +0 -51
  926. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-CKnwPCDr.js +0 -1
  927. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DW_hdGUc.js +0 -1
  928. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DyB90fWk.js +0 -1
  929. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-D_3ero5o.js +0 -1
  930. package/codeyam-cli/src/webserver/build/client/assets/files-ClR0d32A.js +0 -1
  931. package/codeyam-cli/src/webserver/build/client/assets/globals-C6vQASxy.css +0 -1
  932. package/codeyam-cli/src/webserver/build/client/assets/keyAttributeCoverage-CTlFMihX.js +0 -1
  933. package/codeyam-cli/src/webserver/build/client/assets/manifest-09d684be.js +0 -1
  934. package/codeyam-cli/src/webserver/build/client/assets/root-BxJUvKau.js +0 -56
  935. package/codeyam-cli/src/webserver/build/client/assets/settings-DgTyB-Wg.js +0 -1
  936. package/codeyam-cli/src/webserver/build/client/assets/simulations-CoNWGt0K.js +0 -1
  937. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BMIGFP-m.js +0 -1
  938. package/codeyam-cli/src/webserver/build/client/assets/useInteractiveMode-Dk_FQqWJ.js +0 -1
  939. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DsJbgMY9.js +0 -1
  940. package/codeyam-cli/src/webserver/build/server/assets/index-CV6i1S1A.js +0 -1
  941. package/codeyam-cli/src/webserver/build/server/assets/server-build-BDlyhfrv.js +0 -175
  942. package/codeyam-cli/templates/debug-codeyam.md +0 -620
  943. package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
  944. package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
  945. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -298
  946. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
  947. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -226
  948. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
  949. package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -408
  950. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
  951. package/packages/ai/src/lib/isFrontend.js +0 -5
  952. package/packages/ai/src/lib/isFrontend.js.map +0 -1
  953. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
  954. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
  955. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -77
  956. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
  957. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  958. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  959. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  960. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  961. /package/codeyam-cli/src/webserver/build/client/assets/{api.link-scenario-value-l0sNRNKZ.js → api.agent-transcripts-l0sNRNKZ.js} +0 -0
  962. /package/codeyam-cli/src/webserver/build/client/assets/{api.update-key-attributes-l0sNRNKZ.js → api.health-l0sNRNKZ.js} +0 -0
  963. /package/codeyam-cli/src/webserver/build/client/assets/{api.update-valid-values-l0sNRNKZ.js → api.labs-unlock-l0sNRNKZ.js} +0 -0
  964. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  965. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  966. /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
@@ -82,21 +82,36 @@
82
82
  import { ScopeAnalysis } from '~codeyam/types';
83
83
  import { EquivalencyManager } from './equivalencyManagers/EquivalencyManager';
84
84
  import fillInSchemaGapsAndUnknowns from './helpers/fillInSchemaGapsAndUnknowns';
85
+ import { clearCleanKnownObjectFunctionsCache } from './helpers/cleanKnownObjectFunctions';
86
+ import { clearCleanNonObjectFunctionsCache } from './helpers/cleanNonObjectFunctions';
87
+
88
+ /**
89
+ * Patterns that indicate recursive type structures in schema paths.
90
+ * Used by hasExcessivePatternRepetition() to detect exponential path blowup.
91
+ */
92
+ const RECURSIVE_PATH_PATTERNS = [
93
+ /\.attributes\.properties\[\]/g, // TypeScript AST JSX nodes
94
+ /\.children\[\]/g, // Tree structures
95
+ /\.elements\[\]/g, // Array-like structures
96
+ /\.members\[\]/g, // Class/interface members
97
+ /\.properties\[\]/g, // Object properties
98
+ /\.items\[\]/g, // Generic items arrays
99
+ ];
85
100
  import ensureSchemaConsistency from './helpers/ensureSchemaConsistency';
86
101
  import cleanPath from './helpers/cleanPath';
87
102
  import { PathManager } from './helpers/PathManager';
88
103
  import {
89
104
  uniqueId,
90
- uniqueScopeVariables,
91
105
  uniqueScopeAndPaths,
106
+ uniqueScopeVariables,
92
107
  } from './helpers/uniqueIdUtils';
93
108
  import selectBestValue from './helpers/selectBestValue';
94
109
  import { VisitedTracker } from './helpers/VisitedTracker';
95
110
  import { DebugTracer } from './helpers/DebugTracer';
96
111
  import { BatchSchemaProcessor } from './helpers/BatchSchemaProcessor';
97
112
  import {
98
- ScopeTreeManager,
99
113
  ROOT_SCOPE_NAME,
114
+ ScopeTreeManager,
100
115
  ScopeTreeNode,
101
116
  } from './helpers/ScopeTreeManager';
102
117
  import cleanScopeNodeName from './helpers/cleanScopeNodeName';
@@ -108,6 +123,7 @@ import type {
108
123
  SerializableFunctionCallInfo,
109
124
  SerializableFunctionResult,
110
125
  SerializableScopeVariable,
126
+ EnrichedConditionalUsage,
111
127
  } from '../worker/SerializableDataStructure';
112
128
 
113
129
  /**
@@ -125,6 +141,21 @@ export interface ScopeInfo {
125
141
  isStatic?: boolean;
126
142
  isClassScope?: boolean;
127
143
  analysis?: any;
144
+ /** For JSX child scopes, the original JSX tag name (e.g., 'ChildViewer') */
145
+ jsxTagName?: string;
146
+ /**
147
+ * Gating conditions detected during JSX extraction (before JSX is simplified).
148
+ * Maps child component name to conditions that must be true for it to render.
149
+ * This is populated by processJSXForScope in isolateScopes.ts.
150
+ */
151
+ extractedGatingConditions?: {
152
+ [childComponentName: string]: Array<{
153
+ path: string;
154
+ conditionType: 'truthiness' | 'comparison';
155
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
156
+ isNegated?: boolean;
157
+ }>;
158
+ };
128
159
  }
129
160
 
130
161
  /**
@@ -303,6 +334,19 @@ export function resetScopeDataStructureMetrics() {
303
334
  followEquivalenciesEarlyExitPhase1Count = 0;
304
335
  followEquivalenciesWithWorkCount = 0;
305
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
+ }
306
350
  }
307
351
 
308
352
  // Performance: Pre-computed Sets for equivalency reason filtering (O(1) vs O(n))
@@ -353,6 +397,7 @@ const SILENTLY_IGNORED_EQUIVALENCY_REASONS = new Set([
353
397
  'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
354
398
  'transformed non-object function equivalency - Array.from() equivalency',
355
399
  'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
400
+ // 'transformed non-object function equivalency - Explicit array deconstruction equivalency value',
356
401
  ]);
357
402
 
358
403
  export class ScopeDataStructure {
@@ -380,10 +425,40 @@ export class ScopeDataStructure {
380
425
  path: string;
381
426
  conditionType: 'truthiness' | 'comparison' | 'switch';
382
427
  comparedValues?: string[];
383
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
428
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
384
429
  }>
385
430
  > = {};
386
431
 
432
+ /**
433
+ * Conditional effects collected during AST analysis.
434
+ * Tracks what setter calls happen inside conditionals (if, switch, ternary).
435
+ */
436
+ private rawConditionalEffects: import('../astScopes/types').ConditionalEffect[] =
437
+ [];
438
+
439
+ /**
440
+ * Compound conditionals collected during AST analysis.
441
+ * Groups conditions that must all be true together (e.g., a && b && c).
442
+ */
443
+ private rawCompoundConditionals: import('../astScopes/types').CompoundConditional[] =
444
+ [];
445
+
446
+ /**
447
+ * Gating conditions for child component boundaries.
448
+ * Maps child component name to the conditions that must be true for it to render.
449
+ */
450
+ private rawChildBoundaryGatingConditions: Record<
451
+ string,
452
+ import('../astScopes/types').ConditionalUsage[]
453
+ > = {};
454
+
455
+ /**
456
+ * JSX rendering usages collected during AST analysis.
457
+ * Tracks arrays rendered via .map() and strings interpolated in JSX.
458
+ */
459
+ private rawJsxRenderingUsages: import('../astScopes/types').JsxRenderingUsage[] =
460
+ [];
461
+
387
462
  private lastAddToSchemaId = 0;
388
463
  private lastEquivalencyId = 0;
389
464
  private lastEquivalencyDatabaseId = 0;
@@ -725,6 +800,11 @@ export class ScopeDataStructure {
725
800
  return;
726
801
  }
727
802
 
803
+ // PERF: Early exit for paths with repeated function-call signature patterns
804
+ if (this.hasExcessivePatternRepetition(path)) {
805
+ return;
806
+ }
807
+
728
808
  // Update chain metadata for database tracking
729
809
  if (equivalencyValueChain.length > 0) {
730
810
  equivalencyValueChain[equivalencyValueChain.length - 1].addToSchemaId =
@@ -968,8 +1048,8 @@ export class ScopeDataStructure {
968
1048
  equivalencyValueChain?: EquivalencyValueChainItem[],
969
1049
  traceId?: number,
970
1050
  ) {
971
- // DEBUG: Detect infinite loops
972
1051
  addEquivalencyCallCount++;
1052
+
973
1053
  if (addEquivalencyCallCount > 50000) {
974
1054
  console.error('INFINITE LOOP DETECTED in addEquivalency', {
975
1055
  callCount: addEquivalencyCallCount,
@@ -1395,11 +1475,32 @@ export class ScopeDataStructure {
1395
1475
  const equivalentSchemaPath = equivalentSchemaPathMap.get(remainingKey);
1396
1476
 
1397
1477
  if (equivalentSchemaPath) {
1478
+ // Skip propagation when there's a structural mismatch:
1479
+ // - schemaPath ends with [] (array element, represents an object)
1480
+ // - equivalentSchemaPath doesn't end with [] (non-array prop, usually a scalar)
1481
+ // This prevents incorrectly typing array elements as strings when they're
1482
+ // equivalent to scalar props like JSX keys (e.g., workouts[] ↔ Card().key)
1483
+ const schemaPathEndsWithArray = schemaPath.endsWith('[]');
1484
+ const equivalentEndsWithArray = equivalentSchemaPath.endsWith('[]');
1485
+ if (schemaPathEndsWithArray !== equivalentEndsWithArray) {
1486
+ // Don't propagate between array element paths and non-array paths
1487
+ continue;
1488
+ }
1489
+
1398
1490
  const value1 = scopeNode.schema[schemaPath];
1399
1491
  const value2 = equivalentScopeNode.schema[equivalentSchemaPath];
1400
1492
 
1401
1493
  const bestValue = selectBestValue(value1, value2);
1402
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
+
1403
1504
  scopeNode.schema[schemaPath] = bestValue;
1404
1505
  equivalentScopeNode.schema[equivalentSchemaPath] = bestValue;
1405
1506
  } else if (
@@ -1413,6 +1514,11 @@ export class ScopeDataStructure {
1413
1514
  ...remainingSchemaPathParts,
1414
1515
  ]);
1415
1516
 
1517
+ // PERF: Skip paths with repeated function-call signature patterns
1518
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
1519
+ continue;
1520
+ }
1521
+
1416
1522
  equivalentScopeNode.schema[newEquivalentPath] =
1417
1523
  scopeNode.schema[schemaPath];
1418
1524
  }
@@ -1503,6 +1609,77 @@ export class ScopeDataStructure {
1503
1609
  return this.pathManager.isValidPath(path);
1504
1610
  }
1505
1611
 
1612
+ /**
1613
+ * Detects if a path contains excessive repetition of the same pattern.
1614
+ *
1615
+ * This prevents exponential blowup when analyzing recursive type structures.
1616
+ * For example, TypeScript AST nodes have `.attributes.properties[]` where each
1617
+ * property is also a node with `.attributes.properties[]`. Without this check,
1618
+ * paths like `signature[0].attributes.properties[].attributes.properties[].attributes.properties[]...`
1619
+ * would be generated exponentially.
1620
+ *
1621
+ * Two detection strategies:
1622
+ * 1. Known patterns: Check RECURSIVE_PATH_PATTERNS for common recursive structures
1623
+ * 2. Generic detection: For longer paths, detect any 2-3 part segment that repeats
1624
+ *
1625
+ * @param path - The schema path to check
1626
+ * @param maxRepetitions - Maximum allowed repetitions of any pattern (default: 2)
1627
+ * @returns true if the path has excessive repetition
1628
+ */
1629
+ private hasExcessivePatternRepetition(
1630
+ path: string,
1631
+ maxRepetitions = 2,
1632
+ ): boolean {
1633
+ // Check known recursive patterns
1634
+ for (const pattern of RECURSIVE_PATH_PATTERNS) {
1635
+ const matches = path.match(pattern);
1636
+ if (matches && matches.length > maxRepetitions) {
1637
+ return true;
1638
+ }
1639
+ }
1640
+
1641
+ // Check for repeated function calls that indicate recursive type expansion.
1642
+ // E.g., localeCompare(b[])...localeCompare(b[]) means string.localeCompare
1643
+ // returns a type that again has localeCompare, causing infinite expansion.
1644
+ // We extract all function call patterns like "funcName(args)" and check if
1645
+ // the same normalized call appears more than once.
1646
+ const funcCallPattern = /(?:^|\.)[^.([]+\([^)]*\)/g;
1647
+ const funcCallMatches = path.match(funcCallPattern);
1648
+ if (funcCallMatches && funcCallMatches.length > 1) {
1649
+ const seen = new Set<string>();
1650
+ for (const match of funcCallMatches) {
1651
+ // Strip leading dot and normalize array indices
1652
+ const normalized = match.replace(/^\./, '').replace(/\[\d+\]/g, '[]');
1653
+ if (seen.has(normalized)) return true;
1654
+ seen.add(normalized);
1655
+ }
1656
+ }
1657
+
1658
+ // For longer paths, detect any repeated multi-part segments we haven't explicitly listed
1659
+ const pathParts = this.splitPath(path);
1660
+ if (pathParts.length <= 6) {
1661
+ return false;
1662
+ }
1663
+
1664
+ // Check for repeated sequences of 2-3 consecutive parts
1665
+ for (let segmentLength = 2; segmentLength <= 3; segmentLength++) {
1666
+ const seen = new Map<string, number>();
1667
+
1668
+ for (let i = 0; i <= pathParts.length - segmentLength; i++) {
1669
+ const segment = pathParts.slice(i, i + segmentLength).join('.');
1670
+ const normalizedSegment = segment.replace(/\[\d+\]/g, '[]');
1671
+ const count = (seen.get(normalizedSegment) || 0) + 1;
1672
+ seen.set(normalizedSegment, count);
1673
+
1674
+ if (count > maxRepetitions) {
1675
+ return true;
1676
+ }
1677
+ }
1678
+ }
1679
+
1680
+ return false;
1681
+ }
1682
+
1506
1683
  private addToTree(pathParts: string[]) {
1507
1684
  this.scopeTreeManager.addPath(pathParts);
1508
1685
  }
@@ -1510,17 +1687,26 @@ export class ScopeDataStructure {
1510
1687
  private setInstantiatedVariables(scopeNode: ScopeNode) {
1511
1688
  let instantiatedVariables = scopeNode.analysis?.instantiatedVariables ?? [];
1512
1689
 
1513
- for (const [path, equivalentPath] of Object.entries(
1690
+ for (const [path, rawEquivalentPath] of Object.entries(
1514
1691
  scopeNode.analysis.isolatedEquivalentVariables ?? {},
1515
1692
  )) {
1516
- if (typeof equivalentPath !== 'string') {
1517
- continue;
1518
- }
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
+ }
1519
1704
 
1520
- if (equivalentPath.startsWith('signature[')) {
1521
- const equivalentPathParts = this.splitPath(equivalentPath);
1522
- instantiatedVariables.push(equivalentPathParts[0]);
1523
- instantiatedVariables.push(path);
1705
+ if (equivalentPath.startsWith('signature[')) {
1706
+ const equivalentPathParts = this.splitPath(equivalentPath);
1707
+ instantiatedVariables.push(equivalentPathParts[0]);
1708
+ instantiatedVariables.push(path);
1709
+ }
1524
1710
  }
1525
1711
 
1526
1712
  const duplicateInstantiated = instantiatedVariables.find(
@@ -1533,9 +1719,14 @@ export class ScopeDataStructure {
1533
1719
  }
1534
1720
  }
1535
1721
 
1536
- instantiatedVariables = instantiatedVariables.filter(
1537
- (varName, index, self) => self.indexOf(varName) === index,
1538
- );
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
+ });
1539
1730
 
1540
1731
  scopeNode.instantiatedVariables = instantiatedVariables;
1541
1732
 
@@ -1556,13 +1747,19 @@ export class ScopeDataStructure {
1556
1747
  ...parentScopeNode.instantiatedVariables.filter(
1557
1748
  (v) => !v.startsWith('signature[') && !v.startsWith('returnValue'),
1558
1749
  ),
1559
- ].filter(
1560
- (varName, index, self) =>
1561
- !instantiatedVariables.includes(varName) &&
1562
- self.indexOf(varName) === index,
1563
- );
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
+ });
1564
1761
 
1565
- scopeNode.parentInstantiatedVariables = parentInstantiatedVariables;
1762
+ scopeNode.parentInstantiatedVariables = dedupedParentInstantiatedVariables;
1566
1763
  }
1567
1764
 
1568
1765
  private trackFunctionCalls(scopeNode: ScopeNode) {
@@ -1571,197 +1768,205 @@ export class ScopeDataStructure {
1571
1768
  }
1572
1769
 
1573
1770
  private determineEquivalenciesAndBuildSchema(scopeNode: ScopeNode) {
1771
+ if (!scopeNode.analysis) {
1772
+ return;
1773
+ }
1774
+
1574
1775
  const { isolatedStructure, isolatedEquivalentVariables } =
1575
1776
  scopeNode.analysis;
1576
1777
 
1577
- // DEBUG: Log all equivalencies related to useFetcher
1578
- if (
1579
- Object.keys(isolatedEquivalentVariables || {}).some(
1580
- (k) => k.includes('Fetcher') || k.includes('fetcher'),
1581
- )
1582
- ) {
1583
- console.log(
1584
- 'CodeYam DEBUG determineEquivalenciesAndBuildSchema:',
1585
- JSON.stringify(
1586
- {
1587
- scopeNodeName: scopeNode.name,
1588
- fetcherEquivalencies: Object.entries(
1589
- isolatedEquivalentVariables || {},
1590
- )
1591
- .filter(
1592
- ([k, v]) =>
1593
- k.includes('Fetcher') ||
1594
- k.includes('fetcher') ||
1595
- String(v).includes('Fetcher') ||
1596
- String(v).includes('fetcher'),
1597
- )
1598
- .reduce(
1599
- (acc, [k, v]) => {
1600
- acc[k] = v;
1601
- return acc;
1602
- },
1603
- {} as Record<string, string>,
1604
- ),
1605
- },
1606
- null,
1607
- 2,
1608
- ),
1609
- );
1610
- }
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]));
1611
1782
 
1612
1783
  const allPaths = Array.from(
1613
1784
  new Set([
1614
1785
  ...Object.keys(isolatedStructure || {}),
1615
1786
  ...Object.keys(isolatedEquivalentVariables || {}),
1616
- ...Object.values(isolatedEquivalentVariables || {}),
1787
+ ...flattenedEquivValues,
1617
1788
  ]),
1618
1789
  );
1619
1790
 
1620
1791
  for (let path in isolatedEquivalentVariables) {
1621
- let equivalentValue = isolatedEquivalentVariables?.[path];
1622
-
1623
- if (equivalentValue && this.isValidPath(equivalentValue)) {
1624
- path = cleanPath(path.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1625
- equivalentValue = cleanPath(
1626
- equivalentValue.replace(/::cyDuplicateKey\d+::/g, ''),
1627
- allPaths,
1628
- );
1629
-
1630
- this.addEquivalency(
1631
- path,
1632
- equivalentValue,
1633
- scopeNode.name,
1634
- scopeNode,
1635
- 'original equivalency',
1636
- );
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
+ );
1637
1826
 
1638
- // Propagate equivalencies involving parent-scope variables to those parent scopes.
1639
- // This handles patterns like: collected.push({...entity}) where 'collected' is defined
1640
- // in a parent scope. The equivalency collected[] -> push().signature[0] needs to be
1641
- // visible when tracing from the parent scope.
1642
- const rootVariable = this.extractRootVariable(path);
1643
- const equivalentRootVariable =
1644
- this.extractRootVariable(equivalentValue);
1645
-
1646
- // Skip propagation for self-referential reassignment patterns like:
1647
- // x = x.method().functionCallReturnValue
1648
- // where the path IS the variable itself (not a sub-path like x[] or x.prop).
1649
- // These create circular references since both sides reference the same variable.
1650
- //
1651
- // But DO propagate for patterns like collected[] -> collected.push(...).signature[0]
1652
- // where the path has additional segments beyond the root variable.
1653
- const pathIsJustRootVariable = path === rootVariable;
1654
- const isSelfReferentialReassignment =
1655
- 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;
1656
1845
 
1657
- if (
1658
- rootVariable &&
1659
- !isSelfReferentialReassignment &&
1660
- scopeNode.parentInstantiatedVariables?.includes(rootVariable)
1661
- ) {
1662
- // Find the parent scope where this variable is defined
1663
- for (const parentScopeName of scopeNode.tree || []) {
1664
- const parentScope = this.scopeNodes[parentScopeName];
1665
- if (parentScope?.instantiatedVariables?.includes(rootVariable)) {
1666
- // Add the equivalency to the parent scope as well
1667
- this.addEquivalency(
1668
- path,
1669
- equivalentValue,
1670
- scopeNode.name, // The equivalent path's scope remains the child scope
1671
- parentScope, // But store it in the parent scope's equivalencies
1672
- 'propagated parent-variable equivalency',
1673
- );
1674
- 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
+ }
1675
1865
  }
1676
1866
  }
1677
- }
1678
1867
 
1679
- // Propagate sub-property equivalencies when the equivalentValue is a simple variable
1680
- // that has sub-properties defined in the isolatedEquivalentVariables.
1681
- // This handles cases like: dataItem={{ structure: completeDataStructure }}
1682
- // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
1683
- // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
1684
- const isSimpleVariable =
1685
- !equivalentValue.startsWith('signature[') &&
1686
- !equivalentValue.includes('functionCallReturnValue') &&
1687
- !equivalentValue.includes('.') &&
1688
- !equivalentValue.includes('[');
1689
-
1690
- if (isSimpleVariable) {
1691
- // Look in current scope and all parent scopes for sub-properties
1692
- const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1693
- for (const scopeName of scopesToCheck) {
1694
- const checkScope = this.scopeNodes[scopeName];
1695
- if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1696
-
1697
- for (const [subPath, subValue] of Object.entries(
1698
- checkScope.analysis.isolatedEquivalentVariables,
1699
- )) {
1700
- // Check if this is a sub-property of the equivalentValue variable
1701
- // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
1702
- const matchesDot = subPath.startsWith(equivalentValue + '.');
1703
- const matchesBracket = subPath.startsWith(equivalentValue + '[');
1704
- if (matchesDot || matchesBracket) {
1705
- const subPropertyPath = subPath.substring(
1706
- equivalentValue.length,
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 + '[',
1707
1901
  );
1708
- const newPath = cleanPath(path + subPropertyPath, allPaths);
1709
- const newEquivalentValue = cleanPath(
1710
- (subValue as string).replace(/::cyDuplicateKey\d+::/g, ''),
1711
- allPaths,
1712
- );
1713
-
1714
- if (
1715
- newEquivalentValue &&
1716
- this.isValidPath(newEquivalentValue)
1717
- ) {
1718
- this.addEquivalency(
1719
- newPath,
1720
- newEquivalentValue,
1721
- checkScope.name, // Use the scope where the sub-property was found
1722
- scopeNode,
1723
- 'propagated sub-property equivalency',
1902
+ if (matchesDot || matchesBracket) {
1903
+ const subPropertyPath = subPath.substring(
1904
+ equivalentValue.length,
1724
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
+ }
1725
1928
  }
1726
- }
1727
1929
 
1728
- // Also check if equivalentValue itself maps to a functionCallReturnValue
1729
- // e.g., result = useMemo(...).functionCallReturnValue
1730
- if (
1731
- subPath === equivalentValue &&
1732
- typeof subValue === 'string' &&
1733
- subValue.endsWith('.functionCallReturnValue')
1734
- ) {
1735
- this.propagateFunctionCallReturnSubProperties(
1736
- path,
1737
- subValue,
1738
- scopeNode,
1739
- allPaths,
1740
- );
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
+ }
1741
1946
  }
1742
1947
  }
1743
1948
  }
1744
- }
1745
1949
 
1746
- // Handle function call return values by propagating returnValue.* sub-properties
1747
- // from the callback scope to the usage path
1748
- if (equivalentValue.endsWith('.functionCallReturnValue')) {
1749
- this.propagateFunctionCallReturnSubProperties(
1750
- path,
1751
- equivalentValue,
1752
- scopeNode,
1753
- allPaths,
1754
- );
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
+ );
1755
1959
 
1756
- // Track which variable receives the return value of each function call
1757
- // This enables generating separate mock data for each call site
1758
- this.trackReceivingVariable(path, equivalentValue);
1759
- }
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
+ }
1760
1964
 
1761
- // Also track variables that receive destructured properties from function call return values
1762
- // e.g., "userData" -> "db.query('users').functionCallReturnValue.data"
1763
- if (equivalentValue.includes('.functionCallReturnValue.')) {
1764
- 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
+ }
1765
1970
  }
1766
1971
  }
1767
1972
  }
@@ -1771,7 +1976,7 @@ export class ScopeDataStructure {
1771
1976
  this.batchProcessor = new BatchSchemaProcessor();
1772
1977
  this.batchQueuedSet = new Set();
1773
1978
 
1774
- for (const key of Array.from(allPaths)) {
1979
+ for (const key of allPaths) {
1775
1980
  let value = isolatedStructure[key] ?? 'unknown';
1776
1981
 
1777
1982
  if (['null', 'undefined'].includes(value)) {
@@ -1812,7 +2017,19 @@ export class ScopeDataStructure {
1812
2017
  private processBatchQueue(): void {
1813
2018
  if (!this.batchProcessor) return;
1814
2019
 
2020
+ let iterations = 0;
2021
+
1815
2022
  while (this.batchProcessor.hasWork()) {
2023
+ iterations++;
2024
+
2025
+ // Safety: detect potential infinite loops
2026
+ if (iterations > 100000) {
2027
+ console.error(
2028
+ `[ScopeDataStructure] processBatchQueue exceeded 100k iterations, possible infinite loop!`,
2029
+ );
2030
+ break;
2031
+ }
2032
+
1816
2033
  const item = this.batchProcessor.getNextWork();
1817
2034
  if (!item) break;
1818
2035
 
@@ -1870,26 +2087,6 @@ export class ScopeDataStructure {
1870
2087
  const functionCallInfo =
1871
2088
  this.getExternalFunctionCallsIndex().get(searchKey);
1872
2089
 
1873
- // DEBUG: Track useFetcher calls
1874
- if (searchKey === 'useFetcher' || callSignature.includes('useFetcher')) {
1875
- console.log(
1876
- 'CodeYam DEBUG trackReceivingVariable:',
1877
- JSON.stringify(
1878
- {
1879
- receivingVariable,
1880
- equivalentValue,
1881
- callSignature,
1882
- searchKey,
1883
- foundFunctionCallInfo: !!functionCallInfo,
1884
- existingRecvVars: functionCallInfo?.receivingVariableNames,
1885
- existingCallSigToVar: functionCallInfo?.callSignatureToVariable,
1886
- },
1887
- null,
1888
- 2,
1889
- ),
1890
- );
1891
- }
1892
-
1893
2090
  if (!functionCallInfo) {
1894
2091
  return;
1895
2092
  }
@@ -1950,9 +2147,18 @@ export class ScopeDataStructure {
1950
2147
  const checkScope = this.scopeNodes[scopeName];
1951
2148
  if (!checkScope?.analysis?.isolatedEquivalentVariables) continue;
1952
2149
 
1953
- const functionRef =
2150
+ const rawFunctionRef =
1954
2151
  checkScope.analysis.isolatedEquivalentVariables[functionName];
1955
- 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') {
1956
2162
  callbackScopeName = functionRef.slice(0, -1);
1957
2163
  break;
1958
2164
  }
@@ -1980,19 +2186,24 @@ export class ScopeDataStructure {
1980
2186
 
1981
2187
  const isolatedVars = callbackScope.analysis.isolatedEquivalentVariables;
1982
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
+
1983
2195
  // First, check if returnValue is an alias to another variable (e.g., returnValue = intermediate)
1984
2196
  // If so, we need to look for that variable's sub-properties too
1985
2197
  const returnValueAlias =
1986
- typeof isolatedVars.returnValue === 'string' &&
1987
- !isolatedVars.returnValue.includes('.')
1988
- ? isolatedVars.returnValue
2198
+ typeof firstReturnValue === 'string' && !firstReturnValue.includes('.')
2199
+ ? firstReturnValue
1989
2200
  : undefined;
1990
2201
 
1991
2202
  // Pattern 3: Object.keys(X).reduce() - the reduce result has the same sub-properties as X
1992
2203
  // When returnValue = "Object.keys(source).reduce(...).functionCallReturnValue", look for source.* sub-properties
1993
2204
  let reduceSourceVar: string | undefined;
1994
- if (typeof isolatedVars.returnValue === 'string') {
1995
- const reduceMatch = isolatedVars.returnValue.match(
2205
+ if (typeof firstReturnValue === 'string') {
2206
+ const reduceMatch = firstReturnValue.match(
1996
2207
  /^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/,
1997
2208
  );
1998
2209
  if (reduceMatch) {
@@ -2000,7 +2211,14 @@ export class ScopeDataStructure {
2000
2211
  }
2001
2212
  }
2002
2213
 
2003
- 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
+
2004
2222
  // Check for direct returnValue.* sub-properties
2005
2223
  const isReturnValueSub =
2006
2224
  subPath.startsWith('returnValue.') ||
@@ -2018,57 +2236,59 @@ export class ScopeDataStructure {
2018
2236
  (subPath.startsWith(reduceSourceVar + '.') ||
2019
2237
  subPath.startsWith(reduceSourceVar + '['));
2020
2238
 
2021
- if (
2022
- typeof subValue !== 'string' ||
2023
- (!isReturnValueSub && !isAliasSub && !isReduceSourceSub)
2024
- )
2025
- continue;
2026
-
2027
- // Convert alias/reduceSource paths to returnValue paths
2028
- let effectiveSubPath = subPath;
2029
- if (isAliasSub && !isReturnValueSub) {
2030
- // Replace the alias prefix with returnValue
2031
- effectiveSubPath =
2032
- 'returnValue' + subPath.substring(returnValueAlias!.length);
2033
- } else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
2034
- // Replace the reduce source prefix with returnValue
2035
- effectiveSubPath =
2036
- 'returnValue' + subPath.substring(reduceSourceVar!.length);
2037
- }
2038
- const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
2039
- const newPath = cleanPath(path + subPropertyPath, allPaths);
2040
- let newEquivalentValue = cleanPath(
2041
- subValue.replace(/::cyDuplicateKey\d+::/g, ''),
2042
- allPaths,
2043
- );
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
+ );
2044
2263
 
2045
- // Resolve variable references through parent scope equivalencies
2046
- const resolved = this.resolveVariableThroughParentScopes(
2047
- newEquivalentValue,
2048
- callbackScope,
2049
- allPaths,
2050
- );
2051
- newEquivalentValue = resolved.resolvedPath;
2052
- 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;
2053
2272
 
2054
- if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
2055
- continue;
2273
+ if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
2274
+ continue;
2056
2275
 
2057
- this.addEquivalency(
2058
- newPath,
2059
- newEquivalentValue,
2060
- equivalentScopeName,
2061
- scopeNode,
2062
- 'propagated function call return sub-property equivalency',
2063
- );
2276
+ this.addEquivalency(
2277
+ newPath,
2278
+ newEquivalentValue,
2279
+ equivalentScopeName,
2280
+ scopeNode,
2281
+ 'propagated function call return sub-property equivalency',
2282
+ );
2064
2283
 
2065
- // Ensure the database entry has the usage path
2066
- this.addUsageToEquivalencyDatabaseEntry(
2067
- newPath,
2068
- newEquivalentValue,
2069
- equivalentScopeName,
2070
- scopeNode.name,
2071
- );
2284
+ // Ensure the database entry has the usage path
2285
+ this.addUsageToEquivalencyDatabaseEntry(
2286
+ newPath,
2287
+ newEquivalentValue,
2288
+ equivalentScopeName,
2289
+ scopeNode.name,
2290
+ );
2291
+ }
2072
2292
  }
2073
2293
  }
2074
2294
 
@@ -2108,8 +2328,15 @@ export class ScopeDataStructure {
2108
2328
  const parentScope = this.scopeNodes[parentScopeName];
2109
2329
  if (!parentScope?.analysis?.isolatedEquivalentVariables) continue;
2110
2330
 
2111
- const rootEquiv =
2331
+ const rawRootEquiv =
2112
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');
2113
2340
  if (typeof rootEquiv === 'string') {
2114
2341
  return {
2115
2342
  resolvedPath: cleanPath(rootEquiv + restOfPath, allPaths),
@@ -2384,11 +2611,27 @@ export class ScopeDataStructure {
2384
2611
  relevantSubPathParts.every((part, i) => part === schemaPathParts[i]) &&
2385
2612
  equivalentValue.scopeNodeName === scopeNode.name
2386
2613
  ) {
2614
+ // DEBUG
2387
2615
  continue;
2388
2616
  }
2389
2617
 
2390
2618
  const newEquivalentPath = this.joinPathParts([schemaPath, remainingPath]);
2391
2619
 
2620
+ // PERF: Detect repeated patterns in paths to prevent exponential blowup
2621
+ // Paths like `signature[0].attributes.properties[].attributes.properties[]...`
2622
+ // indicate recursive type structures that cause exponential schema explosion
2623
+ if (this.hasExcessivePatternRepetition(newEquivalentPath)) {
2624
+ if (traceId && debugLevel > 0) {
2625
+ console.info(
2626
+ 'Debug: skipping path with excessive pattern repetition',
2627
+ {
2628
+ path: newEquivalentPath,
2629
+ },
2630
+ );
2631
+ }
2632
+ continue;
2633
+ }
2634
+
2392
2635
  if (!equivalentScopeNode) {
2393
2636
  if (traceId) {
2394
2637
  console.info('Debug Propagation: missing equivalent scope info', {
@@ -2555,6 +2798,8 @@ export class ScopeDataStructure {
2555
2798
  usageEquivalency.scopeNodeName,
2556
2799
  ) as ScopeNode;
2557
2800
 
2801
+ if (!usageScopeNode) continue;
2802
+
2558
2803
  // Guard against infinite recursion by tracking which paths we've already
2559
2804
  // added from addComplexSourcePathVariables
2560
2805
  if (
@@ -2634,6 +2879,8 @@ export class ScopeDataStructure {
2634
2879
  usageEquivalency.scopeNodeName,
2635
2880
  ) as ScopeNode;
2636
2881
 
2882
+ if (!usageScopeNode) continue;
2883
+
2637
2884
  // This is put in place to avoid propagating array functions like 'filter' through complex equivalencies
2638
2885
  // but may cause problems if the funtion call is not on a known object (e.g. string or array)
2639
2886
  if (
@@ -2760,10 +3007,105 @@ export class ScopeDataStructure {
2760
3007
  this.intermediatesOrderIndex.set(pathId, databaseEntry);
2761
3008
 
2762
3009
  if (intermediateIndex === 0) {
2763
- const isValidSourceCandidate =
3010
+ let isValidSourceCandidate =
2764
3011
  pathInfo.schemaPath.startsWith('signature[') ||
2765
3012
  pathInfo.schemaPath.includes('functionCallReturnValue');
2766
- 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
+ ) {
2767
3109
  databaseEntry.sourceCandidates.push(pathInfo);
2768
3110
  }
2769
3111
  } else {
@@ -2991,6 +3333,14 @@ export class ScopeDataStructure {
2991
3333
  }
2992
3334
  }
2993
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
+
2994
3344
  fillInSchemaGapsAndUnknowns(scopeNode, fillInUnknowns);
2995
3345
 
2996
3346
  if (final) {
@@ -3005,25 +3355,116 @@ export class ScopeDataStructure {
3005
3355
  }
3006
3356
  }
3007
3357
 
3008
- private filterAndConvertSchema({
3009
- filterPath,
3010
- newPath,
3011
- schema,
3012
- }: {
3013
- filterPath: string;
3014
- newPath?: string;
3015
- schema: Record<string, string>;
3016
- }): Record<string, string> {
3017
- const filterPathParts = this.splitPath(filterPath);
3018
- return Object.keys(schema).reduce(
3019
- (acc, key) => {
3020
- const keyParts = this.splitPath(key);
3021
- if (!filterPathParts.every((part, index) => keyParts[index] === part)) {
3022
- return acc;
3023
- }
3024
- const newKey = this.joinPathParts([
3025
- newPath ?? filterPath,
3026
- ...keyParts.slice(filterPathParts.length),
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
+
3449
+ private filterAndConvertSchema({
3450
+ filterPath,
3451
+ newPath,
3452
+ schema,
3453
+ }: {
3454
+ filterPath: string;
3455
+ newPath?: string;
3456
+ schema: Record<string, string>;
3457
+ }): Record<string, string> {
3458
+ const filterPathParts = this.splitPath(filterPath);
3459
+ return Object.keys(schema).reduce(
3460
+ (acc, key) => {
3461
+ const keyParts = this.splitPath(key);
3462
+ if (!filterPathParts.every((part, index) => keyParts[index] === part)) {
3463
+ return acc;
3464
+ }
3465
+ const newKey = this.joinPathParts([
3466
+ newPath ?? filterPath,
3467
+ ...keyParts.slice(filterPathParts.length),
3027
3468
  ]);
3028
3469
  acc[newKey] = schema[key];
3029
3470
  return acc;
@@ -3091,6 +3532,9 @@ export class ScopeDataStructure {
3091
3532
  equivalentValueSchemaPathParts.length,
3092
3533
  ),
3093
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;
3094
3538
  resolvedSchema[newKey] = value;
3095
3539
  }
3096
3540
  }
@@ -3113,6 +3557,8 @@ export class ScopeDataStructure {
3113
3557
  if (!subSchema) continue;
3114
3558
 
3115
3559
  for (const resolvedKey in subSchema) {
3560
+ // PERF: Skip keys with repeated function-call signature patterns
3561
+ if (this.hasExcessivePatternRepetition(resolvedKey)) continue;
3116
3562
  if (
3117
3563
  !resolvedSchema[resolvedKey] ||
3118
3564
  subSchema[resolvedKey] === 'unknown'
@@ -3298,10 +3744,29 @@ export class ScopeDataStructure {
3298
3744
  }
3299
3745
  }
3300
3746
  }
3301
- return mergedSchema;
3747
+ return this.filterDuplicateKeys(mergedSchema);
3302
3748
  }
3303
3749
 
3304
- return schema;
3750
+ return this.filterDuplicateKeys(schema);
3751
+ }
3752
+
3753
+ /**
3754
+ * Filter out ::cyDuplicateKey:: entries from a schema.
3755
+ * These are internal markers for tracking variable reassignments
3756
+ * and should not appear in output schemas or LLM prompts.
3757
+ */
3758
+ private filterDuplicateKeys(
3759
+ schema: Record<string, string>,
3760
+ ): Record<string, string> {
3761
+ return Object.entries(schema).reduce(
3762
+ (acc, [key, value]) => {
3763
+ if (!key.includes('::cyDuplicateKey')) {
3764
+ acc[key] = value;
3765
+ }
3766
+ return acc;
3767
+ },
3768
+ {} as Record<string, string>,
3769
+ );
3305
3770
  }
3306
3771
 
3307
3772
  getEquivalencies(scopeName?: string) {
@@ -3331,26 +3796,270 @@ export class ScopeDataStructure {
3331
3796
  return {};
3332
3797
  }
3333
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
+
3334
3833
  const entries = this.equivalencyDatabase.filter((entry) =>
3335
- entry.usages.some((usage) => usage.scopeNodeName === scopeNode.name),
3834
+ entry.usages.some(usageMatchesScope),
3336
3835
  );
3337
- return entries.reduce(
3338
- (acc, entry) => {
3339
- if (entry.sourceCandidates.length === 0) return acc;
3340
- const usages = entry.usages.filter(
3341
- (u) => u.scopeNodeName === scopeNode.name,
3342
- );
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);
3343
3957
  for (const usage of usages) {
3344
- acc[usage.schemaPath] ||= [];
3345
- 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
+ }
3346
3964
  }
3347
- return acc;
3965
+ return result;
3348
3966
  },
3349
3967
  {} as Record<
3350
3968
  string,
3351
3969
  Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[]
3352
3970
  >,
3353
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
+ }
3354
4063
  }
3355
4064
 
3356
4065
  getUsageEquivalencies(functionName?: string) {
@@ -3409,12 +4118,14 @@ export class ScopeDataStructure {
3409
4118
  );
3410
4119
 
3411
4120
  const equivalencies = this.getEquivalencies(functionName);
4121
+ const scopeName = functionName ?? this.scopeTreeManager.getRootName();
4122
+
3412
4123
  for (const equivalenceKey in equivalencies ?? {}) {
3413
4124
  for (const equivalenceValue of equivalencies[equivalenceKey]) {
3414
4125
  const schemaPath = equivalenceValue.schemaPath;
3415
4126
  if (
3416
4127
  schemaPath.startsWith('signature[') &&
3417
- equivalenceValue.scopeNodeName === functionName &&
4128
+ equivalenceValue.scopeNodeName === scopeName &&
3418
4129
  !signatureInSchema[schemaPath]
3419
4130
  ) {
3420
4131
  signatureInSchema[schemaPath] = 'unknown';
@@ -3428,16 +4139,190 @@ export class ScopeDataStructure {
3428
4139
  equivalencies,
3429
4140
  );
3430
4141
 
3431
- // CRITICAL: Set onlyEquivalencies to true to prevent database modifications
3432
- // during this "getter" method. validateSchema triggers manager.finalize which
3433
- // can call addToSchema -> addToEquivalencyDatabase -> mergeEquivalencyDatabaseEntries,
3434
- // which would incorrectly remove entries from the database.
3435
- const wasOnlyEquivalencies = this.onlyEquivalencies;
3436
- this.onlyEquivalencies = true;
3437
4142
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
3438
- this.onlyEquivalencies = wasOnlyEquivalencies;
3439
4143
 
3440
- return tempScopeNode.schema;
4144
+ // After validateSchema has filled in types, propagate nested paths from
4145
+ // variables to their signature equivalents.
4146
+ // e.g., workouts[].activity_type -> signature[0].workouts[].activity_type
4147
+ //
4148
+ // Build a map of variable names that are equivalent to signature paths
4149
+ // e.g., { 'workouts': 'signature[0].workouts' }
4150
+ const variableToSignatureMap: Record<string, string> = {};
4151
+
4152
+ for (const equivalenceKey in equivalencies ?? {}) {
4153
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
4154
+ const schemaPath = equivalenceValue.schemaPath;
4155
+ // Track which variables map to signature paths
4156
+ // equivalenceKey is the variable name (e.g., 'workouts')
4157
+ // schemaPath is where it comes from (e.g., 'signature[0].workouts')
4158
+ if (
4159
+ schemaPath.startsWith('signature[') &&
4160
+ equivalenceValue.scopeNodeName === scopeName
4161
+ ) {
4162
+ variableToSignatureMap[equivalenceKey] = schemaPath;
4163
+ }
4164
+ }
4165
+ }
4166
+
4167
+ // Enrich schema with deeply nested paths from internal function call scopes.
4168
+ // When a function call like traverse(tree) exists, and traverse's scope has
4169
+ // signature[0].children[path][entityName] (from propagateParameterToSignaturePaths),
4170
+ // we need to map those paths back to the argument variable (tree) in this scope.
4171
+ // This handles cases where cycle detection prevented the equivalency chain from
4172
+ // propagating deep paths during Phase 2 batch queue processing.
4173
+ for (const equivalenceKey in equivalencies ?? {}) {
4174
+ // Look for keys matching function call pattern: funcName(...).signature[N]
4175
+ const funcCallMatch = equivalenceKey.match(
4176
+ /^([^(]+)\(.*?\)\.(signature\[\d+\])$/,
4177
+ );
4178
+ if (!funcCallMatch) continue;
4179
+
4180
+ const calledFunctionName = funcCallMatch[1];
4181
+ const signatureParam = funcCallMatch[2]; // e.g., "signature[0]"
4182
+
4183
+ for (const equivalenceValue of equivalencies[equivalenceKey]) {
4184
+ if (equivalenceValue.scopeNodeName !== scopeName) continue;
4185
+
4186
+ const targetVariable = equivalenceValue.schemaPath;
4187
+
4188
+ // Get the called function's schema (includes propagated parameter paths)
4189
+ const childSchema = this.getSchema({
4190
+ scopeName: calledFunctionName,
4191
+ });
4192
+ if (!childSchema) continue;
4193
+
4194
+ // Map child function's signature paths to parent variable paths
4195
+ const sigPrefix = signatureParam + '.';
4196
+ const sigBracketPrefix = signatureParam + '[';
4197
+ for (const childKey in childSchema) {
4198
+ let suffix: string | null = null;
4199
+ if (childKey.startsWith(sigPrefix)) {
4200
+ suffix = childKey.slice(signatureParam.length);
4201
+ } else if (childKey.startsWith(sigBracketPrefix)) {
4202
+ suffix = childKey.slice(signatureParam.length);
4203
+ }
4204
+
4205
+ if (suffix !== null) {
4206
+ const parentKey = targetVariable + suffix;
4207
+ if (!schema[parentKey]) {
4208
+ schema[parentKey] = childSchema[childKey];
4209
+ }
4210
+ }
4211
+ }
4212
+ }
4213
+ }
4214
+
4215
+ // Helper: check if a type is a concrete scalar that cannot have sub-properties.
4216
+ // e.g., "string", "number | undefined", "boolean | null" are scalar.
4217
+ // "object", "array", "function", "unknown", "Workout", etc. are NOT scalar.
4218
+ const SCALAR_TYPES = new Set([
4219
+ 'string',
4220
+ 'number',
4221
+ 'boolean',
4222
+ 'bigint',
4223
+ 'symbol',
4224
+ 'void',
4225
+ 'never',
4226
+ ]);
4227
+ const isDefinitelyScalarType = (type: string): boolean => {
4228
+ const parts = type.split('|').map((s) => s.trim());
4229
+ const base = parts.filter((s) => s !== 'undefined' && s !== 'null');
4230
+ return base.length > 0 && base.every((b) => SCALAR_TYPES.has(b));
4231
+ };
4232
+
4233
+ // Propagate nested paths from variables to their signature equivalents
4234
+ // e.g., if workouts = signature[0].workouts, then workouts[].title becomes
4235
+ // signature[0].workouts[].title
4236
+ for (const schemaKey in schema) {
4237
+ // Skip keys that already start with signature[
4238
+ if (schemaKey.startsWith('signature[')) continue;
4239
+
4240
+ // Check if this key starts with a variable that maps to a signature path
4241
+ for (const [variableName, signaturePath] of Object.entries(
4242
+ variableToSignatureMap,
4243
+ )) {
4244
+ // Check if schemaKey starts with variableName followed by a property accessor
4245
+ // e.g., 'workouts[]' starts with 'workouts'
4246
+ if (
4247
+ schemaKey === variableName ||
4248
+ schemaKey.startsWith(variableName + '.') ||
4249
+ schemaKey.startsWith(variableName + '[')
4250
+ ) {
4251
+ // Transform the path: replace the variable prefix with the signature path
4252
+ const suffix = schemaKey.slice(variableName.length);
4253
+ const signatureKey = signaturePath + suffix;
4254
+
4255
+ // Add to schema if not already present
4256
+ if (!tempScopeNode.schema[signatureKey]) {
4257
+ // Check if this path represents variable conflation:
4258
+ // When a standalone variable (e.g., showWorkoutForm from useState)
4259
+ // appears as a sub-property of a scalar-typed ancestor (e.g.,
4260
+ // activity_type = "string"), it's from scope conflation, not real
4261
+ // property access. Block these while allowing legitimate built-in
4262
+ // accesses like string.length or string.slice.
4263
+ let isConflatedPath = false;
4264
+ let checkPos = signaturePath.length;
4265
+ while (true) {
4266
+ checkPos = signatureKey.indexOf('.', checkPos + 1);
4267
+ if (checkPos === -1) break;
4268
+ const ancestorPath = signatureKey.substring(0, checkPos);
4269
+ const ancestorType = tempScopeNode.schema[ancestorPath];
4270
+ if (ancestorType && isDefinitelyScalarType(ancestorType)) {
4271
+ // Ancestor is scalar — check if the immediate sub-property
4272
+ // is also a standalone variable (indicating conflation)
4273
+ const afterDot = signatureKey.substring(checkPos + 1);
4274
+ const nextSep = afterDot.search(/[.\[]/);
4275
+ const subPropName =
4276
+ nextSep === -1 ? afterDot : afterDot.substring(0, nextSep);
4277
+ if (schema[subPropName] !== undefined) {
4278
+ isConflatedPath = true;
4279
+ break;
4280
+ }
4281
+ }
4282
+ }
4283
+
4284
+ if (!isConflatedPath) {
4285
+ tempScopeNode.schema[signatureKey] = schema[schemaKey];
4286
+ }
4287
+ }
4288
+ }
4289
+ }
4290
+ }
4291
+
4292
+ // Post-process: filter out conflated signature paths.
4293
+ // During phase 2 scope analysis, useState(false) conflation can create
4294
+ // bad paths like signature[0].mockWorkouts[].activity_type.showWorkoutForm
4295
+ // directly in scopeNode.schema. These flow through signatureInSchema into
4296
+ // tempScopeNode.schema without any guard. Filter them out here by checking:
4297
+ // 1. An ancestor in the path has a concrete scalar type (string, number, boolean, etc.)
4298
+ // 2. The immediate sub-property of that scalar ancestor is also a standalone
4299
+ // variable in the schema (indicating conflation, not a real property access)
4300
+ for (const key of Object.keys(tempScopeNode.schema)) {
4301
+ if (!key.startsWith('signature[')) continue;
4302
+
4303
+ // Walk through the path looking for scalar-typed ancestors
4304
+ let pos = 0;
4305
+ while (true) {
4306
+ pos = key.indexOf('.', pos + 1);
4307
+ if (pos === -1) break;
4308
+ const ancestorPath = key.substring(0, pos);
4309
+ const ancestorType = tempScopeNode.schema[ancestorPath];
4310
+ if (ancestorType && isDefinitelyScalarType(ancestorType)) {
4311
+ // Found a scalar ancestor — check if the sub-property name
4312
+ // is a standalone variable in the getSchema() result
4313
+ const afterDot = key.substring(pos + 1);
4314
+ const nextSep = afterDot.search(/[.\[]/);
4315
+ const subPropName =
4316
+ nextSep === -1 ? afterDot : afterDot.substring(0, nextSep);
4317
+ if (schema[subPropName] !== undefined) {
4318
+ delete tempScopeNode.schema[key];
4319
+ break;
4320
+ }
4321
+ }
4322
+ }
4323
+ }
4324
+
4325
+ return this.filterDuplicateKeys(tempScopeNode.schema);
3441
4326
  }
3442
4327
 
3443
4328
  getReturnValue({
@@ -3499,7 +4384,17 @@ export class ScopeDataStructure {
3499
4384
  // Include function paths even if their return value wasn't captured
3500
4385
  // This ensures methods like onAuthStateChange are included in the schema
3501
4386
  // But exclude signature entries (they should only be included via functionCallReturnValue paths)
3502
- (schema[key] === 'function' && key.indexOf('signature[') === -1),
4387
+ // Also exclude bare function call signatures - paths that are JUST a call like
4388
+ // "useCustomSizes(projectSlug)" should not be included as return values.
4389
+ // These represent "the function exists" not actual return data, and including
4390
+ // them causes nested path bugs in dependencySchemas.
4391
+ (schema[key] === 'function' &&
4392
+ key.indexOf('signature[') === -1 &&
4393
+ // Exclude bare call signatures: function calls with no dots OUTSIDE parentheses
4394
+ // e.g., "useCustomSizes(projectSlug)" is bare (exclude)
4395
+ // e.g., "loadProject({nested.property})" is bare - dots are inside args (exclude)
4396
+ // e.g., "getSupabase().auth.method()" has dots outside - method chain (include)
4397
+ !this.isBareCallSignature(key)),
3503
4398
  )
3504
4399
  .reduce(
3505
4400
  (acc, key) => {
@@ -3509,7 +4404,10 @@ export class ScopeDataStructure {
3509
4404
  for (const path in schema) {
3510
4405
  const pathParts = this.splitPath(path);
3511
4406
  if (pathParts.every((p, i) => keyParts[i] === p)) {
3512
- acc[path] = schema[path];
4407
+ // Also exclude bare call signatures from prefix paths
4408
+ if (!this.isBareCallSignature(path)) {
4409
+ acc[path] = schema[path];
4410
+ }
3513
4411
  }
3514
4412
  }
3515
4413
 
@@ -3530,7 +4428,59 @@ export class ScopeDataStructure {
3530
4428
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
3531
4429
  this.onlyEquivalencies = wasOnlyEquivalencies;
3532
4430
 
3533
- return tempScopeNode.schema;
4431
+ // Remove bare call signatures from the return value schema.
4432
+ // fillInSchemaGapsAndUnknowns may add parent paths like "useCustomSizes(projectSlug)"
4433
+ // when it sees "useCustomSizes(projectSlug).functionCallReturnValue". These bare
4434
+ // call signatures represent "the function exists" not actual return data, and
4435
+ // including them causes nested path bugs in dependencySchemas.
4436
+ const resultSchema = tempScopeNode.schema;
4437
+ for (const key of Object.keys(resultSchema)) {
4438
+ if (this.isBareCallSignature(key)) {
4439
+ delete resultSchema[key];
4440
+ }
4441
+ }
4442
+
4443
+ return resultSchema;
4444
+ }
4445
+
4446
+ /**
4447
+ * Checks if a schema key is a "bare call signature" - a function call with no
4448
+ * method chain before it and no path segments after it.
4449
+ *
4450
+ * A bare call signature represents "this function exists" rather than actual
4451
+ * return data, and including them causes nested path bugs in dependencySchemas.
4452
+ *
4453
+ * Examples:
4454
+ * - "useCustomSizes(projectSlug)" -> bare (true)
4455
+ * - "loadProject({nested.property})" -> bare (dots are inside args, true)
4456
+ * - "getSupabase().auth.method()" -> not bare (has dots outside parens, false)
4457
+ * - "useProject().functionCallReturnValue" -> not bare (has path after, false)
4458
+ */
4459
+ private isBareCallSignature(key: string): boolean {
4460
+ // Must end with ) and contain ( to be a call
4461
+ if (!key.endsWith(')') || key.indexOf('(') === -1) {
4462
+ return false;
4463
+ }
4464
+
4465
+ // Check if there are any dots OUTSIDE of parentheses
4466
+ // Strip out content inside balanced parentheses, then check for dots
4467
+ let depth = 0;
4468
+ let hasDotsOutsideParens = false;
4469
+
4470
+ for (let i = 0; i < key.length; i++) {
4471
+ const char = key[i];
4472
+ if (char === '(') {
4473
+ depth++;
4474
+ } else if (char === ')') {
4475
+ depth--;
4476
+ } else if (char === '.' && depth === 0) {
4477
+ hasDotsOutsideParens = true;
4478
+ break;
4479
+ }
4480
+ }
4481
+
4482
+ // It's a bare call signature if there are no dots outside parentheses
4483
+ return !hasDotsOutsideParens;
3534
4484
  }
3535
4485
 
3536
4486
  /**
@@ -3614,18 +4564,428 @@ export class ScopeDataStructure {
3614
4564
  return scopeText;
3615
4565
  }
3616
4566
 
3617
- getEquivalentSignatureVariables() {
4567
+ getEquivalentSignatureVariables(): Record<string, string | string[]> {
3618
4568
  const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
3619
4569
 
3620
- 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
+
3621
4593
  for (const [path, equivalentValues] of Object.entries(
3622
4594
  scopeNode.equivalencies,
3623
4595
  )) {
3624
4596
  for (const equivalentValue of equivalentValues) {
4597
+ // Case 1: Props/signature equivalencies (existing behavior)
4598
+ // Maps local variable names to their signature paths
4599
+ // e.g., "propValue" -> "signature[0].prop"
3625
4600
  if (path.startsWith('signature[')) {
3626
- equivalentSignatureVariables[equivalentValue.schemaPath] = path;
4601
+ addEquivalency(equivalentValue.schemaPath, path);
4602
+ }
4603
+
4604
+ // Case 2: Hook variable equivalencies (new behavior)
4605
+ // The equivalencies are stored as: path = variable name, schemaPath = data source
4606
+ // e.g., path = "debugFetcher", schemaPath = "useFetcher<...>().functionCallReturnValue"
4607
+ // We need to map: "debugFetcher" -> "useFetcher<...>()"
4608
+ // This enables resolving paths like "debugFetcher.state" to
4609
+ // "useFetcher<...>().state" for execution flow validation
4610
+ if (equivalentValue.schemaPath.endsWith('.functionCallReturnValue')) {
4611
+ // Extract the hook call path (everything before .functionCallReturnValue)
4612
+ let hookCallPath = equivalentValue.schemaPath.slice(
4613
+ 0,
4614
+ -'.functionCallReturnValue'.length,
4615
+ );
4616
+ // Only include if it looks like a hook call (contains parentheses)
4617
+ // and the variable name (path) is a simple identifier (no dots)
4618
+ if (hookCallPath.includes('(') && !path.includes('.')) {
4619
+ // Special case: If hookCallPath is a callback scope (cyScope pattern),
4620
+ // trace through it to find what the callback actually returns.
4621
+ // This handles useState(() => { return prop; }) patterns.
4622
+ const cyScopeMatch = hookCallPath.match(/^(cyScope\d+)\(\)$/);
4623
+ if (cyScopeMatch) {
4624
+ // Use the equivalency database to trace the callback's return value
4625
+ // to its actual source (e.g., viewModeFromUrl -> segments -> params -> useParams)
4626
+ const dbEntry = this.getEquivalenciesDatabaseEntry(
4627
+ scopeNode.name, // Component scope
4628
+ path, // variable name (e.g., viewMode)
4629
+ );
4630
+ if (dbEntry?.sourceCandidates?.length > 0) {
4631
+ // Use the traced source instead of the callback scope
4632
+ hookCallPath = dbEntry.sourceCandidates[0].schemaPath;
4633
+ }
4634
+ }
4635
+ addEquivalency(path, hookCallPath);
4636
+ }
4637
+ }
4638
+
4639
+ // Case 3: Destructured variables from local variables
4640
+ // e.g., const { scenarios } = currentEntityAnalysis;
4641
+ // This creates: path = "scenarios", schemaPath = "currentEntityAnalysis.scenarios"
4642
+ // We need to map: "scenarios" -> "currentEntityAnalysis.scenarios"
4643
+ // AND resolve transitively if currentEntityAnalysis is itself equivalent to a hook call
4644
+ if (
4645
+ !path.includes('.') && // path is a simple identifier
4646
+ !equivalentValue.schemaPath.startsWith('signature[') && // not a signature path
4647
+ !equivalentValue.schemaPath.endsWith('.functionCallReturnValue') // not already handled above
4648
+ ) {
4649
+ // Skip bare "returnValue" from child scopes — this is the child's return value,
4650
+ // not a meaningful data source path in the parent scope
4651
+ if (
4652
+ equivalentValue.schemaPath === 'returnValue' &&
4653
+ equivalentValue.scopeNodeName !==
4654
+ this.scopeTreeManager.getRootName()
4655
+ ) {
4656
+ continue;
4657
+ }
4658
+ // Add equivalency (will accumulate if multiple values for OR expressions)
4659
+ addEquivalency(path, equivalentValue.schemaPath);
4660
+ }
4661
+
4662
+ // Case 4: Child component prop mappings (Fix 22)
4663
+ // When parent renders <ChildComponent prop={value} />, we get equivalencies like:
4664
+ // path = "ChildComponent().signature[0].prop"
4665
+ // schemaPath = "value" (the variable passed as the prop)
4666
+ // We need to include these so translateChildPathToParent can work.
4667
+ // Pattern: ComponentName().signature[N] or ComponentName().signature[N].propName
4668
+ if (
4669
+ path.includes('().signature[') &&
4670
+ !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable, not a function call
4671
+ ) {
4672
+ addEquivalency(path, equivalentValue.schemaPath);
4673
+ }
4674
+
4675
+ // Case 5: Destructured function parameters (Fix 25)
4676
+ // When a function has destructured props: function Comp({ propA, propB }: Props)
4677
+ // We get equivalencies like:
4678
+ // path = "propA" (the destructured variable name)
4679
+ // schemaPath = "signature[0].propA" (the signature path)
4680
+ // We need to map: "propA" -> "signature[0].propA"
4681
+ // This enables translateChildPathToParent to resolve child variable paths
4682
+ // to their signature paths when merging execution flows.
4683
+ if (
4684
+ !path.includes('.') && // path is a simple identifier (destructured prop name)
4685
+ equivalentValue.schemaPath.startsWith('signature[') // schemaPath IS a signature path
4686
+ ) {
4687
+ addEquivalency(path, equivalentValue.schemaPath);
4688
+ }
4689
+
4690
+ // Case 7: Method calls on variables that result in .functionCallReturnValue (Fix 33)
4691
+ // When we have patterns like:
4692
+ // path = "segments" (simple identifier)
4693
+ // schemaPath = "splat.split('/').functionCallReturnValue"
4694
+ // This is a method call on a variable (not a hook call), but we still need to
4695
+ // track it so transitive resolution can resolve `splat` to its actual source.
4696
+ // E.g., if splat -> useParams().functionCallReturnValue['*'], then
4697
+ // segments -> useParams().functionCallReturnValue['*'].split('/').functionCallReturnValue
4698
+ if (
4699
+ !path.includes('.') && // path is a simple identifier
4700
+ equivalentValue.schemaPath.endsWith('.functionCallReturnValue') && // ends with function return
4701
+ equivalentValue.schemaPath.includes('.') // has property access (method call)
4702
+ ) {
4703
+ // Check if this looks like a method call on a variable (not a hook call)
4704
+ // Hook calls look like: hookName() or hookName<T>()
4705
+ // Method calls look like: variable.method() or variable.method<T>()
4706
+ const hookCallPath = equivalentValue.schemaPath.slice(
4707
+ 0,
4708
+ -'.functionCallReturnValue'.length,
4709
+ );
4710
+ // If it's a method call (contains a dot before the parenthesis), include it
4711
+ const dotBeforeParen = hookCallPath.indexOf('.');
4712
+ const parenPos = hookCallPath.indexOf('(');
4713
+ if (dotBeforeParen !== -1 && dotBeforeParen < parenPos) {
4714
+ // This is a method call like "splat.split('/')", not a hook call
4715
+ addEquivalency(path, equivalentValue.schemaPath);
4716
+ }
4717
+ }
4718
+ }
4719
+ }
4720
+
4721
+ // Case 6: Collect JSX child prop equivalencies from child scopes (Fix 26)
4722
+ // When a parent component renders <ChildComponent prop={value} />, the JSX
4723
+ // return statement may be in a child scope (e.g., cyScope2). The equivalencies
4724
+ // like ChildComponent().signature[0].prop -> value get stored in that child scope.
4725
+ // But translateChildPathToParent needs to find them from the parent scope's context.
4726
+ // So we collect Case 4 patterns from ALL child scopes that belong to this root scope.
4727
+ const rootName = this.scopeTreeManager.getRootName();
4728
+ for (const [scopeName, childScopeNode] of Object.entries(this.scopeNodes)) {
4729
+ // Skip the root scope (already processed above)
4730
+ if (scopeName === rootName) continue;
4731
+
4732
+ // Only include scopes that are children of the root (their tree includes root)
4733
+ if (!childScopeNode.tree?.includes(rootName)) continue;
4734
+
4735
+ // Look for Case 4 patterns in the child scope
4736
+ for (const [path, equivalentValues] of Object.entries(
4737
+ childScopeNode.equivalencies || {},
4738
+ )) {
4739
+ for (const equivalentValue of equivalentValues) {
4740
+ // Case 4 pattern: ChildComponent().signature[0].propName -> parentVariable
4741
+ if (
4742
+ path.includes('().signature[') &&
4743
+ !equivalentValue.schemaPath.includes('()') // schemaPath is a simple variable
4744
+ ) {
4745
+ // Only add if not already present from the root scope
4746
+ // Root scope values take precedence over child scope values
4747
+ if (!(path in equivalentSignatureVariables)) {
4748
+ addEquivalency(path, equivalentValue.schemaPath);
4749
+ }
4750
+ }
4751
+ }
4752
+ }
4753
+ }
4754
+
4755
+ // Transitive resolution: Resolve variable chains through multiple levels
4756
+ // E.g., analysis → currentEntityAnalysis → useLoaderData().functionCallReturnValue.currentEntityAnalysis
4757
+ // We need multiple passes because resolutions can depend on each other
4758
+ const maxIterations = 5; // Prevent infinite loops
4759
+
4760
+ // Helper function to resolve a single source path using equivalencies
4761
+ const resolveSourcePath = (
4762
+ sourcePath: string,
4763
+ equivMap: Record<string, string | string[]>,
4764
+ ): string | null => {
4765
+ // Extract base variable from the path
4766
+ const dotIndex = sourcePath.indexOf('.');
4767
+ const bracketIndex = sourcePath.indexOf('[');
4768
+
4769
+ let baseVar: string;
4770
+ let rest: string;
4771
+
4772
+ if (dotIndex === -1 && bracketIndex === -1) {
4773
+ baseVar = sourcePath;
4774
+ rest = '';
4775
+ } else if (dotIndex === -1) {
4776
+ baseVar = sourcePath.slice(0, bracketIndex);
4777
+ rest = sourcePath.slice(bracketIndex);
4778
+ } else if (bracketIndex === -1) {
4779
+ baseVar = sourcePath.slice(0, dotIndex);
4780
+ rest = sourcePath.slice(dotIndex);
4781
+ } else {
4782
+ const firstIndex = Math.min(dotIndex, bracketIndex);
4783
+ baseVar = sourcePath.slice(0, firstIndex);
4784
+ rest = sourcePath.slice(firstIndex);
4785
+ }
4786
+
4787
+ // Look up the base variable in equivalencies
4788
+ if (baseVar in equivMap && equivMap[baseVar] !== sourcePath) {
4789
+ const baseResolved = equivMap[baseVar];
4790
+ // Skip if baseResolved is an array (handle later)
4791
+ if (Array.isArray(baseResolved)) return null;
4792
+ // If it resolves to a signature path, build the full resolved path
4793
+ if (
4794
+ baseResolved.startsWith('signature[') ||
4795
+ baseResolved.includes('()')
4796
+ ) {
4797
+ if (baseResolved.endsWith('()')) {
4798
+ return baseResolved + '.functionCallReturnValue' + rest;
4799
+ }
4800
+ return baseResolved + rest;
3627
4801
  }
3628
4802
  }
4803
+ return null;
4804
+ };
4805
+
4806
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
4807
+ let changed = false;
4808
+
4809
+ for (const [varName, sourcePathOrArray] of Object.entries(
4810
+ equivalentSignatureVariables,
4811
+ )) {
4812
+ // Handle arrays (OR expressions) by resolving each element
4813
+ if (Array.isArray(sourcePathOrArray)) {
4814
+ const resolvedArray: string[] = [];
4815
+ let arrayChanged = false;
4816
+ for (const sourcePath of sourcePathOrArray) {
4817
+ // Try to resolve this path using transitive resolution
4818
+ const resolved = resolveSourcePath(
4819
+ sourcePath,
4820
+ equivalentSignatureVariables,
4821
+ );
4822
+ if (resolved && resolved !== sourcePath) {
4823
+ resolvedArray.push(resolved);
4824
+ arrayChanged = true;
4825
+ } else {
4826
+ resolvedArray.push(sourcePath);
4827
+ }
4828
+ }
4829
+ if (arrayChanged) {
4830
+ equivalentSignatureVariables[varName] = resolvedArray;
4831
+ changed = true;
4832
+ }
4833
+ continue;
4834
+ }
4835
+ const sourcePath = sourcePathOrArray;
4836
+
4837
+ // Skip if already fully resolved (contains function call syntax)
4838
+ // BUT first check for computed value patterns that need resolution (Fix 28)
4839
+ // AND method call patterns that need base variable resolution (Fix 33)
4840
+ if (sourcePath.includes('()')) {
4841
+ // Fix 28: Handle computed value patterns with dependency arrays
4842
+ // Patterns like `functionName(arg, [dep1, dep2, ...])` are NOT controllable
4843
+ // data sources. We trace through the dependencies to find controllable sources.
4844
+ const bracketStart = sourcePath.indexOf('[');
4845
+ const bracketEnd = sourcePath.lastIndexOf(']');
4846
+
4847
+ if (bracketStart !== -1 && bracketEnd > bracketStart) {
4848
+ const arrayContent = sourcePath.slice(bracketStart + 1, bracketEnd);
4849
+ const items = arrayContent.split(',').map((s) => s.trim());
4850
+
4851
+ // Only process if this looks like a dependency array:
4852
+ // multiple items that are all simple identifiers (not numbers or expressions)
4853
+ const isIdentifier = (s: string) =>
4854
+ /^\w+$/.test(s) && !/^\d+$/.test(s);
4855
+ if (items.length > 1 && items.every(isIdentifier)) {
4856
+ // Look for a dependency that's already resolved to a controllable source
4857
+ for (const dep of items) {
4858
+ if (dep in equivalentSignatureVariables) {
4859
+ const resolvedDep = equivalentSignatureVariables[dep];
4860
+ // Use if it's a controllable path (contains hook call)
4861
+ // and is NOT another unresolved computed pattern (has comma-separated deps)
4862
+ const hasCommaInBrackets =
4863
+ resolvedDep.includes('[') &&
4864
+ resolvedDep.includes(',') &&
4865
+ resolvedDep.indexOf(',') > resolvedDep.indexOf('[');
4866
+ if (resolvedDep.includes('()') && !hasCommaInBrackets) {
4867
+ // Computed value is typically an element from an array
4868
+ equivalentSignatureVariables[varName] = resolvedDep + '[]';
4869
+ changed = true;
4870
+ break;
4871
+ }
4872
+ }
4873
+ }
4874
+ }
4875
+ }
4876
+
4877
+ // Fix 33: Handle method call patterns on variables
4878
+ // Patterns like: "splat.split('/').functionCallReturnValue"
4879
+ // We need to resolve the base variable (splat) to its actual source
4880
+ // Check if this is a method call on a variable (dot before first parenthesis)
4881
+ const dotIndex = sourcePath.indexOf('.');
4882
+ const parenIndex = sourcePath.indexOf('(');
4883
+ if (
4884
+ dotIndex !== -1 &&
4885
+ dotIndex < parenIndex &&
4886
+ !sourcePath.startsWith('use') // Not a hook call like useState()
4887
+ ) {
4888
+ // Extract the base variable (before the first dot)
4889
+ const baseVar = sourcePath.slice(0, dotIndex);
4890
+ const rest = sourcePath.slice(dotIndex); // includes ".method(...).functionCallReturnValue"
4891
+
4892
+ // Check if the base variable can be resolved
4893
+ if (
4894
+ baseVar in equivalentSignatureVariables &&
4895
+ baseVar !== varName
4896
+ ) {
4897
+ const baseResolved = equivalentSignatureVariables[baseVar];
4898
+ // Skip if baseResolved is an array (OR expression)
4899
+ if (Array.isArray(baseResolved)) continue;
4900
+ // Only resolve if the base resolved to something useful (contains () or .)
4901
+ if (baseResolved.includes('()') || baseResolved.includes('.')) {
4902
+ const newPath = baseResolved + rest;
4903
+ if (newPath !== equivalentSignatureVariables[varName]) {
4904
+ equivalentSignatureVariables[varName] = newPath;
4905
+ changed = true;
4906
+ }
4907
+ }
4908
+ }
4909
+ }
4910
+
4911
+ // Fix 38: Handle cyScope lazy initializer return values
4912
+ // When we have viewMode -> cyScope20(), trace through to find what cyScope20 returns.
4913
+ // The lazy initializer's return value should be the controllable data source.
4914
+ // Pattern: cyScopeN() where N is a number
4915
+ const cyScopeMatch = sourcePath.match(/^(cyScope\d+)\(\)$/);
4916
+ if (cyScopeMatch) {
4917
+ const cyScopeName = cyScopeMatch[1];
4918
+ const cyScopeNode = this.scopeNodes[cyScopeName];
4919
+
4920
+ if (cyScopeNode?.equivalencies) {
4921
+ // Look for returnValue equivalency in the cyScope
4922
+ const returnValueEquivs =
4923
+ cyScopeNode.equivalencies['returnValue'];
4924
+ if (returnValueEquivs && returnValueEquivs.length > 0) {
4925
+ // Get the first return value source
4926
+ const returnSource = returnValueEquivs[0].schemaPath;
4927
+
4928
+ // If the return source is a simple variable (not a complex path),
4929
+ // resolve varName directly to that variable
4930
+ if (
4931
+ returnSource &&
4932
+ !returnSource.includes('(') &&
4933
+ !returnSource.includes('[')
4934
+ ) {
4935
+ // Update varName to point to the return source
4936
+ if (equivalentSignatureVariables[varName] !== returnSource) {
4937
+ equivalentSignatureVariables[varName] = returnSource;
4938
+ changed = true;
4939
+ }
4940
+ }
4941
+ }
4942
+ }
4943
+ }
4944
+
4945
+ continue;
4946
+ }
4947
+
4948
+ // Check if the source path starts with a variable that's also in the map
4949
+ const dotIndex = sourcePath.indexOf('.');
4950
+ let baseVar: string;
4951
+ let rest: string;
4952
+
4953
+ if (dotIndex > 0) {
4954
+ // Path has a dot: "a.b.c" -> baseVar="a", rest=".b.c"
4955
+ baseVar = sourcePath.slice(0, dotIndex);
4956
+ rest = sourcePath.slice(dotIndex); // includes the leading dot
4957
+ } else {
4958
+ // Path is a simple identifier: "currentEntityAnalysis" -> baseVar="currentEntityAnalysis", rest=""
4959
+ baseVar = sourcePath;
4960
+ rest = '';
4961
+ }
4962
+
4963
+ if (baseVar in equivalentSignatureVariables && baseVar !== varName) {
4964
+ // Handle array case (OR expressions) - use first element
4965
+ const rawBaseResolved = equivalentSignatureVariables[baseVar];
4966
+ const baseResolved = Array.isArray(rawBaseResolved)
4967
+ ? rawBaseResolved[0]
4968
+ : rawBaseResolved;
4969
+ if (!baseResolved) continue;
4970
+ // If the base resolves to a hook call, add .functionCallReturnValue
4971
+ if (baseResolved.endsWith('()')) {
4972
+ const newPath = baseResolved + '.functionCallReturnValue' + rest;
4973
+ if (newPath !== equivalentSignatureVariables[varName]) {
4974
+ equivalentSignatureVariables[varName] = newPath;
4975
+ changed = true;
4976
+ }
4977
+ } else if (baseResolved !== sourcePath) {
4978
+ const newPath = baseResolved + rest;
4979
+ if (newPath !== equivalentSignatureVariables[varName]) {
4980
+ equivalentSignatureVariables[varName] = newPath;
4981
+ changed = true;
4982
+ }
4983
+ }
4984
+ }
4985
+ }
4986
+
4987
+ // Stop if no changes were made in this iteration
4988
+ if (!changed) break;
3629
4989
  }
3630
4990
 
3631
4991
  return equivalentSignatureVariables;
@@ -3696,9 +5056,109 @@ export class ScopeDataStructure {
3696
5056
  // Replace cyScope placeholders in all external function call data
3697
5057
  // This ensures call signatures and schema paths use actual callback text
3698
5058
  // instead of internal cyScope names, preventing mock data merge conflicts.
3699
- return this.externalFunctionCalls.map((efc) =>
3700
- this.cleanCyScopeFromFunctionCallInfo(efc),
3701
- );
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 };
3702
5162
  }
3703
5163
 
3704
5164
  /**
@@ -3826,7 +5286,7 @@ export class ScopeDataStructure {
3826
5286
  path: string;
3827
5287
  conditionType: 'truthiness' | 'comparison' | 'switch';
3828
5288
  comparedValues?: string[];
3829
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
5289
+ location: 'if' | 'ternary' | 'logical-and' | 'switch' | 'unconditional';
3830
5290
  }>
3831
5291
  >,
3832
5292
  ): void {
@@ -3851,29 +5311,149 @@ export class ScopeDataStructure {
3851
5311
  }
3852
5312
 
3853
5313
  /**
3854
- * Get enriched conditional usages with source tracing.
3855
- * Uses explainPath to trace each local variable back to its data source.
5314
+ * Add conditional effects from AST analysis.
5315
+ * Called during scope analysis to collect all setter calls inside conditionals.
3856
5316
  */
3857
- getEnrichedConditionalUsages(): Record<
5317
+ addConditionalEffects(
5318
+ effects: import('../astScopes/types').ConditionalEffect[],
5319
+ ): void {
5320
+ // Add effects, avoiding duplicates based on effect stateVariable and condition paths
5321
+ for (const effect of effects) {
5322
+ const exists = this.rawConditionalEffects.some((existing) => {
5323
+ // Same effect target (stateVariable + value)
5324
+ const sameEffect =
5325
+ existing.effect.stateVariable === effect.effect.stateVariable &&
5326
+ existing.effect.value === effect.effect.value;
5327
+ if (!sameEffect) return false;
5328
+
5329
+ // Same condition(s)
5330
+ if (existing.condition && effect.condition) {
5331
+ return (
5332
+ existing.condition.path === effect.condition.path &&
5333
+ existing.condition.requiredValue === effect.condition.requiredValue
5334
+ );
5335
+ }
5336
+ if (existing.conditions && effect.conditions) {
5337
+ if (existing.conditions.length !== effect.conditions.length)
5338
+ return false;
5339
+ return existing.conditions.every((ec, i) => {
5340
+ const newCond = effect.conditions![i];
5341
+ return (
5342
+ ec.path === newCond.path &&
5343
+ ec.requiredValue === newCond.requiredValue
5344
+ );
5345
+ });
5346
+ }
5347
+ return false;
5348
+ });
5349
+ if (!exists) {
5350
+ this.rawConditionalEffects.push(effect);
5351
+ }
5352
+ }
5353
+ }
5354
+
5355
+ /**
5356
+ * Get conditional effects collected during analysis.
5357
+ */
5358
+ getConditionalEffects(): import('../astScopes/types').ConditionalEffect[] {
5359
+ return this.rawConditionalEffects;
5360
+ }
5361
+
5362
+ /**
5363
+ * Add compound conditionals from AST analysis.
5364
+ * Called during scope analysis to collect grouped conditions (e.g., a && b && c).
5365
+ */
5366
+ addCompoundConditionals(
5367
+ compounds: import('../astScopes/types').CompoundConditional[],
5368
+ ): void {
5369
+ // Add compounds, avoiding duplicates based on chainId
5370
+ for (const compound of compounds) {
5371
+ const exists = this.rawCompoundConditionals.some(
5372
+ (existing) => existing.chainId === compound.chainId,
5373
+ );
5374
+ if (!exists) {
5375
+ this.rawCompoundConditionals.push(compound);
5376
+ }
5377
+ }
5378
+ }
5379
+
5380
+ /**
5381
+ * Get compound conditionals collected during analysis.
5382
+ */
5383
+ getCompoundConditionals(): import('../astScopes/types').CompoundConditional[] {
5384
+ return this.rawCompoundConditionals;
5385
+ }
5386
+
5387
+ /**
5388
+ * Add child boundary gating conditions from AST analysis.
5389
+ * These track which conditions must be true for a child component to render.
5390
+ */
5391
+ addChildBoundaryGatingConditions(
5392
+ conditions: Record<string, import('../astScopes/types').ConditionalUsage[]>,
5393
+ ): void {
5394
+ for (const [childName, usages] of Object.entries(conditions)) {
5395
+ if (!this.rawChildBoundaryGatingConditions[childName]) {
5396
+ this.rawChildBoundaryGatingConditions[childName] = [];
5397
+ }
5398
+ // Add usages, avoiding duplicates
5399
+ for (const usage of usages) {
5400
+ const exists = this.rawChildBoundaryGatingConditions[childName].some(
5401
+ (existing) =>
5402
+ existing.path === usage.path &&
5403
+ existing.conditionType === usage.conditionType &&
5404
+ existing.isNegated === usage.isNegated,
5405
+ );
5406
+ if (!exists) {
5407
+ this.rawChildBoundaryGatingConditions[childName].push(usage);
5408
+ }
5409
+ }
5410
+ }
5411
+ }
5412
+
5413
+ /**
5414
+ * Get enriched child boundary gating conditions with source tracing.
5415
+ * Similar to getEnrichedConditionalUsages but for gating conditions.
5416
+ */
5417
+ getEnrichedChildBoundaryGatingConditions(): Record<
3858
5418
  string,
3859
- Array<{
3860
- path: string;
3861
- conditionType: 'truthiness' | 'comparison' | 'switch';
3862
- comparedValues?: string[];
3863
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
3864
- sourceDataPath?: string;
3865
- }>
5419
+ EnrichedConditionalUsage[]
3866
5420
  > {
3867
- const enriched: Record<
3868
- string,
3869
- Array<{
3870
- path: string;
3871
- conditionType: 'truthiness' | 'comparison' | 'switch';
3872
- comparedValues?: string[];
3873
- location: 'if' | 'ternary' | 'logical-and' | 'switch';
3874
- sourceDataPath?: string;
3875
- }>
3876
- > = {};
5421
+ const enriched: Record<string, EnrichedConditionalUsage[]> = {};
5422
+ const rootScopeName = this.scopeTreeManager.getTree().name;
5423
+
5424
+ for (const [childName, usages] of Object.entries(
5425
+ this.rawChildBoundaryGatingConditions,
5426
+ )) {
5427
+ enriched[childName] = usages.map((usage) => {
5428
+ // Try to trace this path back to a data source
5429
+ const explanation = this.explainPath(rootScopeName, usage.path);
5430
+
5431
+ let sourceDataPath: string | undefined;
5432
+ if (explanation.source) {
5433
+ sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
5434
+ }
5435
+
5436
+ return {
5437
+ ...usage,
5438
+ sourceDataPath,
5439
+ };
5440
+ });
5441
+ }
5442
+
5443
+ return enriched;
5444
+ }
5445
+
5446
+ /**
5447
+ * Get enriched conditional usages with source tracing.
5448
+ * Uses explainPath to trace each local variable back to its data source.
5449
+ * Preserves all fields from the raw conditional usages including derivedFrom.
5450
+ */
5451
+ getEnrichedConditionalUsages(): Record<string, EnrichedConditionalUsage[]> {
5452
+ const enriched: Record<string, EnrichedConditionalUsage[]> = {};
5453
+
5454
+ console.log(
5455
+ `[getEnrichedConditionalUsages] Processing ${Object.keys(this.rawConditionalUsages).length} conditional paths: [${Object.keys(this.rawConditionalUsages).join(', ')}]`,
5456
+ );
3877
5457
 
3878
5458
  for (const [path, usages] of Object.entries(this.rawConditionalUsages)) {
3879
5459
  // Try to trace this path back to a data source
@@ -3883,10 +5463,69 @@ export class ScopeDataStructure {
3883
5463
 
3884
5464
  let sourceDataPath: string | undefined;
3885
5465
  if (explanation.source) {
3886
- // Build the full data path: scopeName.path
3887
- 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
+ );
3888
5484
  }
3889
5485
 
5486
+ // If explainPath didn't find a useful external source (e.g., it traced to
5487
+ // useState or just to the component scope itself), check sourceEquivalencies
5488
+ // for an external function call source like a fetch call
5489
+ const hasExternalSource = sourceDataPath?.includes(
5490
+ '.functionCallReturnValue',
5491
+ );
5492
+ if (!hasExternalSource) {
5493
+ console.log(
5494
+ `[getEnrichedConditionalUsages] "${path}" no external source (sourceDataPath="${sourceDataPath}"), checking sourceEquivalencies fallback...`,
5495
+ );
5496
+ const sourceEquiv = this.getSourceEquivalencies();
5497
+ const returnValueKey = `returnValue.${path}`;
5498
+ const sources = sourceEquiv[returnValueKey];
5499
+ if (sources) {
5500
+ console.log(
5501
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies["${returnValueKey}"] has ${sources.length} sources: [${sources.map((s: { schemaPath: string }) => s.schemaPath).join(', ')}]`,
5502
+ );
5503
+ const externalSource = sources.find(
5504
+ (s: { schemaPath: string }) =>
5505
+ s.schemaPath.includes('.functionCallReturnValue') &&
5506
+ !s.schemaPath.startsWith('useState('),
5507
+ );
5508
+ if (externalSource) {
5509
+ console.log(
5510
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies fallback found external source: "${externalSource.schemaPath}"`,
5511
+ );
5512
+ sourceDataPath = externalSource.schemaPath;
5513
+ } else {
5514
+ console.log(
5515
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies fallback found no external function call source`,
5516
+ );
5517
+ }
5518
+ } else {
5519
+ console.log(
5520
+ `[getEnrichedConditionalUsages] "${path}" sourceEquivalencies["${returnValueKey}"] not found`,
5521
+ );
5522
+ }
5523
+ }
5524
+
5525
+ console.log(
5526
+ `[getEnrichedConditionalUsages] "${path}" FINAL sourceDataPath="${sourceDataPath ?? '(none)'}" (${usages.length} usages)`,
5527
+ );
5528
+
3890
5529
  enriched[path] = usages.map((usage) => ({
3891
5530
  ...usage,
3892
5531
  sourceDataPath,
@@ -3896,10 +5535,37 @@ export class ScopeDataStructure {
3896
5535
  return enriched;
3897
5536
  }
3898
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
+
3899
5565
  toSerializable(): SerializableDataStructure {
3900
- // Helper to clean cyScope from a string
5566
+ // Helper to clean cyScope and cyDuplicateKey from a string for output
3901
5567
  const cleanCyScope = (str: string): string =>
3902
- this.replaceCyScopeInString(str);
5568
+ this.replaceCyScopeInString(str).replace(/::cyDuplicateKey\d+::/g, '');
3903
5569
 
3904
5570
  // Helper to convert ScopeVariable to SerializableScopeVariable (with cyScope cleaned)
3905
5571
  const toSerializableVariable = (
@@ -4049,6 +5715,16 @@ export class ScopeDataStructure {
4049
5715
  if (Object.keys(perVariableSchemas).length < numReceivingVars) {
4050
5716
  // Not all variables have schemas - fall back to rootSchema extraction
4051
5717
  perVariableSchemas = undefined;
5718
+ } else {
5719
+ // Also check that at least one schema is non-empty
5720
+ // Bug fix: perCallSignatureSchemas may have entries but with empty schemas {}
5721
+ // In this case, we should fall through to Fallback which uses rootSchema
5722
+ const hasNonEmptySchema = Object.values(perVariableSchemas).some(
5723
+ (schema) => Object.keys(schema).length > 0,
5724
+ );
5725
+ if (!hasNonEmptySchema) {
5726
+ perVariableSchemas = undefined;
5727
+ }
4052
5728
  }
4053
5729
  }
4054
5730
 
@@ -4068,7 +5744,11 @@ export class ScopeDataStructure {
4068
5744
  }
4069
5745
  }
4070
5746
 
4071
- // CASE 3: Parameterized calls that create SEPARATE efc entries (no perCallSignatureSchemas)
5747
+ // CASE 3: Extract from efc.schema when perCallSignatureSchemas is missing or empty
5748
+ // This handles two scenarios:
5749
+ // 1. Parameterized calls that create SEPARATE efc entries (no perCallSignatureSchemas)
5750
+ // 2. Destructuring where perCallSignatureSchemas exists but has EMPTY schemas
5751
+ //
4072
5752
  // When useFetcher<ConfigData>() and useFetcher<SettingsData>() are called, they create separate
4073
5753
  // efc entries because getFunctionCallRoot preserves type parameters. Each entry has its own
4074
5754
  // `schema` field, but due to variable reassignment, the schema may be contaminated with paths
@@ -4084,14 +5764,39 @@ export class ScopeDataStructure {
4084
5764
  //
4085
5765
  // We filter to only keep paths that should belong to THIS call by checking if the
4086
5766
  // receiving variable's equivalency points to this call's return value.
5767
+ //
5768
+ // BUG FIX: The old condition `!efc.perCallSignatureSchemas` was FALSE when the object
5769
+ // existed (even with empty schemas), causing this case to be skipped. We now also check
5770
+ // if all schemas in perCallSignatureSchemas are empty.
5771
+ const hasNonEmptyPerCallSignatureSchemas =
5772
+ efc.perCallSignatureSchemas &&
5773
+ Object.values(efc.perCallSignatureSchemas).some(
5774
+ (schema) => Object.keys(schema).length > 0,
5775
+ );
5776
+
5777
+ // Build the call signature prefix that paths should start with
5778
+ const callSigPrefix = `${efc.callSignature}.functionCallReturnValue`;
5779
+
5780
+ // Check if efc.schema has variable-specific paths (indicating destructuring).
5781
+ // Destructuring: const { entities, gitStatus } = useLoaderData()
5782
+ // - efc.schema has paths like: useLoaderData().functionCallReturnValue.entities...
5783
+ // Multiple calls: const x = useFetcher(); const y = useFetcher();
5784
+ // - efc.schema has paths like: useFetcher().functionCallReturnValue.data...
5785
+ // CASE 3 should only run for destructuring (variable-specific paths exist).
5786
+ const hasVariableSpecificPaths = (
5787
+ efc.receivingVariableNames ?? []
5788
+ ).some((varName) =>
5789
+ Object.keys(efc.schema).some((path) =>
5790
+ path.startsWith(`${callSigPrefix}.${varName}`),
5791
+ ),
5792
+ );
5793
+
4087
5794
  if (
4088
5795
  !perVariableSchemas &&
4089
- !efc.perCallSignatureSchemas &&
4090
- numReceivingVars >= 1
5796
+ !hasNonEmptyPerCallSignatureSchemas &&
5797
+ numReceivingVars >= 1 &&
5798
+ hasVariableSpecificPaths
4091
5799
  ) {
4092
- // Build the call signature prefix that paths should start with
4093
- const callSigPrefix = `${efc.callSignature}.functionCallReturnValue`;
4094
-
4095
5800
  // Filter efc.schema to only include paths matching this call signature
4096
5801
  const filteredSchema: Record<string, string> = {};
4097
5802
  for (const [path, type] of Object.entries(efc.schema)) {
@@ -4101,16 +5806,18 @@ export class ScopeDataStructure {
4101
5806
  }
4102
5807
 
4103
5808
  // Build perVariableSchemas from the filtered schema
5809
+ // For destructuring, filter paths by variable name
4104
5810
  if (Object.keys(filteredSchema).length > 0) {
4105
5811
  perVariableSchemas = {};
4106
5812
  for (const varName of efc.receivingVariableNames ?? []) {
4107
- // For each variable, extract paths and transform to functionCallReturnValue format
5813
+ // For destructuring, extract only paths specific to this variable
5814
+ const varSpecificPrefix = `${callSigPrefix}.${varName}`;
4108
5815
  const varSchema: Record<string, string> = {};
5816
+
4109
5817
  for (const [path, type] of Object.entries(filteredSchema)) {
4110
- if (path.startsWith(callSigPrefix)) {
4111
- // Transform to generic functionCallReturnValue path
4112
- // e.g., "useFetcher<ConfigData>().functionCallReturnValue.data.data.theme"
4113
- // -> "functionCallReturnValue.data.data.theme"
5818
+ if (path.startsWith(varSpecificPrefix)) {
5819
+ // Transform: useLoaderData().functionCallReturnValue.entities.sha
5820
+ // -> functionCallReturnValue.entities.sha (keep the variable name)
4114
5821
  const suffix = path.slice(callSigPrefix.length);
4115
5822
  const returnValuePath = `functionCallReturnValue${suffix}`;
4116
5823
  varSchema[returnValuePath] = type;
@@ -4156,7 +5863,8 @@ export class ScopeDataStructure {
4156
5863
  }
4157
5864
  }
4158
5865
  if (Object.keys(varSchema).length > 0) {
4159
- perVariableSchemas[varName] = varSchema;
5866
+ // Clean the variable name when using as key in output
5867
+ perVariableSchemas[cleanCyScope(varName)] = varSchema;
4160
5868
  }
4161
5869
  }
4162
5870
  // Only include if we have any entries
@@ -4165,11 +5873,22 @@ export class ScopeDataStructure {
4165
5873
  }
4166
5874
  }
4167
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
+
4168
5887
  return {
4169
5888
  name: efc.name,
4170
5889
  callSignature: efc.callSignature,
4171
5890
  callScope: efc.callScope,
4172
- schema: efc.schema,
5891
+ schema: enrichedSchema,
4173
5892
  equivalencies: efc.equivalencies
4174
5893
  ? Object.entries(efc.equivalencies).reduce(
4175
5894
  (acc, [key, vars]) => {
@@ -4181,8 +5900,15 @@ export class ScopeDataStructure {
4181
5900
  )
4182
5901
  : undefined,
4183
5902
  allCallSignatures: efc.allCallSignatures,
4184
- receivingVariableNames: efc.receivingVariableNames,
4185
- callSignatureToVariable: efc.callSignatureToVariable,
5903
+ receivingVariableNames: efc.receivingVariableNames?.map(cleanCyScope),
5904
+ callSignatureToVariable: efc.callSignatureToVariable
5905
+ ? Object.fromEntries(
5906
+ Object.entries(efc.callSignatureToVariable).map(([k, v]) => [
5907
+ k,
5908
+ cleanCyScope(v),
5909
+ ]),
5910
+ )
5911
+ : undefined,
4186
5912
  perVariableSchemas,
4187
5913
  };
4188
5914
  });
@@ -4302,6 +6028,13 @@ export class ScopeDataStructure {
4302
6028
  externalFunctionCalls,
4303
6029
  );
4304
6030
 
6031
+ // IMPORTANT: Get equivalent signature variables BEFORE calling getFunctionResult
6032
+ // because getFunctionResult calls validateSchema which may remove equivalencies
6033
+ // during the finalize step (e.g., cleanNonObjectFunctions removes method call
6034
+ // equivalencies like `segments -> splat.split('/').functionCallReturnValue`).
6035
+ // Fix 33: Move this call before any schema validation to preserve method call chains.
6036
+ const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
6037
+
4305
6038
  // Get root function result
4306
6039
  const rootFunction = getFunctionResult();
4307
6040
 
@@ -4311,9 +6044,6 @@ export class ScopeDataStructure {
4311
6044
  functionResults[efc.name] = getFunctionResult(efc.name);
4312
6045
  }
4313
6046
 
4314
- // Get equivalent signature variables
4315
- const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
4316
-
4317
6047
  const environmentVariables = this.getEnvironmentVariables();
4318
6048
 
4319
6049
  // Get enriched conditional usages with source tracing
@@ -4323,6 +6053,32 @@ export class ScopeDataStructure {
4323
6053
  ? enrichedConditionalUsages
4324
6054
  : undefined;
4325
6055
 
6056
+ // Get conditional effects (setter calls inside conditionals)
6057
+ const conditionalEffects =
6058
+ this.rawConditionalEffects.length > 0
6059
+ ? this.rawConditionalEffects
6060
+ : undefined;
6061
+
6062
+ // Get compound conditionals (grouped conditions that must all be true)
6063
+ const compoundConditionals =
6064
+ this.rawCompoundConditionals.length > 0
6065
+ ? this.rawCompoundConditionals
6066
+ : undefined;
6067
+
6068
+ // Get child boundary gating conditions
6069
+ const enrichedGatingConditions =
6070
+ this.getEnrichedChildBoundaryGatingConditions();
6071
+ const childBoundaryGatingConditions =
6072
+ Object.keys(enrichedGatingConditions).length > 0
6073
+ ? enrichedGatingConditions
6074
+ : undefined;
6075
+
6076
+ // Get JSX rendering usages (arrays via .map(), strings via interpolation)
6077
+ const jsxRenderingUsages =
6078
+ this.rawJsxRenderingUsages.length > 0
6079
+ ? this.rawJsxRenderingUsages
6080
+ : undefined;
6081
+
4326
6082
  return {
4327
6083
  externalFunctionCalls: deduplicatedExternalFunctionCalls,
4328
6084
  rootFunction,
@@ -4330,6 +6086,10 @@ export class ScopeDataStructure {
4330
6086
  equivalentSignatureVariables,
4331
6087
  environmentVariables,
4332
6088
  conditionalUsages,
6089
+ conditionalEffects,
6090
+ compoundConditionals,
6091
+ childBoundaryGatingConditions,
6092
+ jsxRenderingUsages,
4333
6093
  };
4334
6094
  }
4335
6095