@gracker/smartperfetto 1.0.13

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 (2287) hide show
  1. package/.env.example +586 -0
  2. package/LICENSE +685 -0
  3. package/data/perfettoSqlDocs.json +33478 -0
  4. package/data/perfettoSqlIndex.json +9458 -0
  5. package/data/perfettoSqlIndex.light.json +13129 -0
  6. package/data/perfettoStdlibSymbols.json +677 -0
  7. package/dist/agent/agents/base/baseAgent.d.ts +378 -0
  8. package/dist/agent/agents/base/baseAgent.d.ts.map +1 -0
  9. package/dist/agent/agents/base/baseAgent.js +1484 -0
  10. package/dist/agent/agents/base/baseAgent.js.map +1 -0
  11. package/dist/agent/agents/base/baseSubAgent.d.ts +135 -0
  12. package/dist/agent/agents/base/baseSubAgent.d.ts.map +1 -0
  13. package/dist/agent/agents/base/baseSubAgent.js +483 -0
  14. package/dist/agent/agents/base/baseSubAgent.js.map +1 -0
  15. package/dist/agent/agents/baseExpertAgent.d.ts +37 -0
  16. package/dist/agent/agents/baseExpertAgent.d.ts.map +1 -0
  17. package/dist/agent/agents/baseExpertAgent.js +322 -0
  18. package/dist/agent/agents/baseExpertAgent.js.map +1 -0
  19. package/dist/agent/agents/domain/additionalAgents.d.ts +54 -0
  20. package/dist/agent/agents/domain/additionalAgents.d.ts.map +1 -0
  21. package/dist/agent/agents/domain/additionalAgents.js +292 -0
  22. package/dist/agent/agents/domain/additionalAgents.js.map +1 -0
  23. package/dist/agent/agents/domain/binderAgent.d.ts +27 -0
  24. package/dist/agent/agents/domain/binderAgent.d.ts.map +1 -0
  25. package/dist/agent/agents/domain/binderAgent.js +100 -0
  26. package/dist/agent/agents/domain/binderAgent.js.map +1 -0
  27. package/dist/agent/agents/domain/cpuAgent.d.ts +35 -0
  28. package/dist/agent/agents/domain/cpuAgent.d.ts.map +1 -0
  29. package/dist/agent/agents/domain/cpuAgent.js +163 -0
  30. package/dist/agent/agents/domain/cpuAgent.js.map +1 -0
  31. package/dist/agent/agents/domain/frameAgent.d.ts +59 -0
  32. package/dist/agent/agents/domain/frameAgent.d.ts.map +1 -0
  33. package/dist/agent/agents/domain/frameAgent.js +511 -0
  34. package/dist/agent/agents/domain/frameAgent.js.map +1 -0
  35. package/dist/agent/agents/domain/index.d.ts +92 -0
  36. package/dist/agent/agents/domain/index.d.ts.map +1 -0
  37. package/dist/agent/agents/domain/index.js +250 -0
  38. package/dist/agent/agents/domain/index.js.map +1 -0
  39. package/dist/agent/agents/domain/memoryAgent.d.ts +26 -0
  40. package/dist/agent/agents/domain/memoryAgent.d.ts.map +1 -0
  41. package/dist/agent/agents/domain/memoryAgent.js +94 -0
  42. package/dist/agent/agents/domain/memoryAgent.js.map +1 -0
  43. package/dist/agent/agents/domain/skillCatalog.d.ts +10 -0
  44. package/dist/agent/agents/domain/skillCatalog.d.ts.map +1 -0
  45. package/dist/agent/agents/domain/skillCatalog.js +66 -0
  46. package/dist/agent/agents/domain/skillCatalog.js.map +1 -0
  47. package/dist/agent/agents/evaluatorAgent.d.ts +76 -0
  48. package/dist/agent/agents/evaluatorAgent.d.ts.map +1 -0
  49. package/dist/agent/agents/evaluatorAgent.js +517 -0
  50. package/dist/agent/agents/evaluatorAgent.js.map +1 -0
  51. package/dist/agent/agents/index.d.ts +13 -0
  52. package/dist/agent/agents/index.d.ts.map +1 -0
  53. package/dist/agent/agents/index.js +25 -0
  54. package/dist/agent/agents/index.js.map +1 -0
  55. package/dist/agent/agents/iterationStrategyPlanner.d.ts +140 -0
  56. package/dist/agent/agents/iterationStrategyPlanner.d.ts.map +1 -0
  57. package/dist/agent/agents/iterationStrategyPlanner.js +359 -0
  58. package/dist/agent/agents/iterationStrategyPlanner.js.map +1 -0
  59. package/dist/agent/agents/plannerAgent.d.ts +56 -0
  60. package/dist/agent/agents/plannerAgent.d.ts.map +1 -0
  61. package/dist/agent/agents/plannerAgent.js +379 -0
  62. package/dist/agent/agents/plannerAgent.js.map +1 -0
  63. package/dist/agent/agents/scrollingExpertAgent.d.ts +11 -0
  64. package/dist/agent/agents/scrollingExpertAgent.d.ts.map +1 -0
  65. package/dist/agent/agents/scrollingExpertAgent.js +132 -0
  66. package/dist/agent/agents/scrollingExpertAgent.js.map +1 -0
  67. package/dist/agent/agents/tools/adbTools.d.ts +5 -0
  68. package/dist/agent/agents/tools/adbTools.d.ts.map +1 -0
  69. package/dist/agent/agents/tools/adbTools.js +326 -0
  70. package/dist/agent/agents/tools/adbTools.js.map +1 -0
  71. package/dist/agent/communication/agentMessageBus.d.ts +138 -0
  72. package/dist/agent/communication/agentMessageBus.d.ts.map +1 -0
  73. package/dist/agent/communication/agentMessageBus.js +542 -0
  74. package/dist/agent/communication/agentMessageBus.js.map +1 -0
  75. package/dist/agent/communication/index.d.ts +7 -0
  76. package/dist/agent/communication/index.d.ts.map +1 -0
  77. package/dist/agent/communication/index.js +15 -0
  78. package/dist/agent/communication/index.js.map +1 -0
  79. package/dist/agent/compaction/compactionTypes.d.ts +163 -0
  80. package/dist/agent/compaction/compactionTypes.d.ts.map +1 -0
  81. package/dist/agent/compaction/compactionTypes.js +32 -0
  82. package/dist/agent/compaction/compactionTypes.js.map +1 -0
  83. package/dist/agent/compaction/contextCompactor.d.ts +109 -0
  84. package/dist/agent/compaction/contextCompactor.d.ts.map +1 -0
  85. package/dist/agent/compaction/contextCompactor.js +225 -0
  86. package/dist/agent/compaction/contextCompactor.js.map +1 -0
  87. package/dist/agent/compaction/index.d.ts +10 -0
  88. package/dist/agent/compaction/index.d.ts.map +1 -0
  89. package/dist/agent/compaction/index.js +43 -0
  90. package/dist/agent/compaction/index.js.map +1 -0
  91. package/dist/agent/compaction/strategies/index.d.ts +5 -0
  92. package/dist/agent/compaction/strategies/index.d.ts.map +1 -0
  93. package/dist/agent/compaction/strategies/index.js +13 -0
  94. package/dist/agent/compaction/strategies/index.js.map +1 -0
  95. package/dist/agent/compaction/strategies/slidingWindowStrategy.d.ts +53 -0
  96. package/dist/agent/compaction/strategies/slidingWindowStrategy.d.ts.map +1 -0
  97. package/dist/agent/compaction/strategies/slidingWindowStrategy.js +237 -0
  98. package/dist/agent/compaction/strategies/slidingWindowStrategy.js.map +1 -0
  99. package/dist/agent/compaction/tokenEstimator.d.ts +78 -0
  100. package/dist/agent/compaction/tokenEstimator.d.ts.map +1 -0
  101. package/dist/agent/compaction/tokenEstimator.js +203 -0
  102. package/dist/agent/compaction/tokenEstimator.js.map +1 -0
  103. package/dist/agent/config/decisionThresholdManifest.d.ts +72 -0
  104. package/dist/agent/config/decisionThresholdManifest.d.ts.map +1 -0
  105. package/dist/agent/config/decisionThresholdManifest.js +77 -0
  106. package/dist/agent/config/decisionThresholdManifest.js.map +1 -0
  107. package/dist/agent/config/domainManifest.d.ts +77 -0
  108. package/dist/agent/config/domainManifest.d.ts.map +1 -0
  109. package/dist/agent/config/domainManifest.js +269 -0
  110. package/dist/agent/config/domainManifest.js.map +1 -0
  111. package/dist/agent/config/drillDownRegistry.d.ts +19 -0
  112. package/dist/agent/config/drillDownRegistry.d.ts.map +1 -0
  113. package/dist/agent/config/drillDownRegistry.js +118 -0
  114. package/dist/agent/config/drillDownRegistry.js.map +1 -0
  115. package/dist/agent/context/contextBuilder.d.ts +79 -0
  116. package/dist/agent/context/contextBuilder.d.ts.map +1 -0
  117. package/dist/agent/context/contextBuilder.js +273 -0
  118. package/dist/agent/context/contextBuilder.js.map +1 -0
  119. package/dist/agent/context/contextTypes.d.ts +121 -0
  120. package/dist/agent/context/contextTypes.d.ts.map +1 -0
  121. package/dist/agent/context/contextTypes.js +14 -0
  122. package/dist/agent/context/contextTypes.js.map +1 -0
  123. package/dist/agent/context/enhancedSessionContext.d.ts +283 -0
  124. package/dist/agent/context/enhancedSessionContext.d.ts.map +1 -0
  125. package/dist/agent/context/enhancedSessionContext.js +1636 -0
  126. package/dist/agent/context/enhancedSessionContext.js.map +1 -0
  127. package/dist/agent/context/entityStore.d.ts +374 -0
  128. package/dist/agent/context/entityStore.d.ts.map +1 -0
  129. package/dist/agent/context/entityStore.js +621 -0
  130. package/dist/agent/context/entityStore.js.map +1 -0
  131. package/dist/agent/context/focusStore.d.ts +229 -0
  132. package/dist/agent/context/focusStore.d.ts.map +1 -0
  133. package/dist/agent/context/focusStore.js +528 -0
  134. package/dist/agent/context/focusStore.js.map +1 -0
  135. package/dist/agent/context/index.d.ts +10 -0
  136. package/dist/agent/context/index.d.ts.map +1 -0
  137. package/dist/agent/context/index.js +42 -0
  138. package/dist/agent/context/index.js.map +1 -0
  139. package/dist/agent/context/policies/evaluatorPolicy.d.ts +22 -0
  140. package/dist/agent/context/policies/evaluatorPolicy.d.ts.map +1 -0
  141. package/dist/agent/context/policies/evaluatorPolicy.js +82 -0
  142. package/dist/agent/context/policies/evaluatorPolicy.js.map +1 -0
  143. package/dist/agent/context/policies/index.d.ts +7 -0
  144. package/dist/agent/context/policies/index.d.ts.map +1 -0
  145. package/dist/agent/context/policies/index.js +18 -0
  146. package/dist/agent/context/policies/index.js.map +1 -0
  147. package/dist/agent/context/policies/plannerPolicy.d.ts +27 -0
  148. package/dist/agent/context/policies/plannerPolicy.d.ts.map +1 -0
  149. package/dist/agent/context/policies/plannerPolicy.js +67 -0
  150. package/dist/agent/context/policies/plannerPolicy.js.map +1 -0
  151. package/dist/agent/context/policies/workerPolicy.d.ts +29 -0
  152. package/dist/agent/context/policies/workerPolicy.d.ts.map +1 -0
  153. package/dist/agent/context/policies/workerPolicy.js +99 -0
  154. package/dist/agent/context/policies/workerPolicy.js.map +1 -0
  155. package/dist/agent/core/circuitBreaker.d.ts +150 -0
  156. package/dist/agent/core/circuitBreaker.d.ts.map +1 -0
  157. package/dist/agent/core/circuitBreaker.js +500 -0
  158. package/dist/agent/core/circuitBreaker.js.map +1 -0
  159. package/dist/agent/core/conclusionContract.d.ts +61 -0
  160. package/dist/agent/core/conclusionContract.d.ts.map +1 -0
  161. package/dist/agent/core/conclusionContract.js +6 -0
  162. package/dist/agent/core/conclusionContract.js.map +1 -0
  163. package/dist/agent/core/conclusionGenerator.d.ts +42 -0
  164. package/dist/agent/core/conclusionGenerator.d.ts.map +1 -0
  165. package/dist/agent/core/conclusionGenerator.js +4109 -0
  166. package/dist/agent/core/conclusionGenerator.js.map +1 -0
  167. package/dist/agent/core/conclusionSceneTemplates.d.ts +8 -0
  168. package/dist/agent/core/conclusionSceneTemplates.d.ts.map +1 -0
  169. package/dist/agent/core/conclusionSceneTemplates.js +31 -0
  170. package/dist/agent/core/conclusionSceneTemplates.js.map +1 -0
  171. package/dist/agent/core/drillDownResolver.d.ts +67 -0
  172. package/dist/agent/core/drillDownResolver.d.ts.map +1 -0
  173. package/dist/agent/core/drillDownResolver.js +583 -0
  174. package/dist/agent/core/drillDownResolver.js.map +1 -0
  175. package/dist/agent/core/emittedEnvelopeRegistry.d.ts +75 -0
  176. package/dist/agent/core/emittedEnvelopeRegistry.d.ts.map +1 -0
  177. package/dist/agent/core/emittedEnvelopeRegistry.js +164 -0
  178. package/dist/agent/core/emittedEnvelopeRegistry.js.map +1 -0
  179. package/dist/agent/core/entityCapture.d.ts +53 -0
  180. package/dist/agent/core/entityCapture.d.ts.map +1 -0
  181. package/dist/agent/core/entityCapture.js +522 -0
  182. package/dist/agent/core/entityCapture.js.map +1 -0
  183. package/dist/agent/core/entityRegistry.d.ts +19 -0
  184. package/dist/agent/core/entityRegistry.d.ts.map +1 -0
  185. package/dist/agent/core/entityRegistry.js +102 -0
  186. package/dist/agent/core/entityRegistry.js.map +1 -0
  187. package/dist/agent/core/executors/analysisExecutor.d.ts +21 -0
  188. package/dist/agent/core/executors/analysisExecutor.d.ts.map +1 -0
  189. package/dist/agent/core/executors/analysisExecutor.js +6 -0
  190. package/dist/agent/core/executors/analysisExecutor.js.map +1 -0
  191. package/dist/agent/core/executors/clarifyExecutor.d.ts +42 -0
  192. package/dist/agent/core/executors/clarifyExecutor.d.ts.map +1 -0
  193. package/dist/agent/core/executors/clarifyExecutor.js +316 -0
  194. package/dist/agent/core/executors/clarifyExecutor.js.map +1 -0
  195. package/dist/agent/core/executors/comparisonExecutor.d.ts +39 -0
  196. package/dist/agent/core/executors/comparisonExecutor.d.ts.map +1 -0
  197. package/dist/agent/core/executors/comparisonExecutor.js +404 -0
  198. package/dist/agent/core/executors/comparisonExecutor.js.map +1 -0
  199. package/dist/agent/core/executors/directDrillDownExecutor.d.ts +56 -0
  200. package/dist/agent/core/executors/directDrillDownExecutor.d.ts.map +1 -0
  201. package/dist/agent/core/executors/directDrillDownExecutor.js +665 -0
  202. package/dist/agent/core/executors/directDrillDownExecutor.js.map +1 -0
  203. package/dist/agent/core/executors/directSkillExecutor.d.ts +106 -0
  204. package/dist/agent/core/executors/directSkillExecutor.d.ts.map +1 -0
  205. package/dist/agent/core/executors/directSkillExecutor.js +633 -0
  206. package/dist/agent/core/executors/directSkillExecutor.js.map +1 -0
  207. package/dist/agent/core/executors/extendExecutor.d.ts +50 -0
  208. package/dist/agent/core/executors/extendExecutor.d.ts.map +1 -0
  209. package/dist/agent/core/executors/extendExecutor.js +402 -0
  210. package/dist/agent/core/executors/extendExecutor.js.map +1 -0
  211. package/dist/agent/core/executors/hypothesisExecutor.d.ts +52 -0
  212. package/dist/agent/core/executors/hypothesisExecutor.d.ts.map +1 -0
  213. package/dist/agent/core/executors/hypothesisExecutor.js +564 -0
  214. package/dist/agent/core/executors/hypothesisExecutor.js.map +1 -0
  215. package/dist/agent/core/executors/index.d.ts +9 -0
  216. package/dist/agent/core/executors/index.d.ts.map +1 -0
  217. package/dist/agent/core/executors/index.js +15 -0
  218. package/dist/agent/core/executors/index.js.map +1 -0
  219. package/dist/agent/core/executors/strategy/strategyFrameEnvelopeCoordinator.d.ts +12 -0
  220. package/dist/agent/core/executors/strategy/strategyFrameEnvelopeCoordinator.d.ts.map +1 -0
  221. package/dist/agent/core/executors/strategy/strategyFrameEnvelopeCoordinator.js +186 -0
  222. package/dist/agent/core/executors/strategy/strategyFrameEnvelopeCoordinator.js.map +1 -0
  223. package/dist/agent/core/executors/strategy/strategyFrameMechanismCollector.d.ts +9 -0
  224. package/dist/agent/core/executors/strategy/strategyFrameMechanismCollector.d.ts.map +1 -0
  225. package/dist/agent/core/executors/strategy/strategyFrameMechanismCollector.js +123 -0
  226. package/dist/agent/core/executors/strategy/strategyFrameMechanismCollector.js.map +1 -0
  227. package/dist/agent/core/executors/strategy/strategyStagePlanner.d.ts +18 -0
  228. package/dist/agent/core/executors/strategy/strategyStagePlanner.d.ts.map +1 -0
  229. package/dist/agent/core/executors/strategy/strategyStagePlanner.js +69 -0
  230. package/dist/agent/core/executors/strategy/strategyStagePlanner.js.map +1 -0
  231. package/dist/agent/core/executors/strategy/strategyStageTaskBuilder.d.ts +14 -0
  232. package/dist/agent/core/executors/strategy/strategyStageTaskBuilder.d.ts.map +1 -0
  233. package/dist/agent/core/executors/strategy/strategyStageTaskBuilder.js +129 -0
  234. package/dist/agent/core/executors/strategy/strategyStageTaskBuilder.js.map +1 -0
  235. package/dist/agent/core/executors/strategyExecutor.d.ts +16 -0
  236. package/dist/agent/core/executors/strategyExecutor.d.ts.map +1 -0
  237. package/dist/agent/core/executors/strategyExecutor.js +377 -0
  238. package/dist/agent/core/executors/strategyExecutor.js.map +1 -0
  239. package/dist/agent/core/executors/traceConfigDetector.d.ts +28 -0
  240. package/dist/agent/core/executors/traceConfigDetector.d.ts.map +1 -0
  241. package/dist/agent/core/executors/traceConfigDetector.js +156 -0
  242. package/dist/agent/core/executors/traceConfigDetector.js.map +1 -0
  243. package/dist/agent/core/feedbackSynthesizer.d.ts +28 -0
  244. package/dist/agent/core/feedbackSynthesizer.d.ts.map +1 -0
  245. package/dist/agent/core/feedbackSynthesizer.js +841 -0
  246. package/dist/agent/core/feedbackSynthesizer.js.map +1 -0
  247. package/dist/agent/core/followUpHandler.d.ts +36 -0
  248. package/dist/agent/core/followUpHandler.d.ts.map +1 -0
  249. package/dist/agent/core/followUpHandler.js +413 -0
  250. package/dist/agent/core/followUpHandler.js.map +1 -0
  251. package/dist/agent/core/hypothesisGenerator.d.ts +45 -0
  252. package/dist/agent/core/hypothesisGenerator.d.ts.map +1 -0
  253. package/dist/agent/core/hypothesisGenerator.js +257 -0
  254. package/dist/agent/core/hypothesisGenerator.js.map +1 -0
  255. package/dist/agent/core/incrementalAnalyzer.d.ts +164 -0
  256. package/dist/agent/core/incrementalAnalyzer.d.ts.map +1 -0
  257. package/dist/agent/core/incrementalAnalyzer.js +382 -0
  258. package/dist/agent/core/incrementalAnalyzer.js.map +1 -0
  259. package/dist/agent/core/index.d.ts +25 -0
  260. package/dist/agent/core/index.d.ts.map +1 -0
  261. package/dist/agent/core/index.js +61 -0
  262. package/dist/agent/core/index.js.map +1 -0
  263. package/dist/agent/core/intentUnderstanding.d.ts +28 -0
  264. package/dist/agent/core/intentUnderstanding.d.ts.map +1 -0
  265. package/dist/agent/core/intentUnderstanding.js +451 -0
  266. package/dist/agent/core/intentUnderstanding.js.map +1 -0
  267. package/dist/agent/core/interventionController.d.ts +211 -0
  268. package/dist/agent/core/interventionController.d.ts.map +1 -0
  269. package/dist/agent/core/interventionController.js +477 -0
  270. package/dist/agent/core/interventionController.js.map +1 -0
  271. package/dist/agent/core/jankCauseSummarizer.d.ts +87 -0
  272. package/dist/agent/core/jankCauseSummarizer.d.ts.map +1 -0
  273. package/dist/agent/core/jankCauseSummarizer.js +432 -0
  274. package/dist/agent/core/jankCauseSummarizer.js.map +1 -0
  275. package/dist/agent/core/modelRouter.d.ts +164 -0
  276. package/dist/agent/core/modelRouter.d.ts.map +1 -0
  277. package/dist/agent/core/modelRouter.js +1169 -0
  278. package/dist/agent/core/modelRouter.js.map +1 -0
  279. package/dist/agent/core/modelRouterSingleton.d.ts +4 -0
  280. package/dist/agent/core/modelRouterSingleton.d.ts.map +1 -0
  281. package/dist/agent/core/modelRouterSingleton.js +20 -0
  282. package/dist/agent/core/modelRouterSingleton.js.map +1 -0
  283. package/dist/agent/core/orchestratorTypes.d.ts +506 -0
  284. package/dist/agent/core/orchestratorTypes.d.ts.map +1 -0
  285. package/dist/agent/core/orchestratorTypes.js +91 -0
  286. package/dist/agent/core/orchestratorTypes.js.map +1 -0
  287. package/dist/agent/core/pipelineExecutor.d.ts +154 -0
  288. package/dist/agent/core/pipelineExecutor.d.ts.map +1 -0
  289. package/dist/agent/core/pipelineExecutor.js +677 -0
  290. package/dist/agent/core/pipelineExecutor.js.map +1 -0
  291. package/dist/agent/core/scenePolicy.d.ts +3 -0
  292. package/dist/agent/core/scenePolicy.d.ts.map +1 -0
  293. package/dist/agent/core/scenePolicy.js +49 -0
  294. package/dist/agent/core/scenePolicy.js.map +1 -0
  295. package/dist/agent/core/sceneRouter.d.ts +8 -0
  296. package/dist/agent/core/sceneRouter.d.ts.map +1 -0
  297. package/dist/agent/core/sceneRouter.js +122 -0
  298. package/dist/agent/core/sceneRouter.js.map +1 -0
  299. package/dist/agent/core/sceneTaxonomy.d.ts +6 -0
  300. package/dist/agent/core/sceneTaxonomy.d.ts.map +1 -0
  301. package/dist/agent/core/sceneTaxonomy.js +83 -0
  302. package/dist/agent/core/sceneTaxonomy.js.map +1 -0
  303. package/dist/agent/core/sceneTemplateStore.d.ts +10 -0
  304. package/dist/agent/core/sceneTemplateStore.d.ts.map +1 -0
  305. package/dist/agent/core/sceneTemplateStore.js +244 -0
  306. package/dist/agent/core/sceneTemplateStore.js.map +1 -0
  307. package/dist/agent/core/sceneTemplateValidator.d.ts +22 -0
  308. package/dist/agent/core/sceneTemplateValidator.d.ts.map +1 -0
  309. package/dist/agent/core/sceneTemplateValidator.js +226 -0
  310. package/dist/agent/core/sceneTemplateValidator.js.map +1 -0
  311. package/dist/agent/core/sceneTypes.d.ts +53 -0
  312. package/dist/agent/core/sceneTypes.d.ts.map +1 -0
  313. package/dist/agent/core/sceneTypes.js +6 -0
  314. package/dist/agent/core/sceneTypes.js.map +1 -0
  315. package/dist/agent/core/stateMachine.d.ts +135 -0
  316. package/dist/agent/core/stateMachine.d.ts.map +1 -0
  317. package/dist/agent/core/stateMachine.js +516 -0
  318. package/dist/agent/core/stateMachine.js.map +1 -0
  319. package/dist/agent/core/strategySelector.d.ts +121 -0
  320. package/dist/agent/core/strategySelector.d.ts.map +1 -0
  321. package/dist/agent/core/strategySelector.js +344 -0
  322. package/dist/agent/core/strategySelector.js.map +1 -0
  323. package/dist/agent/core/taskGraphExecutor.d.ts +30 -0
  324. package/dist/agent/core/taskGraphExecutor.d.ts.map +1 -0
  325. package/dist/agent/core/taskGraphExecutor.js +142 -0
  326. package/dist/agent/core/taskGraphExecutor.js.map +1 -0
  327. package/dist/agent/core/taskGraphPlanner.d.ts +33 -0
  328. package/dist/agent/core/taskGraphPlanner.d.ts.map +1 -0
  329. package/dist/agent/core/taskGraphPlanner.js +312 -0
  330. package/dist/agent/core/taskGraphPlanner.js.map +1 -0
  331. package/dist/agent/decision/decisionTreeExecutor.d.ts +55 -0
  332. package/dist/agent/decision/decisionTreeExecutor.d.ts.map +1 -0
  333. package/dist/agent/decision/decisionTreeExecutor.js +250 -0
  334. package/dist/agent/decision/decisionTreeExecutor.js.map +1 -0
  335. package/dist/agent/decision/decisionTreeStageExecutor.d.ts +65 -0
  336. package/dist/agent/decision/decisionTreeStageExecutor.d.ts.map +1 -0
  337. package/dist/agent/decision/decisionTreeStageExecutor.js +286 -0
  338. package/dist/agent/decision/decisionTreeStageExecutor.js.map +1 -0
  339. package/dist/agent/decision/index.d.ts +27 -0
  340. package/dist/agent/decision/index.d.ts.map +1 -0
  341. package/dist/agent/decision/index.js +70 -0
  342. package/dist/agent/decision/index.js.map +1 -0
  343. package/dist/agent/decision/skillExecutorAdapter.d.ts +89 -0
  344. package/dist/agent/decision/skillExecutorAdapter.d.ts.map +1 -0
  345. package/dist/agent/decision/skillExecutorAdapter.js +447 -0
  346. package/dist/agent/decision/skillExecutorAdapter.js.map +1 -0
  347. package/dist/agent/decision/trees/index.d.ts +8 -0
  348. package/dist/agent/decision/trees/index.d.ts.map +1 -0
  349. package/dist/agent/decision/trees/index.js +16 -0
  350. package/dist/agent/decision/trees/index.js.map +1 -0
  351. package/dist/agent/decision/trees/launchDecisionTree.d.ts +7 -0
  352. package/dist/agent/decision/trees/launchDecisionTree.d.ts.map +1 -0
  353. package/dist/agent/decision/trees/launchDecisionTree.js +670 -0
  354. package/dist/agent/decision/trees/launchDecisionTree.js.map +1 -0
  355. package/dist/agent/decision/trees/scrollingDecisionTree.d.ts +7 -0
  356. package/dist/agent/decision/trees/scrollingDecisionTree.d.ts.map +1 -0
  357. package/dist/agent/decision/trees/scrollingDecisionTree.js +698 -0
  358. package/dist/agent/decision/trees/scrollingDecisionTree.js.map +1 -0
  359. package/dist/agent/decision/types.d.ts +191 -0
  360. package/dist/agent/decision/types.d.ts.map +1 -0
  361. package/dist/agent/decision/types.js +6 -0
  362. package/dist/agent/decision/types.js.map +1 -0
  363. package/dist/agent/detectors/architectureDetector.d.ts +31 -0
  364. package/dist/agent/detectors/architectureDetector.d.ts.map +1 -0
  365. package/dist/agent/detectors/architectureDetector.js +190 -0
  366. package/dist/agent/detectors/architectureDetector.js.map +1 -0
  367. package/dist/agent/detectors/index.d.ts +11 -0
  368. package/dist/agent/detectors/index.d.ts.map +1 -0
  369. package/dist/agent/detectors/index.js +36 -0
  370. package/dist/agent/detectors/index.js.map +1 -0
  371. package/dist/agent/detectors/types.d.ts +113 -0
  372. package/dist/agent/detectors/types.d.ts.map +1 -0
  373. package/dist/agent/detectors/types.js +6 -0
  374. package/dist/agent/detectors/types.js.map +1 -0
  375. package/dist/agent/evalSystem.d.ts +61 -0
  376. package/dist/agent/evalSystem.d.ts.map +1 -0
  377. package/dist/agent/evalSystem.js +210 -0
  378. package/dist/agent/evalSystem.js.map +1 -0
  379. package/dist/agent/experts/base/baseExpert.d.ts +108 -0
  380. package/dist/agent/experts/base/baseExpert.d.ts.map +1 -0
  381. package/dist/agent/experts/base/baseExpert.js +359 -0
  382. package/dist/agent/experts/base/baseExpert.js.map +1 -0
  383. package/dist/agent/experts/base/index.d.ts +9 -0
  384. package/dist/agent/experts/base/index.d.ts.map +1 -0
  385. package/dist/agent/experts/base/index.js +15 -0
  386. package/dist/agent/experts/base/index.js.map +1 -0
  387. package/dist/agent/experts/base/types.d.ts +202 -0
  388. package/dist/agent/experts/base/types.d.ts.map +1 -0
  389. package/dist/agent/experts/base/types.js +6 -0
  390. package/dist/agent/experts/base/types.js.map +1 -0
  391. package/dist/agent/experts/crossDomain/baseCrossDomainExpert.d.ts +113 -0
  392. package/dist/agent/experts/crossDomain/baseCrossDomainExpert.d.ts.map +1 -0
  393. package/dist/agent/experts/crossDomain/baseCrossDomainExpert.js +412 -0
  394. package/dist/agent/experts/crossDomain/baseCrossDomainExpert.js.map +1 -0
  395. package/dist/agent/experts/crossDomain/dialogueProtocol.d.ts +164 -0
  396. package/dist/agent/experts/crossDomain/dialogueProtocol.d.ts.map +1 -0
  397. package/dist/agent/experts/crossDomain/dialogueProtocol.js +390 -0
  398. package/dist/agent/experts/crossDomain/dialogueProtocol.js.map +1 -0
  399. package/dist/agent/experts/crossDomain/experts/performanceExpert.d.ts +119 -0
  400. package/dist/agent/experts/crossDomain/experts/performanceExpert.d.ts.map +1 -0
  401. package/dist/agent/experts/crossDomain/experts/performanceExpert.js +736 -0
  402. package/dist/agent/experts/crossDomain/experts/performanceExpert.js.map +1 -0
  403. package/dist/agent/experts/crossDomain/hypothesisManager.d.ts +105 -0
  404. package/dist/agent/experts/crossDomain/hypothesisManager.d.ts.map +1 -0
  405. package/dist/agent/experts/crossDomain/hypothesisManager.js +283 -0
  406. package/dist/agent/experts/crossDomain/hypothesisManager.js.map +1 -0
  407. package/dist/agent/experts/crossDomain/index.d.ts +18 -0
  408. package/dist/agent/experts/crossDomain/index.d.ts.map +1 -0
  409. package/dist/agent/experts/crossDomain/index.js +28 -0
  410. package/dist/agent/experts/crossDomain/index.js.map +1 -0
  411. package/dist/agent/experts/crossDomain/moduleCatalog.d.ts +97 -0
  412. package/dist/agent/experts/crossDomain/moduleCatalog.d.ts.map +1 -0
  413. package/dist/agent/experts/crossDomain/moduleCatalog.js +453 -0
  414. package/dist/agent/experts/crossDomain/moduleCatalog.js.map +1 -0
  415. package/dist/agent/experts/crossDomain/moduleExpertInvoker.d.ts +149 -0
  416. package/dist/agent/experts/crossDomain/moduleExpertInvoker.d.ts.map +1 -0
  417. package/dist/agent/experts/crossDomain/moduleExpertInvoker.js +582 -0
  418. package/dist/agent/experts/crossDomain/moduleExpertInvoker.js.map +1 -0
  419. package/dist/agent/experts/crossDomain/types.d.ts +369 -0
  420. package/dist/agent/experts/crossDomain/types.d.ts.map +1 -0
  421. package/dist/agent/experts/crossDomain/types.js +6 -0
  422. package/dist/agent/experts/crossDomain/types.js.map +1 -0
  423. package/dist/agent/experts/index.d.ts +81 -0
  424. package/dist/agent/experts/index.d.ts.map +1 -0
  425. package/dist/agent/experts/index.js +222 -0
  426. package/dist/agent/experts/index.js.map +1 -0
  427. package/dist/agent/experts/interactionExpert.d.ts +66 -0
  428. package/dist/agent/experts/interactionExpert.d.ts.map +1 -0
  429. package/dist/agent/experts/interactionExpert.js +280 -0
  430. package/dist/agent/experts/interactionExpert.js.map +1 -0
  431. package/dist/agent/experts/launchExpert.d.ts +73 -0
  432. package/dist/agent/experts/launchExpert.d.ts.map +1 -0
  433. package/dist/agent/experts/launchExpert.js +411 -0
  434. package/dist/agent/experts/launchExpert.js.map +1 -0
  435. package/dist/agent/experts/systemExpert.d.ts +81 -0
  436. package/dist/agent/experts/systemExpert.d.ts.map +1 -0
  437. package/dist/agent/experts/systemExpert.js +507 -0
  438. package/dist/agent/experts/systemExpert.js.map +1 -0
  439. package/dist/agent/fork/forkManager.d.ts +161 -0
  440. package/dist/agent/fork/forkManager.d.ts.map +1 -0
  441. package/dist/agent/fork/forkManager.js +721 -0
  442. package/dist/agent/fork/forkManager.js.map +1 -0
  443. package/dist/agent/fork/forkTypes.d.ts +274 -0
  444. package/dist/agent/fork/forkTypes.d.ts.map +1 -0
  445. package/dist/agent/fork/forkTypes.js +18 -0
  446. package/dist/agent/fork/forkTypes.js.map +1 -0
  447. package/dist/agent/fork/index.d.ts +10 -0
  448. package/dist/agent/fork/index.d.ts.map +1 -0
  449. package/dist/agent/fork/index.js +47 -0
  450. package/dist/agent/fork/index.js.map +1 -0
  451. package/dist/agent/fork/mergeStrategies.d.ts +115 -0
  452. package/dist/agent/fork/mergeStrategies.d.ts.map +1 -0
  453. package/dist/agent/fork/mergeStrategies.js +404 -0
  454. package/dist/agent/fork/mergeStrategies.js.map +1 -0
  455. package/dist/agent/fork/sessionTree.d.ts +141 -0
  456. package/dist/agent/fork/sessionTree.d.ts.map +1 -0
  457. package/dist/agent/fork/sessionTree.js +443 -0
  458. package/dist/agent/fork/sessionTree.js.map +1 -0
  459. package/dist/agent/hooks/hookContext.d.ts +19 -0
  460. package/dist/agent/hooks/hookContext.d.ts.map +1 -0
  461. package/dist/agent/hooks/hookContext.js +67 -0
  462. package/dist/agent/hooks/hookContext.js.map +1 -0
  463. package/dist/agent/hooks/hookRegistry.d.ts +73 -0
  464. package/dist/agent/hooks/hookRegistry.d.ts.map +1 -0
  465. package/dist/agent/hooks/hookRegistry.js +271 -0
  466. package/dist/agent/hooks/hookRegistry.js.map +1 -0
  467. package/dist/agent/hooks/hookTypes.d.ts +186 -0
  468. package/dist/agent/hooks/hookTypes.d.ts.map +1 -0
  469. package/dist/agent/hooks/hookTypes.js +24 -0
  470. package/dist/agent/hooks/hookTypes.js.map +1 -0
  471. package/dist/agent/hooks/index.d.ts +10 -0
  472. package/dist/agent/hooks/index.d.ts.map +1 -0
  473. package/dist/agent/hooks/index.js +41 -0
  474. package/dist/agent/hooks/index.js.map +1 -0
  475. package/dist/agent/hooks/middleware/index.d.ts +6 -0
  476. package/dist/agent/hooks/middleware/index.d.ts.map +1 -0
  477. package/dist/agent/hooks/middleware/index.js +17 -0
  478. package/dist/agent/hooks/middleware/index.js.map +1 -0
  479. package/dist/agent/hooks/middleware/loggingMiddleware.d.ts +27 -0
  480. package/dist/agent/hooks/middleware/loggingMiddleware.d.ts.map +1 -0
  481. package/dist/agent/hooks/middleware/loggingMiddleware.js +104 -0
  482. package/dist/agent/hooks/middleware/loggingMiddleware.js.map +1 -0
  483. package/dist/agent/hooks/middleware/timingMiddleware.d.ts +56 -0
  484. package/dist/agent/hooks/middleware/timingMiddleware.d.ts.map +1 -0
  485. package/dist/agent/hooks/middleware/timingMiddleware.js +171 -0
  486. package/dist/agent/hooks/middleware/timingMiddleware.js.map +1 -0
  487. package/dist/agent/index.d.ts +15 -0
  488. package/dist/agent/index.d.ts.map +1 -0
  489. package/dist/agent/index.js +88 -0
  490. package/dist/agent/index.js.map +1 -0
  491. package/dist/agent/llmAdapter.d.ts +33 -0
  492. package/dist/agent/llmAdapter.d.ts.map +1 -0
  493. package/dist/agent/llmAdapter.js +257 -0
  494. package/dist/agent/llmAdapter.js.map +1 -0
  495. package/dist/agent/scene/sceneAnalysisJobRunner.d.ts +106 -0
  496. package/dist/agent/scene/sceneAnalysisJobRunner.d.ts.map +1 -0
  497. package/dist/agent/scene/sceneAnalysisJobRunner.js +201 -0
  498. package/dist/agent/scene/sceneAnalysisJobRunner.js.map +1 -0
  499. package/dist/agent/scene/sceneCostEstimator.d.ts +33 -0
  500. package/dist/agent/scene/sceneCostEstimator.d.ts.map +1 -0
  501. package/dist/agent/scene/sceneCostEstimator.js +42 -0
  502. package/dist/agent/scene/sceneCostEstimator.js.map +1 -0
  503. package/dist/agent/scene/sceneIntervalBuilder.d.ts +37 -0
  504. package/dist/agent/scene/sceneIntervalBuilder.d.ts.map +1 -0
  505. package/dist/agent/scene/sceneIntervalBuilder.js +748 -0
  506. package/dist/agent/scene/sceneIntervalBuilder.js.map +1 -0
  507. package/dist/agent/scene/sceneStage1Runner.d.ts +47 -0
  508. package/dist/agent/scene/sceneStage1Runner.d.ts.map +1 -0
  509. package/dist/agent/scene/sceneStage1Runner.js +49 -0
  510. package/dist/agent/scene/sceneStage1Runner.js.map +1 -0
  511. package/dist/agent/scene/sceneStage3Summarizer.d.ts +11 -0
  512. package/dist/agent/scene/sceneStage3Summarizer.d.ts.map +1 -0
  513. package/dist/agent/scene/sceneStage3Summarizer.js +155 -0
  514. package/dist/agent/scene/sceneStage3Summarizer.js.map +1 -0
  515. package/dist/agent/scene/sceneStoryService.d.ts +168 -0
  516. package/dist/agent/scene/sceneStoryService.d.ts.map +1 -0
  517. package/dist/agent/scene/sceneStoryService.js +623 -0
  518. package/dist/agent/scene/sceneStoryService.js.map +1 -0
  519. package/dist/agent/scene/sceneTraceDurationProbe.d.ts +16 -0
  520. package/dist/agent/scene/sceneTraceDurationProbe.d.ts.map +1 -0
  521. package/dist/agent/scene/sceneTraceDurationProbe.js +22 -0
  522. package/dist/agent/scene/sceneTraceDurationProbe.js.map +1 -0
  523. package/dist/agent/scene/traceHash.d.ts +23 -0
  524. package/dist/agent/scene/traceHash.d.ts.map +1 -0
  525. package/dist/agent/scene/traceHash.js +65 -0
  526. package/dist/agent/scene/traceHash.js.map +1 -0
  527. package/dist/agent/scene/types.d.ts +199 -0
  528. package/dist/agent/scene/types.d.ts.map +1 -0
  529. package/dist/agent/scene/types.js +6 -0
  530. package/dist/agent/scene/types.js.map +1 -0
  531. package/dist/agent/state/checkpointManager.d.ts +85 -0
  532. package/dist/agent/state/checkpointManager.d.ts.map +1 -0
  533. package/dist/agent/state/checkpointManager.js +339 -0
  534. package/dist/agent/state/checkpointManager.js.map +1 -0
  535. package/dist/agent/state/index.d.ts +11 -0
  536. package/dist/agent/state/index.d.ts.map +1 -0
  537. package/dist/agent/state/index.js +21 -0
  538. package/dist/agent/state/index.js.map +1 -0
  539. package/dist/agent/state/sessionStore.d.ts +126 -0
  540. package/dist/agent/state/sessionStore.d.ts.map +1 -0
  541. package/dist/agent/state/sessionStore.js +440 -0
  542. package/dist/agent/state/sessionStore.js.map +1 -0
  543. package/dist/agent/state/traceAgentState.d.ts +125 -0
  544. package/dist/agent/state/traceAgentState.d.ts.map +1 -0
  545. package/dist/agent/state/traceAgentState.js +173 -0
  546. package/dist/agent/state/traceAgentState.js.map +1 -0
  547. package/dist/agent/strategies/helpers.d.ts +44 -0
  548. package/dist/agent/strategies/helpers.d.ts.map +1 -0
  549. package/dist/agent/strategies/helpers.js +138 -0
  550. package/dist/agent/strategies/helpers.js.map +1 -0
  551. package/dist/agent/strategies/index.d.ts +15 -0
  552. package/dist/agent/strategies/index.d.ts.map +1 -0
  553. package/dist/agent/strategies/index.js +23 -0
  554. package/dist/agent/strategies/index.js.map +1 -0
  555. package/dist/agent/strategies/interactionStrategy.d.ts +3 -0
  556. package/dist/agent/strategies/interactionStrategy.d.ts.map +1 -0
  557. package/dist/agent/strategies/interactionStrategy.js +242 -0
  558. package/dist/agent/strategies/interactionStrategy.js.map +1 -0
  559. package/dist/agent/strategies/registry.d.ts +110 -0
  560. package/dist/agent/strategies/registry.d.ts.map +1 -0
  561. package/dist/agent/strategies/registry.js +264 -0
  562. package/dist/agent/strategies/registry.js.map +1 -0
  563. package/dist/agent/strategies/sceneReconstructionStrategy.d.ts +4 -0
  564. package/dist/agent/strategies/sceneReconstructionStrategy.d.ts.map +1 -0
  565. package/dist/agent/strategies/sceneReconstructionStrategy.js +593 -0
  566. package/dist/agent/strategies/sceneReconstructionStrategy.js.map +1 -0
  567. package/dist/agent/strategies/scrollingStrategy.d.ts +3 -0
  568. package/dist/agent/strategies/scrollingStrategy.d.ts.map +1 -0
  569. package/dist/agent/strategies/scrollingStrategy.js +414 -0
  570. package/dist/agent/strategies/scrollingStrategy.js.map +1 -0
  571. package/dist/agent/strategies/startupStrategy.d.ts +3 -0
  572. package/dist/agent/strategies/startupStrategy.d.ts.map +1 -0
  573. package/dist/agent/strategies/startupStrategy.js +495 -0
  574. package/dist/agent/strategies/startupStrategy.js.map +1 -0
  575. package/dist/agent/strategies/types.d.ts +156 -0
  576. package/dist/agent/strategies/types.d.ts.map +1 -0
  577. package/dist/agent/strategies/types.js +6 -0
  578. package/dist/agent/strategies/types.js.map +1 -0
  579. package/dist/agent/toolRegistry.d.ts +4 -0
  580. package/dist/agent/toolRegistry.d.ts.map +1 -0
  581. package/dist/agent/toolRegistry.js +45 -0
  582. package/dist/agent/toolRegistry.js.map +1 -0
  583. package/dist/agent/tools/dataStats.d.ts +23 -0
  584. package/dist/agent/tools/dataStats.d.ts.map +1 -0
  585. package/dist/agent/tools/dataStats.js +123 -0
  586. package/dist/agent/tools/dataStats.js.map +1 -0
  587. package/dist/agent/tools/frameAnalyzer.d.ts +45 -0
  588. package/dist/agent/tools/frameAnalyzer.d.ts.map +1 -0
  589. package/dist/agent/tools/frameAnalyzer.js +338 -0
  590. package/dist/agent/tools/frameAnalyzer.js.map +1 -0
  591. package/dist/agent/tools/index.d.ts +6 -0
  592. package/dist/agent/tools/index.d.ts.map +1 -0
  593. package/dist/agent/tools/index.js +31 -0
  594. package/dist/agent/tools/index.js.map +1 -0
  595. package/dist/agent/tools/skillInvoker.d.ts +50 -0
  596. package/dist/agent/tools/skillInvoker.d.ts.map +1 -0
  597. package/dist/agent/tools/skillInvoker.js +279 -0
  598. package/dist/agent/tools/skillInvoker.js.map +1 -0
  599. package/dist/agent/tools/sqlExecutor.d.ts +12 -0
  600. package/dist/agent/tools/sqlExecutor.d.ts.map +1 -0
  601. package/dist/agent/tools/sqlExecutor.js +193 -0
  602. package/dist/agent/tools/sqlExecutor.js.map +1 -0
  603. package/dist/agent/tools/sqlGenerator.d.ts +154 -0
  604. package/dist/agent/tools/sqlGenerator.d.ts.map +1 -0
  605. package/dist/agent/tools/sqlGenerator.js +449 -0
  606. package/dist/agent/tools/sqlGenerator.js.map +1 -0
  607. package/dist/agent/tools/sqlValidator.d.ts +149 -0
  608. package/dist/agent/tools/sqlValidator.d.ts.map +1 -0
  609. package/dist/agent/tools/sqlValidator.js +376 -0
  610. package/dist/agent/tools/sqlValidator.js.map +1 -0
  611. package/dist/agent/traceRecorder.d.ts +42 -0
  612. package/dist/agent/traceRecorder.d.ts.map +1 -0
  613. package/dist/agent/traceRecorder.js +122 -0
  614. package/dist/agent/traceRecorder.js.map +1 -0
  615. package/dist/agent/types/agentProtocol.d.ts +377 -0
  616. package/dist/agent/types/agentProtocol.d.ts.map +1 -0
  617. package/dist/agent/types/agentProtocol.js +102 -0
  618. package/dist/agent/types/agentProtocol.js.map +1 -0
  619. package/dist/agent/types/jankCause.d.ts +47 -0
  620. package/dist/agent/types/jankCause.d.ts.map +1 -0
  621. package/dist/agent/types/jankCause.js +6 -0
  622. package/dist/agent/types/jankCause.js.map +1 -0
  623. package/dist/agent/types.d.ts +725 -0
  624. package/dist/agent/types.d.ts.map +1 -0
  625. package/dist/agent/types.js +63 -0
  626. package/dist/agent/types.js.map +1 -0
  627. package/dist/agentOpenAI/index.d.ts +4 -0
  628. package/dist/agentOpenAI/index.d.ts.map +1 -0
  629. package/dist/agentOpenAI/index.js +17 -0
  630. package/dist/agentOpenAI/index.js.map +1 -0
  631. package/dist/agentOpenAI/mimoReasoningCompat.d.ts +9 -0
  632. package/dist/agentOpenAI/mimoReasoningCompat.d.ts.map +1 -0
  633. package/dist/agentOpenAI/mimoReasoningCompat.js +367 -0
  634. package/dist/agentOpenAI/mimoReasoningCompat.js.map +1 -0
  635. package/dist/agentOpenAI/openAiComplexityClassifier.d.ts +18 -0
  636. package/dist/agentOpenAI/openAiComplexityClassifier.d.ts.map +1 -0
  637. package/dist/agentOpenAI/openAiComplexityClassifier.js +102 -0
  638. package/dist/agentOpenAI/openAiComplexityClassifier.js.map +1 -0
  639. package/dist/agentOpenAI/openAiConfig.d.ts +38 -0
  640. package/dist/agentOpenAI/openAiConfig.d.ts.map +1 -0
  641. package/dist/agentOpenAI/openAiConfig.js +104 -0
  642. package/dist/agentOpenAI/openAiConfig.js.map +1 -0
  643. package/dist/agentOpenAI/openAiRuntime.d.ts +99 -0
  644. package/dist/agentOpenAI/openAiRuntime.d.ts.map +1 -0
  645. package/dist/agentOpenAI/openAiRuntime.js +1440 -0
  646. package/dist/agentOpenAI/openAiRuntime.js.map +1 -0
  647. package/dist/agentOpenAI/openAiToolAdapter.d.ts +9 -0
  648. package/dist/agentOpenAI/openAiToolAdapter.d.ts.map +1 -0
  649. package/dist/agentOpenAI/openAiToolAdapter.js +111 -0
  650. package/dist/agentOpenAI/openAiToolAdapter.js.map +1 -0
  651. package/dist/agentRuntime/envCredentialSources.d.ts +6 -0
  652. package/dist/agentRuntime/envCredentialSources.d.ts.map +1 -0
  653. package/dist/agentRuntime/envCredentialSources.js +104 -0
  654. package/dist/agentRuntime/envCredentialSources.js.map +1 -0
  655. package/dist/agentRuntime/index.d.ts +2 -0
  656. package/dist/agentRuntime/index.d.ts.map +1 -0
  657. package/dist/agentRuntime/index.js +10 -0
  658. package/dist/agentRuntime/index.js.map +1 -0
  659. package/dist/agentRuntime/runtimeHealth.d.ts +65 -0
  660. package/dist/agentRuntime/runtimeHealth.d.ts.map +1 -0
  661. package/dist/agentRuntime/runtimeHealth.js +58 -0
  662. package/dist/agentRuntime/runtimeHealth.js.map +1 -0
  663. package/dist/agentRuntime/runtimeSelection.d.ts +25 -0
  664. package/dist/agentRuntime/runtimeSelection.d.ts.map +1 -0
  665. package/dist/agentRuntime/runtimeSelection.js +66 -0
  666. package/dist/agentRuntime/runtimeSelection.js.map +1 -0
  667. package/dist/agentv3/__mocks__/claude-agent-sdk.d.ts +25 -0
  668. package/dist/agentv3/__mocks__/claude-agent-sdk.d.ts.map +1 -0
  669. package/dist/agentv3/__mocks__/claude-agent-sdk.js +48 -0
  670. package/dist/agentv3/__mocks__/claude-agent-sdk.js.map +1 -0
  671. package/dist/agentv3/activePhaseReminder.d.ts +12 -0
  672. package/dist/agentv3/activePhaseReminder.d.ts.map +1 -0
  673. package/dist/agentv3/activePhaseReminder.js +73 -0
  674. package/dist/agentv3/activePhaseReminder.js.map +1 -0
  675. package/dist/agentv3/agentMetrics.d.ts +114 -0
  676. package/dist/agentv3/agentMetrics.d.ts.map +1 -0
  677. package/dist/agentv3/agentMetrics.js +262 -0
  678. package/dist/agentv3/agentMetrics.js.map +1 -0
  679. package/dist/agentv3/analysisPatternMemory.d.ts +146 -0
  680. package/dist/agentv3/analysisPatternMemory.d.ts.map +1 -0
  681. package/dist/agentv3/analysisPatternMemory.js +860 -0
  682. package/dist/agentv3/analysisPatternMemory.js.map +1 -0
  683. package/dist/agentv3/analysisTermination.d.ts +21 -0
  684. package/dist/agentv3/analysisTermination.d.ts.map +1 -0
  685. package/dist/agentv3/analysisTermination.js +97 -0
  686. package/dist/agentv3/analysisTermination.js.map +1 -0
  687. package/dist/agentv3/artifactStore.d.ts +131 -0
  688. package/dist/agentv3/artifactStore.d.ts.map +1 -0
  689. package/dist/agentv3/artifactStore.js +208 -0
  690. package/dist/agentv3/artifactStore.js.map +1 -0
  691. package/dist/agentv3/claudeAgentDefinitions.d.ts +44 -0
  692. package/dist/agentv3/claudeAgentDefinitions.d.ts.map +1 -0
  693. package/dist/agentv3/claudeAgentDefinitions.js +209 -0
  694. package/dist/agentv3/claudeAgentDefinitions.js.map +1 -0
  695. package/dist/agentv3/claudeConfig.d.ts +156 -0
  696. package/dist/agentv3/claudeConfig.d.ts.map +1 -0
  697. package/dist/agentv3/claudeConfig.js +553 -0
  698. package/dist/agentv3/claudeConfig.js.map +1 -0
  699. package/dist/agentv3/claudeFindingExtractor.d.ts +15 -0
  700. package/dist/agentv3/claudeFindingExtractor.d.ts.map +1 -0
  701. package/dist/agentv3/claudeFindingExtractor.js +150 -0
  702. package/dist/agentv3/claudeFindingExtractor.js.map +1 -0
  703. package/dist/agentv3/claudeMcpServer.d.ts +89 -0
  704. package/dist/agentv3/claudeMcpServer.d.ts.map +1 -0
  705. package/dist/agentv3/claudeMcpServer.js +3785 -0
  706. package/dist/agentv3/claudeMcpServer.js.map +1 -0
  707. package/dist/agentv3/claudeRuntime.d.ts +137 -0
  708. package/dist/agentv3/claudeRuntime.d.ts.map +1 -0
  709. package/dist/agentv3/claudeRuntime.js +2541 -0
  710. package/dist/agentv3/claudeRuntime.js.map +1 -0
  711. package/dist/agentv3/claudeSseBridge.d.ts +23 -0
  712. package/dist/agentv3/claudeSseBridge.d.ts.map +1 -0
  713. package/dist/agentv3/claudeSseBridge.js +385 -0
  714. package/dist/agentv3/claudeSseBridge.js.map +1 -0
  715. package/dist/agentv3/claudeSystemPrompt.d.ts +65 -0
  716. package/dist/agentv3/claudeSystemPrompt.d.ts.map +1 -0
  717. package/dist/agentv3/claudeSystemPrompt.js +486 -0
  718. package/dist/agentv3/claudeSystemPrompt.js.map +1 -0
  719. package/dist/agentv3/claudeVerifier.d.ts +82 -0
  720. package/dist/agentv3/claudeVerifier.d.ts.map +1 -0
  721. package/dist/agentv3/claudeVerifier.js +1047 -0
  722. package/dist/agentv3/claudeVerifier.js.map +1 -0
  723. package/dist/agentv3/contextTokenMeter.d.ts +78 -0
  724. package/dist/agentv3/contextTokenMeter.d.ts.map +1 -0
  725. package/dist/agentv3/contextTokenMeter.js +88 -0
  726. package/dist/agentv3/contextTokenMeter.js.map +1 -0
  727. package/dist/agentv3/focusAppDetector.d.ts +22 -0
  728. package/dist/agentv3/focusAppDetector.d.ts.map +1 -0
  729. package/dist/agentv3/focusAppDetector.js +208 -0
  730. package/dist/agentv3/focusAppDetector.js.map +1 -0
  731. package/dist/agentv3/index.d.ts +6 -0
  732. package/dist/agentv3/index.d.ts.map +1 -0
  733. package/dist/agentv3/index.js +16 -0
  734. package/dist/agentv3/index.js.map +1 -0
  735. package/dist/agentv3/mcpToolRegistry.d.ts +90 -0
  736. package/dist/agentv3/mcpToolRegistry.d.ts.map +1 -0
  737. package/dist/agentv3/mcpToolRegistry.js +152 -0
  738. package/dist/agentv3/mcpToolRegistry.js.map +1 -0
  739. package/dist/agentv3/outputLanguage.d.ts +6 -0
  740. package/dist/agentv3/outputLanguage.d.ts.map +1 -0
  741. package/dist/agentv3/outputLanguage.js +37 -0
  742. package/dist/agentv3/outputLanguage.js.map +1 -0
  743. package/dist/agentv3/phaseHintMatcher.d.ts +36 -0
  744. package/dist/agentv3/phaseHintMatcher.d.ts.map +1 -0
  745. package/dist/agentv3/phaseHintMatcher.js +48 -0
  746. package/dist/agentv3/phaseHintMatcher.js.map +1 -0
  747. package/dist/agentv3/projectMemory.d.ts +80 -0
  748. package/dist/agentv3/projectMemory.d.ts.map +1 -0
  749. package/dist/agentv3/projectMemory.js +334 -0
  750. package/dist/agentv3/projectMemory.js.map +1 -0
  751. package/dist/agentv3/queryComplexityClassifier.d.ts +21 -0
  752. package/dist/agentv3/queryComplexityClassifier.d.ts.map +1 -0
  753. package/dist/agentv3/queryComplexityClassifier.js +196 -0
  754. package/dist/agentv3/queryComplexityClassifier.js.map +1 -0
  755. package/dist/agentv3/rawSqlNormalizer.d.ts +11 -0
  756. package/dist/agentv3/rawSqlNormalizer.d.ts.map +1 -0
  757. package/dist/agentv3/rawSqlNormalizer.js +649 -0
  758. package/dist/agentv3/rawSqlNormalizer.js.map +1 -0
  759. package/dist/agentv3/recoveryNoteBuilder.d.ts +51 -0
  760. package/dist/agentv3/recoveryNoteBuilder.d.ts.map +1 -0
  761. package/dist/agentv3/recoveryNoteBuilder.js +84 -0
  762. package/dist/agentv3/recoveryNoteBuilder.js.map +1 -0
  763. package/dist/agentv3/sceneClassifier.d.ts +11 -0
  764. package/dist/agentv3/sceneClassifier.d.ts.map +1 -0
  765. package/dist/agentv3/sceneClassifier.js +46 -0
  766. package/dist/agentv3/sceneClassifier.js.map +1 -0
  767. package/dist/agentv3/scenePlanTemplates.d.ts +80 -0
  768. package/dist/agentv3/scenePlanTemplates.d.ts.map +1 -0
  769. package/dist/agentv3/scenePlanTemplates.js +164 -0
  770. package/dist/agentv3/scenePlanTemplates.js.map +1 -0
  771. package/dist/agentv3/selfImprove/contentScanner.d.ts +44 -0
  772. package/dist/agentv3/selfImprove/contentScanner.d.ts.map +1 -0
  773. package/dist/agentv3/selfImprove/contentScanner.js +112 -0
  774. package/dist/agentv3/selfImprove/contentScanner.js.map +1 -0
  775. package/dist/agentv3/selfImprove/failureTaxonomy.d.ts +38 -0
  776. package/dist/agentv3/selfImprove/failureTaxonomy.d.ts.map +1 -0
  777. package/dist/agentv3/selfImprove/failureTaxonomy.js +102 -0
  778. package/dist/agentv3/selfImprove/failureTaxonomy.js.map +1 -0
  779. package/dist/agentv3/selfImprove/feedbackEnricher.d.ts +69 -0
  780. package/dist/agentv3/selfImprove/feedbackEnricher.d.ts.map +1 -0
  781. package/dist/agentv3/selfImprove/feedbackEnricher.js +135 -0
  782. package/dist/agentv3/selfImprove/feedbackEnricher.js.map +1 -0
  783. package/dist/agentv3/selfImprove/feedbackPipeline.d.ts +63 -0
  784. package/dist/agentv3/selfImprove/feedbackPipeline.d.ts.map +1 -0
  785. package/dist/agentv3/selfImprove/feedbackPipeline.js +239 -0
  786. package/dist/agentv3/selfImprove/feedbackPipeline.js.map +1 -0
  787. package/dist/agentv3/selfImprove/hintFingerprint.d.ts +14 -0
  788. package/dist/agentv3/selfImprove/hintFingerprint.d.ts.map +1 -0
  789. package/dist/agentv3/selfImprove/hintFingerprint.js +47 -0
  790. package/dist/agentv3/selfImprove/hintFingerprint.js.map +1 -0
  791. package/dist/agentv3/selfImprove/metricsAggregator.d.ts +46 -0
  792. package/dist/agentv3/selfImprove/metricsAggregator.d.ts.map +1 -0
  793. package/dist/agentv3/selfImprove/metricsAggregator.js +195 -0
  794. package/dist/agentv3/selfImprove/metricsAggregator.js.map +1 -0
  795. package/dist/agentv3/selfImprove/migrateFailureModeHash.d.ts +31 -0
  796. package/dist/agentv3/selfImprove/migrateFailureModeHash.d.ts.map +1 -0
  797. package/dist/agentv3/selfImprove/migrateFailureModeHash.js +220 -0
  798. package/dist/agentv3/selfImprove/migrateFailureModeHash.js.map +1 -0
  799. package/dist/agentv3/selfImprove/phaseHintsRenderer.d.ts +56 -0
  800. package/dist/agentv3/selfImprove/phaseHintsRenderer.d.ts.map +1 -0
  801. package/dist/agentv3/selfImprove/phaseHintsRenderer.js +202 -0
  802. package/dist/agentv3/selfImprove/phaseHintsRenderer.js.map +1 -0
  803. package/dist/agentv3/selfImprove/promoteSkillNote.d.ts +17 -0
  804. package/dist/agentv3/selfImprove/promoteSkillNote.d.ts.map +1 -0
  805. package/dist/agentv3/selfImprove/promoteSkillNote.js +146 -0
  806. package/dist/agentv3/selfImprove/promoteSkillNote.js.map +1 -0
  807. package/dist/agentv3/selfImprove/proposeStrategyPatch.d.ts +40 -0
  808. package/dist/agentv3/selfImprove/proposeStrategyPatch.d.ts.map +1 -0
  809. package/dist/agentv3/selfImprove/proposeStrategyPatch.js +115 -0
  810. package/dist/agentv3/selfImprove/proposeStrategyPatch.js.map +1 -0
  811. package/dist/agentv3/selfImprove/reviewAgentSdk.d.ts +32 -0
  812. package/dist/agentv3/selfImprove/reviewAgentSdk.d.ts.map +1 -0
  813. package/dist/agentv3/selfImprove/reviewAgentSdk.js +173 -0
  814. package/dist/agentv3/selfImprove/reviewAgentSdk.js.map +1 -0
  815. package/dist/agentv3/selfImprove/reviewOutbox.d.ts +128 -0
  816. package/dist/agentv3/selfImprove/reviewOutbox.d.ts.map +1 -0
  817. package/dist/agentv3/selfImprove/reviewOutbox.js +313 -0
  818. package/dist/agentv3/selfImprove/reviewOutbox.js.map +1 -0
  819. package/dist/agentv3/selfImprove/reviewWorker.d.ts +95 -0
  820. package/dist/agentv3/selfImprove/reviewWorker.d.ts.map +1 -0
  821. package/dist/agentv3/selfImprove/reviewWorker.js +172 -0
  822. package/dist/agentv3/selfImprove/reviewWorker.js.map +1 -0
  823. package/dist/agentv3/selfImprove/skillNotesInjector.d.ts +71 -0
  824. package/dist/agentv3/selfImprove/skillNotesInjector.d.ts.map +1 -0
  825. package/dist/agentv3/selfImprove/skillNotesInjector.js +214 -0
  826. package/dist/agentv3/selfImprove/skillNotesInjector.js.map +1 -0
  827. package/dist/agentv3/selfImprove/skillNotesWriter.d.ts +89 -0
  828. package/dist/agentv3/selfImprove/skillNotesWriter.d.ts.map +1 -0
  829. package/dist/agentv3/selfImprove/skillNotesWriter.js +274 -0
  830. package/dist/agentv3/selfImprove/skillNotesWriter.js.map +1 -0
  831. package/dist/agentv3/selfImprove/strategyFingerprint.d.ts +85 -0
  832. package/dist/agentv3/selfImprove/strategyFingerprint.d.ts.map +1 -0
  833. package/dist/agentv3/selfImprove/strategyFingerprint.js +189 -0
  834. package/dist/agentv3/selfImprove/strategyFingerprint.js.map +1 -0
  835. package/dist/agentv3/selfImprove/strategyPatchApplier.d.ts +15 -0
  836. package/dist/agentv3/selfImprove/strategyPatchApplier.d.ts.map +1 -0
  837. package/dist/agentv3/selfImprove/strategyPatchApplier.js +138 -0
  838. package/dist/agentv3/selfImprove/strategyPatchApplier.js.map +1 -0
  839. package/dist/agentv3/selfImprove/supersedeStore.d.ts +136 -0
  840. package/dist/agentv3/selfImprove/supersedeStore.d.ts.map +1 -0
  841. package/dist/agentv3/selfImprove/supersedeStore.js +386 -0
  842. package/dist/agentv3/selfImprove/supersedeStore.js.map +1 -0
  843. package/dist/agentv3/selfImprove/worktreeRunner.d.ts +49 -0
  844. package/dist/agentv3/selfImprove/worktreeRunner.d.ts.map +1 -0
  845. package/dist/agentv3/selfImprove/worktreeRunner.js +153 -0
  846. package/dist/agentv3/selfImprove/worktreeRunner.js.map +1 -0
  847. package/dist/agentv3/sessionStateSnapshot.d.ts +166 -0
  848. package/dist/agentv3/sessionStateSnapshot.d.ts.map +1 -0
  849. package/dist/agentv3/sessionStateSnapshot.js +6 -0
  850. package/dist/agentv3/sessionStateSnapshot.js.map +1 -0
  851. package/dist/agentv3/sqlIncludeInjector.d.ts +24 -0
  852. package/dist/agentv3/sqlIncludeInjector.d.ts.map +1 -0
  853. package/dist/agentv3/sqlIncludeInjector.js +78 -0
  854. package/dist/agentv3/sqlIncludeInjector.js.map +1 -0
  855. package/dist/agentv3/sqlSummarizer.d.ts +38 -0
  856. package/dist/agentv3/sqlSummarizer.d.ts.map +1 -0
  857. package/dist/agentv3/sqlSummarizer.js +101 -0
  858. package/dist/agentv3/sqlSummarizer.js.map +1 -0
  859. package/dist/agentv3/standaloneMcpServer.d.ts +96 -0
  860. package/dist/agentv3/standaloneMcpServer.d.ts.map +1 -0
  861. package/dist/agentv3/standaloneMcpServer.js +244 -0
  862. package/dist/agentv3/standaloneMcpServer.js.map +1 -0
  863. package/dist/agentv3/strategyLoader.d.ts +96 -0
  864. package/dist/agentv3/strategyLoader.d.ts.map +1 -0
  865. package/dist/agentv3/strategyLoader.js +204 -0
  866. package/dist/agentv3/strategyLoader.js.map +1 -0
  867. package/dist/agentv3/toolCallSummary.d.ts +15 -0
  868. package/dist/agentv3/toolCallSummary.d.ts.map +1 -0
  869. package/dist/agentv3/toolCallSummary.js +66 -0
  870. package/dist/agentv3/toolCallSummary.js.map +1 -0
  871. package/dist/agentv3/toolNarration.d.ts +4 -0
  872. package/dist/agentv3/toolNarration.d.ts.map +1 -0
  873. package/dist/agentv3/toolNarration.js +371 -0
  874. package/dist/agentv3/toolNarration.js.map +1 -0
  875. package/dist/agentv3/traceCompletenessProber.d.ts +56 -0
  876. package/dist/agentv3/traceCompletenessProber.d.ts.map +1 -0
  877. package/dist/agentv3/traceCompletenessProber.js +337 -0
  878. package/dist/agentv3/traceCompletenessProber.js.map +1 -0
  879. package/dist/agentv3/types.d.ts +443 -0
  880. package/dist/agentv3/types.d.ts.map +1 -0
  881. package/dist/agentv3/types.js +37 -0
  882. package/dist/agentv3/types.js.map +1 -0
  883. package/dist/assistant/application/agentAnalyzeSessionService.d.ts +130 -0
  884. package/dist/assistant/application/agentAnalyzeSessionService.d.ts.map +1 -0
  885. package/dist/assistant/application/agentAnalyzeSessionService.js +433 -0
  886. package/dist/assistant/application/agentAnalyzeSessionService.js.map +1 -0
  887. package/dist/assistant/application/assistantApplicationService.d.ts +39 -0
  888. package/dist/assistant/application/assistantApplicationService.d.ts.map +1 -0
  889. package/dist/assistant/application/assistantApplicationService.js +88 -0
  890. package/dist/assistant/application/assistantApplicationService.js.map +1 -0
  891. package/dist/assistant/contracts/assistantResultContract.d.ts +41 -0
  892. package/dist/assistant/contracts/assistantResultContract.d.ts.map +1 -0
  893. package/dist/assistant/contracts/assistantResultContract.js +145 -0
  894. package/dist/assistant/contracts/assistantResultContract.js.map +1 -0
  895. package/dist/assistant/stream/sessionSseReplay.d.ts +10 -0
  896. package/dist/assistant/stream/sessionSseReplay.d.ts.map +1 -0
  897. package/dist/assistant/stream/sessionSseReplay.js +42 -0
  898. package/dist/assistant/stream/sessionSseReplay.js.map +1 -0
  899. package/dist/assistant/stream/streamProjector.d.ts +53 -0
  900. package/dist/assistant/stream/streamProjector.d.ts.map +1 -0
  901. package/dist/assistant/stream/streamProjector.js +150 -0
  902. package/dist/assistant/stream/streamProjector.js.map +1 -0
  903. package/dist/cli/commands/coverage.d.ts +12 -0
  904. package/dist/cli/commands/coverage.d.ts.map +1 -0
  905. package/dist/cli/commands/coverage.js +106 -0
  906. package/dist/cli/commands/coverage.js.map +1 -0
  907. package/dist/cli/commands/list.d.ts +11 -0
  908. package/dist/cli/commands/list.d.ts.map +1 -0
  909. package/dist/cli/commands/list.js +169 -0
  910. package/dist/cli/commands/list.js.map +1 -0
  911. package/dist/cli/commands/smoke.d.ts +11 -0
  912. package/dist/cli/commands/smoke.d.ts.map +1 -0
  913. package/dist/cli/commands/smoke.js +215 -0
  914. package/dist/cli/commands/smoke.js.map +1 -0
  915. package/dist/cli/commands/test.d.ts +11 -0
  916. package/dist/cli/commands/test.d.ts.map +1 -0
  917. package/dist/cli/commands/test.js +183 -0
  918. package/dist/cli/commands/test.js.map +1 -0
  919. package/dist/cli/commands/validate.d.ts +26 -0
  920. package/dist/cli/commands/validate.d.ts.map +1 -0
  921. package/dist/cli/commands/validate.js +918 -0
  922. package/dist/cli/commands/validate.js.map +1 -0
  923. package/dist/cli/index.d.ts +3 -0
  924. package/dist/cli/index.d.ts.map +1 -0
  925. package/dist/cli/index.js +29 -0
  926. package/dist/cli/index.js.map +1 -0
  927. package/dist/cli-user/bin.d.ts +3 -0
  928. package/dist/cli-user/bin.d.ts.map +1 -0
  929. package/dist/cli-user/bin.js +490 -0
  930. package/dist/cli-user/bin.js.map +1 -0
  931. package/dist/cli-user/bootstrap.d.ts +12 -0
  932. package/dist/cli-user/bootstrap.d.ts.map +1 -0
  933. package/dist/cli-user/bootstrap.js +165 -0
  934. package/dist/cli-user/bootstrap.js.map +1 -0
  935. package/dist/cli-user/commands/analyze.d.ts +12 -0
  936. package/dist/cli-user/commands/analyze.d.ts.map +1 -0
  937. package/dist/cli-user/commands/analyze.js +83 -0
  938. package/dist/cli-user/commands/analyze.js.map +1 -0
  939. package/dist/cli-user/commands/capture.d.ts +12 -0
  940. package/dist/cli-user/commands/capture.d.ts.map +1 -0
  941. package/dist/cli-user/commands/capture.js +155 -0
  942. package/dist/cli-user/commands/capture.js.map +1 -0
  943. package/dist/cli-user/commands/compare.d.ts +13 -0
  944. package/dist/cli-user/commands/compare.d.ts.map +1 -0
  945. package/dist/cli-user/commands/compare.js +74 -0
  946. package/dist/cli-user/commands/compare.js.map +1 -0
  947. package/dist/cli-user/commands/config.d.ts +9 -0
  948. package/dist/cli-user/commands/config.d.ts.map +1 -0
  949. package/dist/cli-user/commands/config.js +109 -0
  950. package/dist/cli-user/commands/config.js.map +1 -0
  951. package/dist/cli-user/commands/doctor.d.ts +8 -0
  952. package/dist/cli-user/commands/doctor.d.ts.map +1 -0
  953. package/dist/cli-user/commands/doctor.js +37 -0
  954. package/dist/cli-user/commands/doctor.js.map +1 -0
  955. package/dist/cli-user/commands/list.d.ts +10 -0
  956. package/dist/cli-user/commands/list.d.ts.map +1 -0
  957. package/dist/cli-user/commands/list.js +79 -0
  958. package/dist/cli-user/commands/list.js.map +1 -0
  959. package/dist/cli-user/commands/provider.d.ts +12 -0
  960. package/dist/cli-user/commands/provider.d.ts.map +1 -0
  961. package/dist/cli-user/commands/provider.js +121 -0
  962. package/dist/cli-user/commands/provider.js.map +1 -0
  963. package/dist/cli-user/commands/query.d.ts +10 -0
  964. package/dist/cli-user/commands/query.d.ts.map +1 -0
  965. package/dist/cli-user/commands/query.js +128 -0
  966. package/dist/cli-user/commands/query.js.map +1 -0
  967. package/dist/cli-user/commands/report.d.ts +18 -0
  968. package/dist/cli-user/commands/report.d.ts.map +1 -0
  969. package/dist/cli-user/commands/report.js +225 -0
  970. package/dist/cli-user/commands/report.js.map +1 -0
  971. package/dist/cli-user/commands/resume.d.ts +12 -0
  972. package/dist/cli-user/commands/resume.d.ts.map +1 -0
  973. package/dist/cli-user/commands/resume.js +48 -0
  974. package/dist/cli-user/commands/resume.js.map +1 -0
  975. package/dist/cli-user/commands/rm.d.ts +8 -0
  976. package/dist/cli-user/commands/rm.d.ts.map +1 -0
  977. package/dist/cli-user/commands/rm.js +91 -0
  978. package/dist/cli-user/commands/rm.js.map +1 -0
  979. package/dist/cli-user/commands/show.d.ts +8 -0
  980. package/dist/cli-user/commands/show.d.ts.map +1 -0
  981. package/dist/cli-user/commands/show.js +84 -0
  982. package/dist/cli-user/commands/show.js.map +1 -0
  983. package/dist/cli-user/commands/skill.d.ts +11 -0
  984. package/dist/cli-user/commands/skill.d.ts.map +1 -0
  985. package/dist/cli-user/commands/skill.js +118 -0
  986. package/dist/cli-user/commands/skill.js.map +1 -0
  987. package/dist/cli-user/constants.d.ts +10 -0
  988. package/dist/cli-user/constants.d.ts.map +1 -0
  989. package/dist/cli-user/constants.js +16 -0
  990. package/dist/cli-user/constants.js.map +1 -0
  991. package/dist/cli-user/io/indexJson.d.ts +11 -0
  992. package/dist/cli-user/io/indexJson.d.ts.map +1 -0
  993. package/dist/cli-user/io/indexJson.js +79 -0
  994. package/dist/cli-user/io/indexJson.js.map +1 -0
  995. package/dist/cli-user/io/openFile.d.ts +8 -0
  996. package/dist/cli-user/io/openFile.d.ts.map +1 -0
  997. package/dist/cli-user/io/openFile.js +34 -0
  998. package/dist/cli-user/io/openFile.js.map +1 -0
  999. package/dist/cli-user/io/paths.d.ts +33 -0
  1000. package/dist/cli-user/io/paths.d.ts.map +1 -0
  1001. package/dist/cli-user/io/paths.js +149 -0
  1002. package/dist/cli-user/io/paths.js.map +1 -0
  1003. package/dist/cli-user/io/sessionStore.d.ts +17 -0
  1004. package/dist/cli-user/io/sessionStore.d.ts.map +1 -0
  1005. package/dist/cli-user/io/sessionStore.js +101 -0
  1006. package/dist/cli-user/io/sessionStore.js.map +1 -0
  1007. package/dist/cli-user/io/stdio.d.ts +8 -0
  1008. package/dist/cli-user/io/stdio.d.ts.map +1 -0
  1009. package/dist/cli-user/io/stdio.js +25 -0
  1010. package/dist/cli-user/io/stdio.js.map +1 -0
  1011. package/dist/cli-user/io/transcriptWriter.d.ts +5 -0
  1012. package/dist/cli-user/io/transcriptWriter.d.ts.map +1 -0
  1013. package/dist/cli-user/io/transcriptWriter.js +60 -0
  1014. package/dist/cli-user/io/transcriptWriter.js.map +1 -0
  1015. package/dist/cli-user/repl/index.d.ts +14 -0
  1016. package/dist/cli-user/repl/index.d.ts.map +1 -0
  1017. package/dist/cli-user/repl/index.js +301 -0
  1018. package/dist/cli-user/repl/index.js.map +1 -0
  1019. package/dist/cli-user/repl/renderer.d.ts +43 -0
  1020. package/dist/cli-user/repl/renderer.d.ts.map +1 -0
  1021. package/dist/cli-user/repl/renderer.js +210 -0
  1022. package/dist/cli-user/repl/renderer.js.map +1 -0
  1023. package/dist/cli-user/repl/slashCommands.d.ts +49 -0
  1024. package/dist/cli-user/repl/slashCommands.d.ts.map +1 -0
  1025. package/dist/cli-user/repl/slashCommands.js +65 -0
  1026. package/dist/cli-user/repl/slashCommands.js.map +1 -0
  1027. package/dist/cli-user/services/cliAnalyzeService.d.ts +73 -0
  1028. package/dist/cli-user/services/cliAnalyzeService.d.ts.map +1 -0
  1029. package/dist/cli-user/services/cliAnalyzeService.js +393 -0
  1030. package/dist/cli-user/services/cliAnalyzeService.js.map +1 -0
  1031. package/dist/cli-user/services/runtimeGuard.d.ts +46 -0
  1032. package/dist/cli-user/services/runtimeGuard.d.ts.map +1 -0
  1033. package/dist/cli-user/services/runtimeGuard.js +188 -0
  1034. package/dist/cli-user/services/runtimeGuard.js.map +1 -0
  1035. package/dist/cli-user/services/traceProcessorInstaller.d.ts +2 -0
  1036. package/dist/cli-user/services/traceProcessorInstaller.d.ts.map +1 -0
  1037. package/dist/cli-user/services/traceProcessorInstaller.js +241 -0
  1038. package/dist/cli-user/services/traceProcessorInstaller.js.map +1 -0
  1039. package/dist/cli-user/services/turnPersistence.d.ts +41 -0
  1040. package/dist/cli-user/services/turnPersistence.d.ts.map +1 -0
  1041. package/dist/cli-user/services/turnPersistence.js +55 -0
  1042. package/dist/cli-user/services/turnPersistence.js.map +1 -0
  1043. package/dist/cli-user/services/turnRunner.d.ts +49 -0
  1044. package/dist/cli-user/services/turnRunner.d.ts.map +1 -0
  1045. package/dist/cli-user/services/turnRunner.js +436 -0
  1046. package/dist/cli-user/services/turnRunner.js.map +1 -0
  1047. package/dist/cli-user/types.d.ts +62 -0
  1048. package/dist/cli-user/types.d.ts.map +1 -0
  1049. package/dist/cli-user/types.js +6 -0
  1050. package/dist/cli-user/types.js.map +1 -0
  1051. package/dist/config/index.d.ts +393 -0
  1052. package/dist/config/index.d.ts.map +1 -0
  1053. package/dist/config/index.js +334 -0
  1054. package/dist/config/index.js.map +1 -0
  1055. package/dist/config/prompts.d.ts +20 -0
  1056. package/dist/config/prompts.d.ts.map +1 -0
  1057. package/dist/config/prompts.js +74 -0
  1058. package/dist/config/prompts.js.map +1 -0
  1059. package/dist/config/teaching.config.d.ts +253 -0
  1060. package/dist/config/teaching.config.d.ts.map +1 -0
  1061. package/dist/config/teaching.config.js +203 -0
  1062. package/dist/config/teaching.config.js.map +1 -0
  1063. package/dist/config/thresholds.d.ts +300 -0
  1064. package/dist/config/thresholds.d.ts.map +1 -0
  1065. package/dist/config/thresholds.js +338 -0
  1066. package/dist/config/thresholds.js.map +1 -0
  1067. package/dist/controllers/skillAdminController.d.ts +62 -0
  1068. package/dist/controllers/skillAdminController.d.ts.map +1 -0
  1069. package/dist/controllers/skillAdminController.js +482 -0
  1070. package/dist/controllers/skillAdminController.js.map +1 -0
  1071. package/dist/controllers/skillController.d.ts +49 -0
  1072. package/dist/controllers/skillController.d.ts.map +1 -0
  1073. package/dist/controllers/skillController.js +246 -0
  1074. package/dist/controllers/skillController.js.map +1 -0
  1075. package/dist/controllers/sqlController.d.ts +9 -0
  1076. package/dist/controllers/sqlController.d.ts.map +1 -0
  1077. package/dist/controllers/sqlController.js +125 -0
  1078. package/dist/controllers/sqlController.js.map +1 -0
  1079. package/dist/controllers/traceController.d.ts +13 -0
  1080. package/dist/controllers/traceController.d.ts.map +1 -0
  1081. package/dist/controllers/traceController.js +209 -0
  1082. package/dist/controllers/traceController.js.map +1 -0
  1083. package/dist/controllers/traceProcessorController.d.ts +14 -0
  1084. package/dist/controllers/traceProcessorController.d.ts.map +1 -0
  1085. package/dist/controllers/traceProcessorController.js +222 -0
  1086. package/dist/controllers/traceProcessorController.js.map +1 -0
  1087. package/dist/data/perfettoSchema.d.ts +9 -0
  1088. package/dist/data/perfettoSchema.d.ts.map +1 -0
  1089. package/dist/data/perfettoSchema.js +286 -0
  1090. package/dist/data/perfettoSchema.js.map +1 -0
  1091. package/dist/index.d.ts +2 -0
  1092. package/dist/index.d.ts.map +1 -0
  1093. package/dist/index.js +251 -0
  1094. package/dist/index.js.map +1 -0
  1095. package/dist/middleware/auth.d.ts +37 -0
  1096. package/dist/middleware/auth.d.ts.map +1 -0
  1097. package/dist/middleware/auth.js +307 -0
  1098. package/dist/middleware/auth.js.map +1 -0
  1099. package/dist/middleware/legacyAgentApi.d.ts +8 -0
  1100. package/dist/middleware/legacyAgentApi.d.ts.map +1 -0
  1101. package/dist/middleware/legacyAgentApi.js +64 -0
  1102. package/dist/middleware/legacyAgentApi.js.map +1 -0
  1103. package/dist/middleware/workspaceRouteContext.d.ts +4 -0
  1104. package/dist/middleware/workspaceRouteContext.d.ts.map +1 -0
  1105. package/dist/middleware/workspaceRouteContext.js +44 -0
  1106. package/dist/middleware/workspaceRouteContext.js.map +1 -0
  1107. package/dist/models/sessionSchema.d.ts +106 -0
  1108. package/dist/models/sessionSchema.d.ts.map +1 -0
  1109. package/dist/models/sessionSchema.js +6 -0
  1110. package/dist/models/sessionSchema.js.map +1 -0
  1111. package/dist/routes/agentLogsRoutes.d.ts +3 -0
  1112. package/dist/routes/agentLogsRoutes.d.ts.map +1 -0
  1113. package/dist/routes/agentLogsRoutes.js +283 -0
  1114. package/dist/routes/agentLogsRoutes.js.map +1 -0
  1115. package/dist/routes/agentQuickSceneRoutes.d.ts +9 -0
  1116. package/dist/routes/agentQuickSceneRoutes.d.ts.map +1 -0
  1117. package/dist/routes/agentQuickSceneRoutes.js +51 -0
  1118. package/dist/routes/agentQuickSceneRoutes.js.map +1 -0
  1119. package/dist/routes/agentReportRoutes.d.ts +11 -0
  1120. package/dist/routes/agentReportRoutes.d.ts.map +1 -0
  1121. package/dist/routes/agentReportRoutes.js +100 -0
  1122. package/dist/routes/agentReportRoutes.js.map +1 -0
  1123. package/dist/routes/agentResumeRoutes.d.ts +14 -0
  1124. package/dist/routes/agentResumeRoutes.d.ts.map +1 -0
  1125. package/dist/routes/agentResumeRoutes.js +263 -0
  1126. package/dist/routes/agentResumeRoutes.js.map +1 -0
  1127. package/dist/routes/agentRoutes.d.ts +3 -0
  1128. package/dist/routes/agentRoutes.d.ts.map +1 -0
  1129. package/dist/routes/agentRoutes.js +4349 -0
  1130. package/dist/routes/agentRoutes.js.map +1 -0
  1131. package/dist/routes/agentSceneReconstructRoutes.d.ts +68 -0
  1132. package/dist/routes/agentSceneReconstructRoutes.d.ts.map +1 -0
  1133. package/dist/routes/agentSceneReconstructRoutes.js +448 -0
  1134. package/dist/routes/agentSceneReconstructRoutes.js.map +1 -0
  1135. package/dist/routes/agentSessionCatalogRoutes.d.ts +20 -0
  1136. package/dist/routes/agentSessionCatalogRoutes.d.ts.map +1 -0
  1137. package/dist/routes/agentSessionCatalogRoutes.js +90 -0
  1138. package/dist/routes/agentSessionCatalogRoutes.js.map +1 -0
  1139. package/dist/routes/agentTeachingRoutes.d.ts +3 -0
  1140. package/dist/routes/agentTeachingRoutes.d.ts.map +1 -0
  1141. package/dist/routes/agentTeachingRoutes.js +62 -0
  1142. package/dist/routes/agentTeachingRoutes.js.map +1 -0
  1143. package/dist/routes/analysisResultRoutes.d.ts +3 -0
  1144. package/dist/routes/analysisResultRoutes.d.ts.map +1 -0
  1145. package/dist/routes/analysisResultRoutes.js +216 -0
  1146. package/dist/routes/analysisResultRoutes.js.map +1 -0
  1147. package/dist/routes/baselineRoutes.d.ts +29 -0
  1148. package/dist/routes/baselineRoutes.d.ts.map +1 -0
  1149. package/dist/routes/baselineRoutes.js +123 -0
  1150. package/dist/routes/baselineRoutes.js.map +1 -0
  1151. package/dist/routes/caseRoutes.d.ts +29 -0
  1152. package/dist/routes/caseRoutes.d.ts.map +1 -0
  1153. package/dist/routes/caseRoutes.js +194 -0
  1154. package/dist/routes/caseRoutes.js.map +1 -0
  1155. package/dist/routes/ciGateRoutes.d.ts +11 -0
  1156. package/dist/routes/ciGateRoutes.d.ts.map +1 -0
  1157. package/dist/routes/ciGateRoutes.js +363 -0
  1158. package/dist/routes/ciGateRoutes.js.map +1 -0
  1159. package/dist/routes/comparisonRoutes.d.ts +3 -0
  1160. package/dist/routes/comparisonRoutes.d.ts.map +1 -0
  1161. package/dist/routes/comparisonRoutes.js +536 -0
  1162. package/dist/routes/comparisonRoutes.js.map +1 -0
  1163. package/dist/routes/criticalPathRoutes.d.ts +3 -0
  1164. package/dist/routes/criticalPathRoutes.d.ts.map +1 -0
  1165. package/dist/routes/criticalPathRoutes.js +88 -0
  1166. package/dist/routes/criticalPathRoutes.js.map +1 -0
  1167. package/dist/routes/enterpriseApiKeyRoutes.d.ts +9 -0
  1168. package/dist/routes/enterpriseApiKeyRoutes.d.ts.map +1 -0
  1169. package/dist/routes/enterpriseApiKeyRoutes.js +126 -0
  1170. package/dist/routes/enterpriseApiKeyRoutes.js.map +1 -0
  1171. package/dist/routes/enterpriseAuthRoutes.d.ts +18 -0
  1172. package/dist/routes/enterpriseAuthRoutes.d.ts.map +1 -0
  1173. package/dist/routes/enterpriseAuthRoutes.js +160 -0
  1174. package/dist/routes/enterpriseAuthRoutes.js.map +1 -0
  1175. package/dist/routes/enterpriseRuntimeDashboardRoutes.d.ts +6 -0
  1176. package/dist/routes/enterpriseRuntimeDashboardRoutes.d.ts.map +1 -0
  1177. package/dist/routes/enterpriseRuntimeDashboardRoutes.js +32 -0
  1178. package/dist/routes/enterpriseRuntimeDashboardRoutes.js.map +1 -0
  1179. package/dist/routes/enterpriseTenantRoutes.d.ts +4 -0
  1180. package/dist/routes/enterpriseTenantRoutes.d.ts.map +1 -0
  1181. package/dist/routes/enterpriseTenantRoutes.js +313 -0
  1182. package/dist/routes/enterpriseTenantRoutes.js.map +1 -0
  1183. package/dist/routes/exportRoutes.d.ts +3 -0
  1184. package/dist/routes/exportRoutes.d.ts.map +1 -0
  1185. package/dist/routes/exportRoutes.js +196 -0
  1186. package/dist/routes/exportRoutes.js.map +1 -0
  1187. package/dist/routes/flamegraphRoutes.d.ts +3 -0
  1188. package/dist/routes/flamegraphRoutes.d.ts.map +1 -0
  1189. package/dist/routes/flamegraphRoutes.js +99 -0
  1190. package/dist/routes/flamegraphRoutes.js.map +1 -0
  1191. package/dist/routes/memoryRoutes.d.ts +31 -0
  1192. package/dist/routes/memoryRoutes.d.ts.map +1 -0
  1193. package/dist/routes/memoryRoutes.js +150 -0
  1194. package/dist/routes/memoryRoutes.js.map +1 -0
  1195. package/dist/routes/narrativeSanitizer.d.ts +2 -0
  1196. package/dist/routes/narrativeSanitizer.d.ts.map +1 -0
  1197. package/dist/routes/narrativeSanitizer.js +167 -0
  1198. package/dist/routes/narrativeSanitizer.js.map +1 -0
  1199. package/dist/routes/perfettoLocalRoutes.d.ts +3 -0
  1200. package/dist/routes/perfettoLocalRoutes.d.ts.map +1 -0
  1201. package/dist/routes/perfettoLocalRoutes.js +222 -0
  1202. package/dist/routes/perfettoLocalRoutes.js.map +1 -0
  1203. package/dist/routes/perfettoSqlRoutes.d.ts +7 -0
  1204. package/dist/routes/perfettoSqlRoutes.d.ts.map +1 -0
  1205. package/dist/routes/perfettoSqlRoutes.js +738 -0
  1206. package/dist/routes/perfettoSqlRoutes.js.map +1 -0
  1207. package/dist/routes/providerRoutes.d.ts +3 -0
  1208. package/dist/routes/providerRoutes.d.ts.map +1 -0
  1209. package/dist/routes/providerRoutes.js +219 -0
  1210. package/dist/routes/providerRoutes.js.map +1 -0
  1211. package/dist/routes/ragAdminRoutes.d.ts +30 -0
  1212. package/dist/routes/ragAdminRoutes.d.ts.map +1 -0
  1213. package/dist/routes/ragAdminRoutes.js +93 -0
  1214. package/dist/routes/ragAdminRoutes.js.map +1 -0
  1215. package/dist/routes/reportRoutes.d.ts +17 -0
  1216. package/dist/routes/reportRoutes.d.ts.map +1 -0
  1217. package/dist/routes/reportRoutes.js +579 -0
  1218. package/dist/routes/reportRoutes.js.map +1 -0
  1219. package/dist/routes/sessionRoutes.d.ts +3 -0
  1220. package/dist/routes/sessionRoutes.d.ts.map +1 -0
  1221. package/dist/routes/sessionRoutes.js +144 -0
  1222. package/dist/routes/sessionRoutes.js.map +1 -0
  1223. package/dist/routes/simpleTraceRoutes.d.ts +3 -0
  1224. package/dist/routes/simpleTraceRoutes.d.ts.map +1 -0
  1225. package/dist/routes/simpleTraceRoutes.js +1131 -0
  1226. package/dist/routes/simpleTraceRoutes.js.map +1 -0
  1227. package/dist/routes/skillAdminRoutes.d.ts +3 -0
  1228. package/dist/routes/skillAdminRoutes.d.ts.map +1 -0
  1229. package/dist/routes/skillAdminRoutes.js +100 -0
  1230. package/dist/routes/skillAdminRoutes.js.map +1 -0
  1231. package/dist/routes/skillRoutes.d.ts +3 -0
  1232. package/dist/routes/skillRoutes.d.ts.map +1 -0
  1233. package/dist/routes/skillRoutes.js +88 -0
  1234. package/dist/routes/skillRoutes.js.map +1 -0
  1235. package/dist/routes/sql.d.ts +3 -0
  1236. package/dist/routes/sql.d.ts.map +1 -0
  1237. package/dist/routes/sql.js +19 -0
  1238. package/dist/routes/sql.js.map +1 -0
  1239. package/dist/routes/strategyAdminRoutes.d.ts +3 -0
  1240. package/dist/routes/strategyAdminRoutes.d.ts.map +1 -0
  1241. package/dist/routes/strategyAdminRoutes.js +65 -0
  1242. package/dist/routes/strategyAdminRoutes.js.map +1 -0
  1243. package/dist/routes/templateAnalysisRoutes.d.ts +3 -0
  1244. package/dist/routes/templateAnalysisRoutes.d.ts.map +1 -0
  1245. package/dist/routes/templateAnalysisRoutes.js +173 -0
  1246. package/dist/routes/templateAnalysisRoutes.js.map +1 -0
  1247. package/dist/routes/trace.d.ts +3 -0
  1248. package/dist/routes/trace.d.ts.map +1 -0
  1249. package/dist/routes/trace.js +48 -0
  1250. package/dist/routes/trace.js.map +1 -0
  1251. package/dist/routes/traceProcessorProxyRoutes.d.ts +6 -0
  1252. package/dist/routes/traceProcessorProxyRoutes.d.ts.map +1 -0
  1253. package/dist/routes/traceProcessorProxyRoutes.js +607 -0
  1254. package/dist/routes/traceProcessorProxyRoutes.js.map +1 -0
  1255. package/dist/routes/traceProcessorRoutes.d.ts +3 -0
  1256. package/dist/routes/traceProcessorRoutes.d.ts.map +1 -0
  1257. package/dist/routes/traceProcessorRoutes.js +40 -0
  1258. package/dist/routes/traceProcessorRoutes.js.map +1 -0
  1259. package/dist/routes/workspaceWindowRoutes.d.ts +3 -0
  1260. package/dist/routes/workspaceWindowRoutes.d.ts.map +1 -0
  1261. package/dist/routes/workspaceWindowRoutes.js +146 -0
  1262. package/dist/routes/workspaceWindowRoutes.js.map +1 -0
  1263. package/dist/runtimePaths.d.ts +3 -0
  1264. package/dist/runtimePaths.d.ts.map +1 -0
  1265. package/dist/runtimePaths.js +20 -0
  1266. package/dist/runtimePaths.js.map +1 -0
  1267. package/dist/scripts/analyzeComprehensiveTrace.d.ts +2 -0
  1268. package/dist/scripts/analyzeComprehensiveTrace.d.ts.map +1 -0
  1269. package/dist/scripts/analyzeComprehensiveTrace.js +210 -0
  1270. package/dist/scripts/analyzeComprehensiveTrace.js.map +1 -0
  1271. package/dist/scripts/analyzeUserTrace.d.ts +2 -0
  1272. package/dist/scripts/analyzeUserTrace.d.ts.map +1 -0
  1273. package/dist/scripts/analyzeUserTrace.js +170 -0
  1274. package/dist/scripts/analyzeUserTrace.js.map +1 -0
  1275. package/dist/scripts/auditTraceProcessorRssMatrix.d.ts +49 -0
  1276. package/dist/scripts/auditTraceProcessorRssMatrix.d.ts.map +1 -0
  1277. package/dist/scripts/auditTraceProcessorRssMatrix.js +390 -0
  1278. package/dist/scripts/auditTraceProcessorRssMatrix.js.map +1 -0
  1279. package/dist/scripts/benchmarkTraceProcessorRss.d.ts +96 -0
  1280. package/dist/scripts/benchmarkTraceProcessorRss.d.ts.map +1 -0
  1281. package/dist/scripts/benchmarkTraceProcessorRss.js +569 -0
  1282. package/dist/scripts/benchmarkTraceProcessorRss.js.map +1 -0
  1283. package/dist/scripts/captureContextEngineeringBaseline.d.ts +2 -0
  1284. package/dist/scripts/captureContextEngineeringBaseline.d.ts.map +1 -0
  1285. package/dist/scripts/captureContextEngineeringBaseline.js +271 -0
  1286. package/dist/scripts/captureContextEngineeringBaseline.js.map +1 -0
  1287. package/dist/scripts/checkTables.d.ts +2 -0
  1288. package/dist/scripts/checkTables.d.ts.map +1 -0
  1289. package/dist/scripts/checkTables.js +22 -0
  1290. package/dist/scripts/checkTables.js.map +1 -0
  1291. package/dist/scripts/diagnoseJankDetection.d.ts +2 -0
  1292. package/dist/scripts/diagnoseJankDetection.d.ts.map +1 -0
  1293. package/dist/scripts/diagnoseJankDetection.js +314 -0
  1294. package/dist/scripts/diagnoseJankDetection.js.map +1 -0
  1295. package/dist/scripts/diagnoseTrace.d.ts +2 -0
  1296. package/dist/scripts/diagnoseTrace.d.ts.map +1 -0
  1297. package/dist/scripts/diagnoseTrace.js +74 -0
  1298. package/dist/scripts/diagnoseTrace.js.map +1 -0
  1299. package/dist/scripts/enterpriseAcceptanceLoadTest.d.ts +193 -0
  1300. package/dist/scripts/enterpriseAcceptanceLoadTest.d.ts.map +1 -0
  1301. package/dist/scripts/enterpriseAcceptanceLoadTest.js +912 -0
  1302. package/dist/scripts/enterpriseAcceptanceLoadTest.js.map +1 -0
  1303. package/dist/scripts/enterpriseMigrationSnapshot.d.ts +3 -0
  1304. package/dist/scripts/enterpriseMigrationSnapshot.d.ts.map +1 -0
  1305. package/dist/scripts/enterpriseMigrationSnapshot.js +57 -0
  1306. package/dist/scripts/enterpriseMigrationSnapshot.js.map +1 -0
  1307. package/dist/scripts/enterpriseReadinessAudit.d.ts +30 -0
  1308. package/dist/scripts/enterpriseReadinessAudit.d.ts.map +1 -0
  1309. package/dist/scripts/enterpriseReadinessAudit.js +743 -0
  1310. package/dist/scripts/enterpriseReadinessAudit.js.map +1 -0
  1311. package/dist/scripts/enterpriseRssBenchmarkMatrix.d.ts +6 -0
  1312. package/dist/scripts/enterpriseRssBenchmarkMatrix.d.ts.map +1 -0
  1313. package/dist/scripts/enterpriseRssBenchmarkMatrix.js +20 -0
  1314. package/dist/scripts/enterpriseRssBenchmarkMatrix.js.map +1 -0
  1315. package/dist/scripts/enterpriseRuntimeIsolationChecklist.d.ts +22 -0
  1316. package/dist/scripts/enterpriseRuntimeIsolationChecklist.d.ts.map +1 -0
  1317. package/dist/scripts/enterpriseRuntimeIsolationChecklist.js +374 -0
  1318. package/dist/scripts/enterpriseRuntimeIsolationChecklist.js.map +1 -0
  1319. package/dist/scripts/enterpriseSecurityAuditChecklist.d.ts +20 -0
  1320. package/dist/scripts/enterpriseSecurityAuditChecklist.d.ts.map +1 -0
  1321. package/dist/scripts/enterpriseSecurityAuditChecklist.js +113 -0
  1322. package/dist/scripts/enterpriseSecurityAuditChecklist.js.map +1 -0
  1323. package/dist/scripts/probeStdlibSchema.d.ts +2 -0
  1324. package/dist/scripts/probeStdlibSchema.d.ts.map +1 -0
  1325. package/dist/scripts/probeStdlibSchema.js +209 -0
  1326. package/dist/scripts/probeStdlibSchema.js.map +1 -0
  1327. package/dist/scripts/runAgentTest.d.ts +2 -0
  1328. package/dist/scripts/runAgentTest.d.ts.map +1 -0
  1329. package/dist/scripts/runAgentTest.js +149 -0
  1330. package/dist/scripts/runAgentTest.js.map +1 -0
  1331. package/dist/scripts/runScrollingTest.d.ts +2 -0
  1332. package/dist/scripts/runScrollingTest.d.ts.map +1 -0
  1333. package/dist/scripts/runScrollingTest.js +199 -0
  1334. package/dist/scripts/runScrollingTest.js.map +1 -0
  1335. package/dist/scripts/runScrollingTestRealData.d.ts +2 -0
  1336. package/dist/scripts/runScrollingTestRealData.d.ts.map +1 -0
  1337. package/dist/scripts/runScrollingTestRealData.js +121 -0
  1338. package/dist/scripts/runScrollingTestRealData.js.map +1 -0
  1339. package/dist/scripts/testAndroidTrace.d.ts +2 -0
  1340. package/dist/scripts/testAndroidTrace.d.ts.map +1 -0
  1341. package/dist/scripts/testAndroidTrace.js +21 -0
  1342. package/dist/scripts/testAndroidTrace.js.map +1 -0
  1343. package/dist/scripts/testCrossDomainExpert.d.ts +2 -0
  1344. package/dist/scripts/testCrossDomainExpert.d.ts.map +1 -0
  1345. package/dist/scripts/testCrossDomainExpert.js +288 -0
  1346. package/dist/scripts/testCrossDomainExpert.js.map +1 -0
  1347. package/dist/scripts/testCrossDomainIntegration.d.ts +2 -0
  1348. package/dist/scripts/testCrossDomainIntegration.d.ts.map +1 -0
  1349. package/dist/scripts/testCrossDomainIntegration.js +282 -0
  1350. package/dist/scripts/testCrossDomainIntegration.js.map +1 -0
  1351. package/dist/scripts/testDeepLayerFix.d.ts +2 -0
  1352. package/dist/scripts/testDeepLayerFix.d.ts.map +1 -0
  1353. package/dist/scripts/testDeepLayerFix.js +137 -0
  1354. package/dist/scripts/testDeepLayerFix.js.map +1 -0
  1355. package/dist/scripts/testHtmlReportGen.d.ts +2 -0
  1356. package/dist/scripts/testHtmlReportGen.d.ts.map +1 -0
  1357. package/dist/scripts/testHtmlReportGen.js +148 -0
  1358. package/dist/scripts/testHtmlReportGen.js.map +1 -0
  1359. package/dist/scripts/verifyAgentSseScrolling.d.ts +2 -0
  1360. package/dist/scripts/verifyAgentSseScrolling.d.ts.map +1 -0
  1361. package/dist/scripts/verifyAgentSseScrolling.js +558 -0
  1362. package/dist/scripts/verifyAgentSseScrolling.js.map +1 -0
  1363. package/dist/scripts/verifyCriticalPathE2E.d.ts +2 -0
  1364. package/dist/scripts/verifyCriticalPathE2E.d.ts.map +1 -0
  1365. package/dist/scripts/verifyCriticalPathE2E.js +171 -0
  1366. package/dist/scripts/verifyCriticalPathE2E.js.map +1 -0
  1367. package/dist/scripts/verifyEnterpriseMultiTenantWindows.d.ts +24 -0
  1368. package/dist/scripts/verifyEnterpriseMultiTenantWindows.d.ts.map +1 -0
  1369. package/dist/scripts/verifyEnterpriseMultiTenantWindows.js +1363 -0
  1370. package/dist/scripts/verifyEnterpriseMultiTenantWindows.js.map +1 -0
  1371. package/dist/services/adb/adbContextDetector.d.ts +3 -0
  1372. package/dist/services/adb/adbContextDetector.d.ts.map +1 -0
  1373. package/dist/services/adb/adbContextDetector.js +151 -0
  1374. package/dist/services/adb/adbContextDetector.js.map +1 -0
  1375. package/dist/services/adb/adbService.d.ts +28 -0
  1376. package/dist/services/adb/adbService.d.ts.map +1 -0
  1377. package/dist/services/adb/adbService.js +238 -0
  1378. package/dist/services/adb/adbService.js.map +1 -0
  1379. package/dist/services/adb/index.d.ts +5 -0
  1380. package/dist/services/adb/index.d.ts.map +1 -0
  1381. package/dist/services/adb/index.js +24 -0
  1382. package/dist/services/adb/index.js.map +1 -0
  1383. package/dist/services/adb/traceDeviceMatcher.d.ts +12 -0
  1384. package/dist/services/adb/traceDeviceMatcher.d.ts.map +1 -0
  1385. package/dist/services/adb/traceDeviceMatcher.js +149 -0
  1386. package/dist/services/adb/traceDeviceMatcher.js.map +1 -0
  1387. package/dist/services/adb/types.d.ts +69 -0
  1388. package/dist/services/adb/types.d.ts.map +1 -0
  1389. package/dist/services/adb/types.js +6 -0
  1390. package/dist/services/adb/types.js.map +1 -0
  1391. package/dist/services/agentEventStore.d.ts +17 -0
  1392. package/dist/services/agentEventStore.d.ts.map +1 -0
  1393. package/dist/services/agentEventStore.js +139 -0
  1394. package/dist/services/agentEventStore.js.map +1 -0
  1395. package/dist/services/agentReportData.d.ts +42 -0
  1396. package/dist/services/agentReportData.d.ts.map +1 -0
  1397. package/dist/services/agentReportData.js +81 -0
  1398. package/dist/services/agentReportData.js.map +1 -0
  1399. package/dist/services/agentResultNormalizer.d.ts +33 -0
  1400. package/dist/services/agentResultNormalizer.d.ts.map +1 -0
  1401. package/dist/services/agentResultNormalizer.js +92 -0
  1402. package/dist/services/agentResultNormalizer.js.map +1 -0
  1403. package/dist/services/analysisResultSnapshotPipeline.d.ts +24 -0
  1404. package/dist/services/analysisResultSnapshotPipeline.d.ts.map +1 -0
  1405. package/dist/services/analysisResultSnapshotPipeline.js +466 -0
  1406. package/dist/services/analysisResultSnapshotPipeline.js.map +1 -0
  1407. package/dist/services/analysisResultSnapshotStore.d.ts +29 -0
  1408. package/dist/services/analysisResultSnapshotStore.d.ts.map +1 -0
  1409. package/dist/services/analysisResultSnapshotStore.js +457 -0
  1410. package/dist/services/analysisResultSnapshotStore.js.map +1 -0
  1411. package/dist/services/analysisResultWindowStateStore.d.ts +37 -0
  1412. package/dist/services/analysisResultWindowStateStore.d.ts.map +1 -0
  1413. package/dist/services/analysisResultWindowStateStore.js +190 -0
  1414. package/dist/services/analysisResultWindowStateStore.js.map +1 -0
  1415. package/dist/services/analysisRunStore.d.ts +38 -0
  1416. package/dist/services/analysisRunStore.d.ts.map +1 -0
  1417. package/dist/services/analysisRunStore.js +195 -0
  1418. package/dist/services/analysisRunStore.js.map +1 -0
  1419. package/dist/services/analysisTemplates/cpuCoreAnalysis.d.ts +70 -0
  1420. package/dist/services/analysisTemplates/cpuCoreAnalysis.d.ts.map +1 -0
  1421. package/dist/services/analysisTemplates/cpuCoreAnalysis.js +277 -0
  1422. package/dist/services/analysisTemplates/cpuCoreAnalysis.js.map +1 -0
  1423. package/dist/services/analysisTemplates/fourQuadrantAnalysis.d.ts +64 -0
  1424. package/dist/services/analysisTemplates/fourQuadrantAnalysis.d.ts.map +1 -0
  1425. package/dist/services/analysisTemplates/fourQuadrantAnalysis.js +288 -0
  1426. package/dist/services/analysisTemplates/fourQuadrantAnalysis.js.map +1 -0
  1427. package/dist/services/analysisTemplates/frameStatsAnalysis.d.ts +77 -0
  1428. package/dist/services/analysisTemplates/frameStatsAnalysis.d.ts.map +1 -0
  1429. package/dist/services/analysisTemplates/frameStatsAnalysis.js +232 -0
  1430. package/dist/services/analysisTemplates/frameStatsAnalysis.js.map +1 -0
  1431. package/dist/services/analysisTemplates/templateManager.d.ts +70 -0
  1432. package/dist/services/analysisTemplates/templateManager.d.ts.map +1 -0
  1433. package/dist/services/analysisTemplates/templateManager.js +293 -0
  1434. package/dist/services/analysisTemplates/templateManager.js.map +1 -0
  1435. package/dist/services/anonymizer.d.ts +61 -0
  1436. package/dist/services/anonymizer.d.ts.map +1 -0
  1437. package/dist/services/anonymizer.js +232 -0
  1438. package/dist/services/anonymizer.js.map +1 -0
  1439. package/dist/services/aospKnowledgeIngester.d.ts +67 -0
  1440. package/dist/services/aospKnowledgeIngester.d.ts.map +1 -0
  1441. package/dist/services/aospKnowledgeIngester.js +171 -0
  1442. package/dist/services/aospKnowledgeIngester.js.map +1 -0
  1443. package/dist/services/artifactCompression.d.ts +52 -0
  1444. package/dist/services/artifactCompression.d.ts.map +1 -0
  1445. package/dist/services/artifactCompression.js +215 -0
  1446. package/dist/services/artifactCompression.js.map +1 -0
  1447. package/dist/services/baselineDiffer.d.ts +85 -0
  1448. package/dist/services/baselineDiffer.d.ts.map +1 -0
  1449. package/dist/services/baselineDiffer.js +287 -0
  1450. package/dist/services/baselineDiffer.js.map +1 -0
  1451. package/dist/services/baselineStore.d.ts +52 -0
  1452. package/dist/services/baselineStore.d.ts.map +1 -0
  1453. package/dist/services/baselineStore.js +224 -0
  1454. package/dist/services/baselineStore.js.map +1 -0
  1455. package/dist/services/binderRootCauseChain.d.ts +38 -0
  1456. package/dist/services/binderRootCauseChain.d.ts.map +1 -0
  1457. package/dist/services/binderRootCauseChain.js +74 -0
  1458. package/dist/services/binderRootCauseChain.js.map +1 -0
  1459. package/dist/services/blogKnowledgeIngester.d.ts +89 -0
  1460. package/dist/services/blogKnowledgeIngester.d.ts.map +1 -0
  1461. package/dist/services/blogKnowledgeIngester.js +192 -0
  1462. package/dist/services/blogKnowledgeIngester.js.map +1 -0
  1463. package/dist/services/caseGraph.d.ts +55 -0
  1464. package/dist/services/caseGraph.d.ts.map +1 -0
  1465. package/dist/services/caseGraph.js +260 -0
  1466. package/dist/services/caseGraph.js.map +1 -0
  1467. package/dist/services/caseLibrary.d.ts +61 -0
  1468. package/dist/services/caseLibrary.d.ts.map +1 -0
  1469. package/dist/services/caseLibrary.js +269 -0
  1470. package/dist/services/caseLibrary.js.map +1 -0
  1471. package/dist/services/ciGateRunStore.d.ts +39 -0
  1472. package/dist/services/ciGateRunStore.d.ts.map +1 -0
  1473. package/dist/services/ciGateRunStore.js +208 -0
  1474. package/dist/services/ciGateRunStore.js.map +1 -0
  1475. package/dist/services/comparisonAiConclusionService.d.ts +23 -0
  1476. package/dist/services/comparisonAiConclusionService.d.ts.map +1 -0
  1477. package/dist/services/comparisonAiConclusionService.js +207 -0
  1478. package/dist/services/comparisonAiConclusionService.js.map +1 -0
  1479. package/dist/services/comparisonAppendixService.d.ts +50 -0
  1480. package/dist/services/comparisonAppendixService.d.ts.map +1 -0
  1481. package/dist/services/comparisonAppendixService.js +276 -0
  1482. package/dist/services/comparisonAppendixService.js.map +1 -0
  1483. package/dist/services/comparisonHtmlReportService.d.ts +20 -0
  1484. package/dist/services/comparisonHtmlReportService.d.ts.map +1 -0
  1485. package/dist/services/comparisonHtmlReportService.js +214 -0
  1486. package/dist/services/comparisonHtmlReportService.js.map +1 -0
  1487. package/dist/services/comparisonMatrixService.d.ts +7 -0
  1488. package/dist/services/comparisonMatrixService.d.ts.map +1 -0
  1489. package/dist/services/comparisonMatrixService.js +211 -0
  1490. package/dist/services/comparisonMatrixService.js.map +1 -0
  1491. package/dist/services/comparisonResultService.d.ts +13 -0
  1492. package/dist/services/comparisonResultService.d.ts.map +1 -0
  1493. package/dist/services/comparisonResultService.js +99 -0
  1494. package/dist/services/comparisonResultService.js.map +1 -0
  1495. package/dist/services/comparisonSignificance.d.ts +3 -0
  1496. package/dist/services/comparisonSignificance.d.ts.map +1 -0
  1497. package/dist/services/comparisonSignificance.js +42 -0
  1498. package/dist/services/comparisonSignificance.js.map +1 -0
  1499. package/dist/services/cpuThermalPmu.d.ts +38 -0
  1500. package/dist/services/cpuThermalPmu.d.ts.map +1 -0
  1501. package/dist/services/cpuThermalPmu.js +141 -0
  1502. package/dist/services/cpuThermalPmu.js.map +1 -0
  1503. package/dist/services/criticalPathAiSummary.d.ts +29 -0
  1504. package/dist/services/criticalPathAiSummary.d.ts.map +1 -0
  1505. package/dist/services/criticalPathAiSummary.js +310 -0
  1506. package/dist/services/criticalPathAiSummary.js.map +1 -0
  1507. package/dist/services/criticalPathAnalyzer.d.ts +108 -0
  1508. package/dist/services/criticalPathAnalyzer.d.ts.map +1 -0
  1509. package/dist/services/criticalPathAnalyzer.js +880 -0
  1510. package/dist/services/criticalPathAnalyzer.js.map +1 -0
  1511. package/dist/services/criticalPathQuantify.d.ts +70 -0
  1512. package/dist/services/criticalPathQuantify.d.ts.map +1 -0
  1513. package/dist/services/criticalPathQuantify.js +214 -0
  1514. package/dist/services/criticalPathQuantify.js.map +1 -0
  1515. package/dist/services/criticalPathSemantics.d.ts +95 -0
  1516. package/dist/services/criticalPathSemantics.d.ts.map +1 -0
  1517. package/dist/services/criticalPathSemantics.js +453 -0
  1518. package/dist/services/criticalPathSemantics.js.map +1 -0
  1519. package/dist/services/criticalPathWakerChain.d.ts +38 -0
  1520. package/dist/services/criticalPathWakerChain.d.ts.map +1 -0
  1521. package/dist/services/criticalPathWakerChain.js +144 -0
  1522. package/dist/services/criticalPathWakerChain.js.map +1 -0
  1523. package/dist/services/domainSkillEvalHarness.d.ts +51 -0
  1524. package/dist/services/domainSkillEvalHarness.d.ts.map +1 -0
  1525. package/dist/services/domainSkillEvalHarness.js +141 -0
  1526. package/dist/services/domainSkillEvalHarness.js.map +1 -0
  1527. package/dist/services/enhancedAIService.d.ts +81 -0
  1528. package/dist/services/enhancedAIService.d.ts.map +1 -0
  1529. package/dist/services/enhancedAIService.js +277 -0
  1530. package/dist/services/enhancedAIService.js.map +1 -0
  1531. package/dist/services/enterpriseAdminControlPlaneService.d.ts +124 -0
  1532. package/dist/services/enterpriseAdminControlPlaneService.d.ts.map +1 -0
  1533. package/dist/services/enterpriseAdminControlPlaneService.js +323 -0
  1534. package/dist/services/enterpriseAdminControlPlaneService.js.map +1 -0
  1535. package/dist/services/enterpriseApiKeyService.d.ts +56 -0
  1536. package/dist/services/enterpriseApiKeyService.d.ts.map +1 -0
  1537. package/dist/services/enterpriseApiKeyService.js +260 -0
  1538. package/dist/services/enterpriseApiKeyService.js.map +1 -0
  1539. package/dist/services/enterpriseAuditService.d.ts +30 -0
  1540. package/dist/services/enterpriseAuditService.d.ts.map +1 -0
  1541. package/dist/services/enterpriseAuditService.js +73 -0
  1542. package/dist/services/enterpriseAuditService.js.map +1 -0
  1543. package/dist/services/enterpriseDb.d.ts +5 -0
  1544. package/dist/services/enterpriseDb.d.ts.map +1 -0
  1545. package/dist/services/enterpriseDb.js +33 -0
  1546. package/dist/services/enterpriseDb.js.map +1 -0
  1547. package/dist/services/enterpriseMigration.d.ts +89 -0
  1548. package/dist/services/enterpriseMigration.d.ts.map +1 -0
  1549. package/dist/services/enterpriseMigration.js +506 -0
  1550. package/dist/services/enterpriseMigration.js.map +1 -0
  1551. package/dist/services/enterpriseOidcClient.d.ts +36 -0
  1552. package/dist/services/enterpriseOidcClient.d.ts.map +1 -0
  1553. package/dist/services/enterpriseOidcClient.js +124 -0
  1554. package/dist/services/enterpriseOidcClient.js.map +1 -0
  1555. package/dist/services/enterpriseQuotaPolicyService.d.ts +37 -0
  1556. package/dist/services/enterpriseQuotaPolicyService.d.ts.map +1 -0
  1557. package/dist/services/enterpriseQuotaPolicyService.js +198 -0
  1558. package/dist/services/enterpriseQuotaPolicyService.js.map +1 -0
  1559. package/dist/services/enterpriseRepository.d.ts +36 -0
  1560. package/dist/services/enterpriseRepository.d.ts.map +1 -0
  1561. package/dist/services/enterpriseRepository.js +208 -0
  1562. package/dist/services/enterpriseRepository.js.map +1 -0
  1563. package/dist/services/enterpriseRuntimeDashboardService.d.ts +114 -0
  1564. package/dist/services/enterpriseRuntimeDashboardService.d.ts.map +1 -0
  1565. package/dist/services/enterpriseRuntimeDashboardService.js +205 -0
  1566. package/dist/services/enterpriseRuntimeDashboardService.js.map +1 -0
  1567. package/dist/services/enterpriseSchema.d.ts +7 -0
  1568. package/dist/services/enterpriseSchema.d.ts.map +1 -0
  1569. package/dist/services/enterpriseSchema.js +688 -0
  1570. package/dist/services/enterpriseSchema.js.map +1 -0
  1571. package/dist/services/enterpriseSsoService.d.ts +99 -0
  1572. package/dist/services/enterpriseSsoService.d.ts.map +1 -0
  1573. package/dist/services/enterpriseSsoService.js +538 -0
  1574. package/dist/services/enterpriseSsoService.js.map +1 -0
  1575. package/dist/services/enterpriseTenantExportService.d.ts +58 -0
  1576. package/dist/services/enterpriseTenantExportService.d.ts.map +1 -0
  1577. package/dist/services/enterpriseTenantExportService.js +339 -0
  1578. package/dist/services/enterpriseTenantExportService.js.map +1 -0
  1579. package/dist/services/enterpriseTenantLifecycleService.d.ts +52 -0
  1580. package/dist/services/enterpriseTenantLifecycleService.d.ts.map +1 -0
  1581. package/dist/services/enterpriseTenantLifecycleService.js +323 -0
  1582. package/dist/services/enterpriseTenantLifecycleService.js.map +1 -0
  1583. package/dist/services/flamegraphAiSummary.d.ts +4 -0
  1584. package/dist/services/flamegraphAiSummary.d.ts.map +1 -0
  1585. package/dist/services/flamegraphAiSummary.js +172 -0
  1586. package/dist/services/flamegraphAiSummary.js.map +1 -0
  1587. package/dist/services/flamegraphAnalyzer.d.ts +14 -0
  1588. package/dist/services/flamegraphAnalyzer.d.ts.map +1 -0
  1589. package/dist/services/flamegraphAnalyzer.js +607 -0
  1590. package/dist/services/flamegraphAnalyzer.js.map +1 -0
  1591. package/dist/services/flamegraphTypes.d.ts +106 -0
  1592. package/dist/services/flamegraphTypes.d.ts.map +1 -0
  1593. package/dist/services/flamegraphTypes.js +6 -0
  1594. package/dist/services/flamegraphTypes.js.map +1 -0
  1595. package/dist/services/gpuSurfaceFlinger.d.ts +27 -0
  1596. package/dist/services/gpuSurfaceFlinger.d.ts.map +1 -0
  1597. package/dist/services/gpuSurfaceFlinger.js +68 -0
  1598. package/dist/services/gpuSurfaceFlinger.js.map +1 -0
  1599. package/dist/services/htmlReportGenerator.d.ts +425 -0
  1600. package/dist/services/htmlReportGenerator.d.ts.map +1 -0
  1601. package/dist/services/htmlReportGenerator.js +5110 -0
  1602. package/dist/services/htmlReportGenerator.js.map +1 -0
  1603. package/dist/services/ioNetworkWakeup.d.ts +27 -0
  1604. package/dist/services/ioNetworkWakeup.d.ts.map +1 -0
  1605. package/dist/services/ioNetworkWakeup.js +68 -0
  1606. package/dist/services/ioNetworkWakeup.js.map +1 -0
  1607. package/dist/services/jankDecisionTree.d.ts +39 -0
  1608. package/dist/services/jankDecisionTree.d.ts.map +1 -0
  1609. package/dist/services/jankDecisionTree.js +230 -0
  1610. package/dist/services/jankDecisionTree.js.map +1 -0
  1611. package/dist/services/legacyApiTelemetry.d.ts +28 -0
  1612. package/dist/services/legacyApiTelemetry.d.ts.map +1 -0
  1613. package/dist/services/legacyApiTelemetry.js +157 -0
  1614. package/dist/services/legacyApiTelemetry.js.map +1 -0
  1615. package/dist/services/memoryRootCause.d.ts +24 -0
  1616. package/dist/services/memoryRootCause.d.ts.map +1 -0
  1617. package/dist/services/memoryRootCause.js +70 -0
  1618. package/dist/services/memoryRootCause.js.map +1 -0
  1619. package/dist/services/multiTraceComparisonStore.d.ts +28 -0
  1620. package/dist/services/multiTraceComparisonStore.d.ts.map +1 -0
  1621. package/dist/services/multiTraceComparisonStore.js +220 -0
  1622. package/dist/services/multiTraceComparisonStore.js.map +1 -0
  1623. package/dist/services/oemSdkKnowledgeIngester.d.ts +62 -0
  1624. package/dist/services/oemSdkKnowledgeIngester.d.ts.map +1 -0
  1625. package/dist/services/oemSdkKnowledgeIngester.js +154 -0
  1626. package/dist/services/oemSdkKnowledgeIngester.js.map +1 -0
  1627. package/dist/services/perfettoLocalService.d.ts +25 -0
  1628. package/dist/services/perfettoLocalService.d.ts.map +1 -0
  1629. package/dist/services/perfettoLocalService.js +213 -0
  1630. package/dist/services/perfettoLocalService.js.map +1 -0
  1631. package/dist/services/perfettoService.d.ts +39 -0
  1632. package/dist/services/perfettoService.d.ts.map +1 -0
  1633. package/dist/services/perfettoService.js +330 -0
  1634. package/dist/services/perfettoService.js.map +1 -0
  1635. package/dist/services/perfettoSqlDocs.d.ts +94 -0
  1636. package/dist/services/perfettoSqlDocs.d.ts.map +1 -0
  1637. package/dist/services/perfettoSqlDocs.js +222 -0
  1638. package/dist/services/perfettoSqlDocs.js.map +1 -0
  1639. package/dist/services/perfettoSqlSkill.d.ts +263 -0
  1640. package/dist/services/perfettoSqlSkill.d.ts.map +1 -0
  1641. package/dist/services/perfettoSqlSkill.js +3731 -0
  1642. package/dist/services/perfettoSqlSkill.js.map +1 -0
  1643. package/dist/services/perfettoStdlibScanner.d.ts +66 -0
  1644. package/dist/services/perfettoStdlibScanner.d.ts.map +1 -0
  1645. package/dist/services/perfettoStdlibScanner.js +345 -0
  1646. package/dist/services/perfettoStdlibScanner.js.map +1 -0
  1647. package/dist/services/persistAgentSession.d.ts +43 -0
  1648. package/dist/services/persistAgentSession.d.ts.map +1 -0
  1649. package/dist/services/persistAgentSession.js +146 -0
  1650. package/dist/services/persistAgentSession.js.map +1 -0
  1651. package/dist/services/pipelineDocService.d.ts +83 -0
  1652. package/dist/services/pipelineDocService.d.ts.map +1 -0
  1653. package/dist/services/pipelineDocService.js +417 -0
  1654. package/dist/services/pipelineDocService.js.map +1 -0
  1655. package/dist/services/pipelineSkillLoader.d.ts +173 -0
  1656. package/dist/services/pipelineSkillLoader.d.ts.map +1 -0
  1657. package/dist/services/pipelineSkillLoader.js +301 -0
  1658. package/dist/services/pipelineSkillLoader.js.map +1 -0
  1659. package/dist/services/portPool.d.ts +85 -0
  1660. package/dist/services/portPool.d.ts.map +1 -0
  1661. package/dist/services/portPool.js +221 -0
  1662. package/dist/services/portPool.js.map +1 -0
  1663. package/dist/services/processIdentity/identityGate.d.ts +27 -0
  1664. package/dist/services/processIdentity/identityGate.d.ts.map +1 -0
  1665. package/dist/services/processIdentity/identityGate.js +284 -0
  1666. package/dist/services/processIdentity/identityGate.js.map +1 -0
  1667. package/dist/services/processIdentity/types.d.ts +49 -0
  1668. package/dist/services/processIdentity/types.d.ts.map +1 -0
  1669. package/dist/services/processIdentity/types.js +16 -0
  1670. package/dist/services/processIdentity/types.js.map +1 -0
  1671. package/dist/services/processRss.d.ts +10 -0
  1672. package/dist/services/processRss.d.ts.map +1 -0
  1673. package/dist/services/processRss.js +78 -0
  1674. package/dist/services/processRss.js.map +1 -0
  1675. package/dist/services/promptTemplateService.d.ts +68 -0
  1676. package/dist/services/promptTemplateService.d.ts.map +1 -0
  1677. package/dist/services/promptTemplateService.js +196 -0
  1678. package/dist/services/promptTemplateService.js.map +1 -0
  1679. package/dist/services/providerManager/connectionTester.d.ts +3 -0
  1680. package/dist/services/providerManager/connectionTester.d.ts.map +1 -0
  1681. package/dist/services/providerManager/connectionTester.js +479 -0
  1682. package/dist/services/providerManager/connectionTester.js.map +1 -0
  1683. package/dist/services/providerManager/envIsolation.d.ts +3 -0
  1684. package/dist/services/providerManager/envIsolation.d.ts.map +1 -0
  1685. package/dist/services/providerManager/envIsolation.js +31 -0
  1686. package/dist/services/providerManager/envIsolation.js.map +1 -0
  1687. package/dist/services/providerManager/index.d.ts +9 -0
  1688. package/dist/services/providerManager/index.d.ts.map +1 -0
  1689. package/dist/services/providerManager/index.js +40 -0
  1690. package/dist/services/providerManager/index.js.map +1 -0
  1691. package/dist/services/providerManager/localSecretStore.d.ts +32 -0
  1692. package/dist/services/providerManager/localSecretStore.d.ts.map +1 -0
  1693. package/dist/services/providerManager/localSecretStore.js +338 -0
  1694. package/dist/services/providerManager/localSecretStore.js.map +1 -0
  1695. package/dist/services/providerManager/providerService.d.ts +31 -0
  1696. package/dist/services/providerManager/providerService.d.ts.map +1 -0
  1697. package/dist/services/providerManager/providerService.js +460 -0
  1698. package/dist/services/providerManager/providerService.js.map +1 -0
  1699. package/dist/services/providerManager/providerSnapshot.d.ts +30 -0
  1700. package/dist/services/providerManager/providerSnapshot.d.ts.map +1 -0
  1701. package/dist/services/providerManager/providerSnapshot.js +224 -0
  1702. package/dist/services/providerManager/providerSnapshot.js.map +1 -0
  1703. package/dist/services/providerManager/providerStore.d.ts +31 -0
  1704. package/dist/services/providerManager/providerStore.d.ts.map +1 -0
  1705. package/dist/services/providerManager/providerStore.js +553 -0
  1706. package/dist/services/providerManager/providerStore.js.map +1 -0
  1707. package/dist/services/providerManager/templates.d.ts +3 -0
  1708. package/dist/services/providerManager/templates.d.ts.map +1 -0
  1709. package/dist/services/providerManager/templates.js +328 -0
  1710. package/dist/services/providerManager/templates.js.map +1 -0
  1711. package/dist/services/providerManager/types.d.ts +119 -0
  1712. package/dist/services/providerManager/types.d.ts.map +1 -0
  1713. package/dist/services/providerManager/types.js +5 -0
  1714. package/dist/services/providerManager/types.js.map +1 -0
  1715. package/dist/services/ragStore.d.ts +60 -0
  1716. package/dist/services/ragStore.d.ts.map +1 -0
  1717. package/dist/services/ragStore.js +297 -0
  1718. package/dist/services/ragStore.js.map +1 -0
  1719. package/dist/services/rbac.d.ts +19 -0
  1720. package/dist/services/rbac.d.ts.map +1 -0
  1721. package/dist/services/rbac.js +153 -0
  1722. package/dist/services/rbac.js.map +1 -0
  1723. package/dist/services/renderingPipelineDetectionSkillGenerator.d.ts +3 -0
  1724. package/dist/services/renderingPipelineDetectionSkillGenerator.d.ts.map +1 -0
  1725. package/dist/services/renderingPipelineDetectionSkillGenerator.js +1120 -0
  1726. package/dist/services/renderingPipelineDetectionSkillGenerator.js.map +1 -0
  1727. package/dist/services/renderingPipelineTeachingService.d.ts +33 -0
  1728. package/dist/services/renderingPipelineTeachingService.d.ts.map +1 -0
  1729. package/dist/services/renderingPipelineTeachingService.js +1312 -0
  1730. package/dist/services/renderingPipelineTeachingService.js.map +1 -0
  1731. package/dist/services/reportCausalMapAssets.d.ts +3 -0
  1732. package/dist/services/reportCausalMapAssets.d.ts.map +1 -0
  1733. package/dist/services/reportCausalMapAssets.js +898 -0
  1734. package/dist/services/reportCausalMapAssets.js.map +1 -0
  1735. package/dist/services/reportGenerator.d.ts +54 -0
  1736. package/dist/services/reportGenerator.d.ts.map +1 -0
  1737. package/dist/services/reportGenerator.js +241 -0
  1738. package/dist/services/reportGenerator.js.map +1 -0
  1739. package/dist/services/resourceOwnership.d.ts +21 -0
  1740. package/dist/services/resourceOwnership.d.ts.map +1 -0
  1741. package/dist/services/resourceOwnership.js +50 -0
  1742. package/dist/services/resourceOwnership.js.map +1 -0
  1743. package/dist/services/resultExportService.d.ts +66 -0
  1744. package/dist/services/resultExportService.d.ts.map +1 -0
  1745. package/dist/services/resultExportService.js +170 -0
  1746. package/dist/services/resultExportService.js.map +1 -0
  1747. package/dist/services/runtimeSnapshotStore.d.ts +19 -0
  1748. package/dist/services/runtimeSnapshotStore.d.ts.map +1 -0
  1749. package/dist/services/runtimeSnapshotStore.js +222 -0
  1750. package/dist/services/runtimeSnapshotStore.js.map +1 -0
  1751. package/dist/services/sceneReport/sceneReportMemoryCache.d.ts +38 -0
  1752. package/dist/services/sceneReport/sceneReportMemoryCache.d.ts.map +1 -0
  1753. package/dist/services/sceneReport/sceneReportMemoryCache.js +55 -0
  1754. package/dist/services/sceneReport/sceneReportMemoryCache.js.map +1 -0
  1755. package/dist/services/sceneReport/sceneReportStore.d.ts +41 -0
  1756. package/dist/services/sceneReport/sceneReportStore.d.ts.map +1 -0
  1757. package/dist/services/sceneReport/sceneReportStore.js +248 -0
  1758. package/dist/services/sceneReport/sceneReportStore.js.map +1 -0
  1759. package/dist/services/scopedKnowledgeStore.d.ts +45 -0
  1760. package/dist/services/scopedKnowledgeStore.d.ts.map +1 -0
  1761. package/dist/services/scopedKnowledgeStore.js +225 -0
  1762. package/dist/services/scopedKnowledgeStore.js.map +1 -0
  1763. package/dist/services/sessionLogger.d.ts +142 -0
  1764. package/dist/services/sessionLogger.d.ts.map +1 -0
  1765. package/dist/services/sessionLogger.js +566 -0
  1766. package/dist/services/sessionLogger.js.map +1 -0
  1767. package/dist/services/sessionPersistenceService.d.ts +190 -0
  1768. package/dist/services/sessionPersistenceService.d.ts.map +1 -0
  1769. package/dist/services/sessionPersistenceService.js +737 -0
  1770. package/dist/services/sessionPersistenceService.js.map +1 -0
  1771. package/dist/services/skillEngine/answerGenerator.d.ts +102 -0
  1772. package/dist/services/skillEngine/answerGenerator.d.ts.map +1 -0
  1773. package/dist/services/skillEngine/answerGenerator.js +508 -0
  1774. package/dist/services/skillEngine/answerGenerator.js.map +1 -0
  1775. package/dist/services/skillEngine/displayContractValidator.d.ts +26 -0
  1776. package/dist/services/skillEngine/displayContractValidator.d.ts.map +1 -0
  1777. package/dist/services/skillEngine/displayContractValidator.js +232 -0
  1778. package/dist/services/skillEngine/displayContractValidator.js.map +1 -0
  1779. package/dist/services/skillEngine/eventCollector.d.ts +96 -0
  1780. package/dist/services/skillEngine/eventCollector.d.ts.map +1 -0
  1781. package/dist/services/skillEngine/eventCollector.js +226 -0
  1782. package/dist/services/skillEngine/eventCollector.js.map +1 -0
  1783. package/dist/services/skillEngine/expressionUtils.d.ts +25 -0
  1784. package/dist/services/skillEngine/expressionUtils.d.ts.map +1 -0
  1785. package/dist/services/skillEngine/expressionUtils.js +66 -0
  1786. package/dist/services/skillEngine/expressionUtils.js.map +1 -0
  1787. package/dist/services/skillEngine/index.d.ts +25 -0
  1788. package/dist/services/skillEngine/index.d.ts.map +1 -0
  1789. package/dist/services/skillEngine/index.js +98 -0
  1790. package/dist/services/skillEngine/index.js.map +1 -0
  1791. package/dist/services/skillEngine/skillAnalysisAdapter.d.ts +149 -0
  1792. package/dist/services/skillEngine/skillAnalysisAdapter.d.ts.map +1 -0
  1793. package/dist/services/skillEngine/skillAnalysisAdapter.js +752 -0
  1794. package/dist/services/skillEngine/skillAnalysisAdapter.js.map +1 -0
  1795. package/dist/services/skillEngine/skillExecutor.d.ts +371 -0
  1796. package/dist/services/skillEngine/skillExecutor.d.ts.map +1 -0
  1797. package/dist/services/skillEngine/skillExecutor.js +4129 -0
  1798. package/dist/services/skillEngine/skillExecutor.js.map +1 -0
  1799. package/dist/services/skillEngine/skillLoader.d.ts +163 -0
  1800. package/dist/services/skillEngine/skillLoader.d.ts.map +1 -0
  1801. package/dist/services/skillEngine/skillLoader.js +840 -0
  1802. package/dist/services/skillEngine/skillLoader.js.map +1 -0
  1803. package/dist/services/skillEngine/skillValidator.d.ts +53 -0
  1804. package/dist/services/skillEngine/skillValidator.d.ts.map +1 -0
  1805. package/dist/services/skillEngine/skillValidator.js +274 -0
  1806. package/dist/services/skillEngine/skillValidator.js.map +1 -0
  1807. package/dist/services/skillEngine/smartSummaryGenerator.d.ts +70 -0
  1808. package/dist/services/skillEngine/smartSummaryGenerator.d.ts.map +1 -0
  1809. package/dist/services/skillEngine/smartSummaryGenerator.js +324 -0
  1810. package/dist/services/skillEngine/smartSummaryGenerator.js.map +1 -0
  1811. package/dist/services/skillEngine/types.d.ts +584 -0
  1812. package/dist/services/skillEngine/types.d.ts.map +1 -0
  1813. package/dist/services/skillEngine/types.js +6 -0
  1814. package/dist/services/skillEngine/types.js.map +1 -0
  1815. package/dist/services/smartperfettoSqlPackage.d.ts +11 -0
  1816. package/dist/services/smartperfettoSqlPackage.d.ts.map +1 -0
  1817. package/dist/services/smartperfettoSqlPackage.js +168 -0
  1818. package/dist/services/smartperfettoSqlPackage.js.map +1 -0
  1819. package/dist/services/sqlGuardrailAnalyzer.d.ts +24 -0
  1820. package/dist/services/sqlGuardrailAnalyzer.d.ts.map +1 -0
  1821. package/dist/services/sqlGuardrailAnalyzer.js +362 -0
  1822. package/dist/services/sqlGuardrailAnalyzer.js.map +1 -0
  1823. package/dist/services/sqlKnowledgeBase.d.ts +236 -0
  1824. package/dist/services/sqlKnowledgeBase.d.ts.map +1 -0
  1825. package/dist/services/sqlKnowledgeBase.js +1109 -0
  1826. package/dist/services/sqlKnowledgeBase.js.map +1 -0
  1827. package/dist/services/sqlStdlibDependencyAnalyzer.d.ts +26 -0
  1828. package/dist/services/sqlStdlibDependencyAnalyzer.d.ts.map +1 -0
  1829. package/dist/services/sqlStdlibDependencyAnalyzer.js +486 -0
  1830. package/dist/services/sqlStdlibDependencyAnalyzer.js.map +1 -0
  1831. package/dist/services/sqlTemplateEngine.d.ts +134 -0
  1832. package/dist/services/sqlTemplateEngine.d.ts.map +1 -0
  1833. package/dist/services/sqlTemplateEngine.js +430 -0
  1834. package/dist/services/sqlTemplateEngine.js.map +1 -0
  1835. package/dist/services/sqlValidator.d.ts +21 -0
  1836. package/dist/services/sqlValidator.d.ts.map +1 -0
  1837. package/dist/services/sqlValidator.js +175 -0
  1838. package/dist/services/sqlValidator.js.map +1 -0
  1839. package/dist/services/standardMetricBackfillService.d.ts +23 -0
  1840. package/dist/services/standardMetricBackfillService.d.ts.map +1 -0
  1841. package/dist/services/standardMetricBackfillService.js +196 -0
  1842. package/dist/services/standardMetricBackfillService.js.map +1 -0
  1843. package/dist/services/startupAnrMethodGraph.d.ts +20 -0
  1844. package/dist/services/startupAnrMethodGraph.d.ts.map +1 -0
  1845. package/dist/services/startupAnrMethodGraph.js +70 -0
  1846. package/dist/services/startupAnrMethodGraph.js.map +1 -0
  1847. package/dist/services/stdlibSkillCoverage.d.ts +23 -0
  1848. package/dist/services/stdlibSkillCoverage.d.ts.map +1 -0
  1849. package/dist/services/stdlibSkillCoverage.js +289 -0
  1850. package/dist/services/stdlibSkillCoverage.js.map +1 -0
  1851. package/dist/services/threadSchedContext.d.ts +49 -0
  1852. package/dist/services/threadSchedContext.d.ts.map +1 -0
  1853. package/dist/services/threadSchedContext.js +84 -0
  1854. package/dist/services/threadSchedContext.js.map +1 -0
  1855. package/dist/services/timelineBinning.d.ts +44 -0
  1856. package/dist/services/timelineBinning.d.ts.map +1 -0
  1857. package/dist/services/timelineBinning.js +150 -0
  1858. package/dist/services/timelineBinning.js.map +1 -0
  1859. package/dist/services/traceConfigGenerator.d.ts +36 -0
  1860. package/dist/services/traceConfigGenerator.d.ts.map +1 -0
  1861. package/dist/services/traceConfigGenerator.js +110 -0
  1862. package/dist/services/traceConfigGenerator.js.map +1 -0
  1863. package/dist/services/traceFormatDetector.d.ts +39 -0
  1864. package/dist/services/traceFormatDetector.d.ts.map +1 -0
  1865. package/dist/services/traceFormatDetector.js +287 -0
  1866. package/dist/services/traceFormatDetector.js.map +1 -0
  1867. package/dist/services/traceMetadataStore.d.ts +32 -0
  1868. package/dist/services/traceMetadataStore.d.ts.map +1 -0
  1869. package/dist/services/traceMetadataStore.js +375 -0
  1870. package/dist/services/traceMetadataStore.js.map +1 -0
  1871. package/dist/services/traceProcessorConnectionModel.d.ts +32 -0
  1872. package/dist/services/traceProcessorConnectionModel.d.ts.map +1 -0
  1873. package/dist/services/traceProcessorConnectionModel.js +38 -0
  1874. package/dist/services/traceProcessorConnectionModel.js.map +1 -0
  1875. package/dist/services/traceProcessorHttpRpcClient.d.ts +22 -0
  1876. package/dist/services/traceProcessorHttpRpcClient.d.ts.map +1 -0
  1877. package/dist/services/traceProcessorHttpRpcClient.js +89 -0
  1878. package/dist/services/traceProcessorHttpRpcClient.js.map +1 -0
  1879. package/dist/services/traceProcessorLeaseModeDecision.d.ts +52 -0
  1880. package/dist/services/traceProcessorLeaseModeDecision.d.ts.map +1 -0
  1881. package/dist/services/traceProcessorLeaseModeDecision.js +150 -0
  1882. package/dist/services/traceProcessorLeaseModeDecision.js.map +1 -0
  1883. package/dist/services/traceProcessorLeaseStore.d.ts +88 -0
  1884. package/dist/services/traceProcessorLeaseStore.d.ts.map +1 -0
  1885. package/dist/services/traceProcessorLeaseStore.js +463 -0
  1886. package/dist/services/traceProcessorLeaseStore.js.map +1 -0
  1887. package/dist/services/traceProcessorProtobuf.d.ts +56 -0
  1888. package/dist/services/traceProcessorProtobuf.d.ts.map +1 -0
  1889. package/dist/services/traceProcessorProtobuf.js +442 -0
  1890. package/dist/services/traceProcessorProtobuf.js.map +1 -0
  1891. package/dist/services/traceProcessorRamBudget.d.ts +55 -0
  1892. package/dist/services/traceProcessorRamBudget.d.ts.map +1 -0
  1893. package/dist/services/traceProcessorRamBudget.js +140 -0
  1894. package/dist/services/traceProcessorRamBudget.js.map +1 -0
  1895. package/dist/services/traceProcessorService.d.ts +223 -0
  1896. package/dist/services/traceProcessorService.d.ts.map +1 -0
  1897. package/dist/services/traceProcessorService.js +838 -0
  1898. package/dist/services/traceProcessorService.js.map +1 -0
  1899. package/dist/services/traceProcessorSqlWorker.d.ts +49 -0
  1900. package/dist/services/traceProcessorSqlWorker.d.ts.map +1 -0
  1901. package/dist/services/traceProcessorSqlWorker.js +218 -0
  1902. package/dist/services/traceProcessorSqlWorker.js.map +1 -0
  1903. package/dist/services/traceProcessorSqlWorkerThread.d.ts +2 -0
  1904. package/dist/services/traceProcessorSqlWorkerThread.d.ts.map +1 -0
  1905. package/dist/services/traceProcessorSqlWorkerThread.js +35 -0
  1906. package/dist/services/traceProcessorSqlWorkerThread.js.map +1 -0
  1907. package/dist/services/traceSummaryV2.d.ts +47 -0
  1908. package/dist/services/traceSummaryV2.d.ts.map +1 -0
  1909. package/dist/services/traceSummaryV2.js +241 -0
  1910. package/dist/services/traceSummaryV2.js.map +1 -0
  1911. package/dist/services/traceUploadLimit.d.ts +3 -0
  1912. package/dist/services/traceUploadLimit.d.ts.map +1 -0
  1913. package/dist/services/traceUploadLimit.js +24 -0
  1914. package/dist/services/traceUploadLimit.js.map +1 -0
  1915. package/dist/services/workingTraceProcessor.d.ts +226 -0
  1916. package/dist/services/workingTraceProcessor.d.ts.map +1 -0
  1917. package/dist/services/workingTraceProcessor.js +1093 -0
  1918. package/dist/services/workingTraceProcessor.js.map +1 -0
  1919. package/dist/trace-processor-pin.env +39 -0
  1920. package/dist/types/analysis.d.ts +511 -0
  1921. package/dist/types/analysis.d.ts.map +1 -0
  1922. package/dist/types/analysis.js +112 -0
  1923. package/dist/types/analysis.js.map +1 -0
  1924. package/dist/types/ciGateContracts.d.ts +63 -0
  1925. package/dist/types/ciGateContracts.d.ts.map +1 -0
  1926. package/dist/types/ciGateContracts.js +6 -0
  1927. package/dist/types/ciGateContracts.js.map +1 -0
  1928. package/dist/types/dataContract.d.ts +624 -0
  1929. package/dist/types/dataContract.d.ts.map +1 -0
  1930. package/dist/types/dataContract.js +775 -0
  1931. package/dist/types/dataContract.js.map +1 -0
  1932. package/dist/types/index.d.ts +40 -0
  1933. package/dist/types/index.d.ts.map +1 -0
  1934. package/dist/types/index.js +21 -0
  1935. package/dist/types/index.js.map +1 -0
  1936. package/dist/types/multiTraceComparison.d.ts +215 -0
  1937. package/dist/types/multiTraceComparison.d.ts.map +1 -0
  1938. package/dist/types/multiTraceComparison.js +33 -0
  1939. package/dist/types/multiTraceComparison.js.map +1 -0
  1940. package/dist/types/perfettoSql.d.ts +596 -0
  1941. package/dist/types/perfettoSql.d.ts.map +1 -0
  1942. package/dist/types/perfettoSql.js +28 -0
  1943. package/dist/types/perfettoSql.js.map +1 -0
  1944. package/dist/types/sparkContracts.d.ts +1642 -0
  1945. package/dist/types/sparkContracts.d.ts.map +1 -0
  1946. package/dist/types/sparkContracts.js +25 -0
  1947. package/dist/types/sparkContracts.js.map +1 -0
  1948. package/dist/types/teaching.types.d.ts +395 -0
  1949. package/dist/types/teaching.types.d.ts.map +1 -0
  1950. package/dist/types/teaching.types.js +300 -0
  1951. package/dist/types/teaching.types.js.map +1 -0
  1952. package/dist/utils/analysisNarrative.d.ts +24 -0
  1953. package/dist/utils/analysisNarrative.d.ts.map +1 -0
  1954. package/dist/utils/analysisNarrative.js +101 -0
  1955. package/dist/utils/analysisNarrative.js.map +1 -0
  1956. package/dist/utils/atomicFileWriter.d.ts +5 -0
  1957. package/dist/utils/atomicFileWriter.d.ts.map +1 -0
  1958. package/dist/utils/atomicFileWriter.js +90 -0
  1959. package/dist/utils/atomicFileWriter.js.map +1 -0
  1960. package/dist/utils/epipeGuard.d.ts +10 -0
  1961. package/dist/utils/epipeGuard.d.ts.map +1 -0
  1962. package/dist/utils/epipeGuard.js +40 -0
  1963. package/dist/utils/epipeGuard.js.map +1 -0
  1964. package/dist/utils/httpValue.d.ts +2 -0
  1965. package/dist/utils/httpValue.d.ts.map +1 -0
  1966. package/dist/utils/httpValue.js +24 -0
  1967. package/dist/utils/httpValue.js.map +1 -0
  1968. package/dist/utils/llmJson.d.ts +33 -0
  1969. package/dist/utils/llmJson.d.ts.map +1 -0
  1970. package/dist/utils/llmJson.js +148 -0
  1971. package/dist/utils/llmJson.js.map +1 -0
  1972. package/dist/utils/llmPrivacy.d.ts +15 -0
  1973. package/dist/utils/llmPrivacy.d.ts.map +1 -0
  1974. package/dist/utils/llmPrivacy.js +126 -0
  1975. package/dist/utils/llmPrivacy.js.map +1 -0
  1976. package/dist/utils/logger.d.ts +24 -0
  1977. package/dist/utils/logger.d.ts.map +1 -0
  1978. package/dist/utils/logger.js +68 -0
  1979. package/dist/utils/logger.js.map +1 -0
  1980. package/dist/utils/traceProcessorRowUtils.d.ts +11 -0
  1981. package/dist/utils/traceProcessorRowUtils.d.ts.map +1 -0
  1982. package/dist/utils/traceProcessorRowUtils.js +64 -0
  1983. package/dist/utils/traceProcessorRowUtils.js.map +1 -0
  1984. package/dist/utils/uuid.d.ts +3 -0
  1985. package/dist/utils/uuid.d.ts.map +1 -0
  1986. package/dist/utils/uuid.js +7 -0
  1987. package/dist/utils/uuid.js.map +1 -0
  1988. package/dist/version.d.ts +2 -0
  1989. package/dist/version.d.ts.map +1 -0
  1990. package/dist/version.js +53 -0
  1991. package/dist/version.js.map +1 -0
  1992. package/package.json +128 -0
  1993. package/prebuilts/trace_processor/README.md +20 -0
  1994. package/prebuilts/trace_processor/darwin-arm64/trace_processor_shell +0 -0
  1995. package/prebuilts/trace_processor/linux-x64/trace_processor_shell +0 -0
  1996. package/prebuilts/trace_processor/win32-x64/trace_processor_shell.exe +0 -0
  1997. package/skills/README.md +686 -0
  1998. package/skills/_template/README.md +43 -0
  1999. package/skills/_template/atomic_A_template.skill.yaml +79 -0
  2000. package/skills/_template/atomic_B_template.skill.yaml +61 -0
  2001. package/skills/_template/atomic_S_template.skill.yaml +92 -0
  2002. package/skills/_template/composite_S_template.skill.yaml +198 -0
  2003. package/skills/_template/vendor_override_template.yaml +72 -0
  2004. package/skills/atomic/android_bitmap_memory_per_process.skill.yaml +203 -0
  2005. package/skills/atomic/android_dvfs_counter_stats.skill.yaml +60 -0
  2006. package/skills/atomic/android_gpu_work_period_track.skill.yaml +55 -0
  2007. package/skills/atomic/android_heap_graph_summary.skill.yaml +232 -0
  2008. package/skills/atomic/android_job_scheduler_events.skill.yaml +58 -0
  2009. package/skills/atomic/android_kernel_wakelock_summary.skill.yaml +57 -0
  2010. package/skills/atomic/anr_context_in_range.skill.yaml +99 -0
  2011. package/skills/atomic/anr_main_thread_blocking.skill.yaml +513 -0
  2012. package/skills/atomic/app_frame_production.skill.yaml +147 -0
  2013. package/skills/atomic/app_lifecycle_in_range.skill.yaml +142 -0
  2014. package/skills/atomic/app_process_starts_summary.skill.yaml +75 -0
  2015. package/skills/atomic/battery_charge_timeline.skill.yaml +72 -0
  2016. package/skills/atomic/battery_doze_state_timeline.skill.yaml +83 -0
  2017. package/skills/atomic/binder_blocking_in_range.skill.yaml +99 -0
  2018. package/skills/atomic/binder_in_range.skill.yaml +86 -0
  2019. package/skills/atomic/binder_root_cause.skill.yaml +191 -0
  2020. package/skills/atomic/binder_storm_detection.skill.yaml +394 -0
  2021. package/skills/atomic/blocking_chain_analysis.skill.yaml +316 -0
  2022. package/skills/atomic/buffer_transaction_lifecycle.skill.yaml +256 -0
  2023. package/skills/atomic/cache_miss_impact.skill.yaml +115 -0
  2024. package/skills/atomic/chrome_scroll_jank_frame_timeline.skill.yaml +337 -0
  2025. package/skills/atomic/compose_recomposition_hotspot.skill.yaml +403 -0
  2026. package/skills/atomic/consumer_jank_detection.skill.yaml +556 -0
  2027. package/skills/atomic/cpu_cluster_load_in_range.skill.yaml +138 -0
  2028. package/skills/atomic/cpu_cluster_mapping_view.skill.yaml +47 -0
  2029. package/skills/atomic/cpu_freq_timeline.skill.yaml +143 -0
  2030. package/skills/atomic/cpu_idle_analysis.skill.yaml +101 -0
  2031. package/skills/atomic/cpu_idle_state_residency.skill.yaml +54 -0
  2032. package/skills/atomic/cpu_load_in_range.skill.yaml +145 -0
  2033. package/skills/atomic/cpu_process_utilization_period.skill.yaml +51 -0
  2034. package/skills/atomic/cpu_slice_analysis.skill.yaml +118 -0
  2035. package/skills/atomic/cpu_thread_utilization_period.skill.yaml +68 -0
  2036. package/skills/atomic/cpu_throttling_in_range.skill.yaml +131 -0
  2037. package/skills/atomic/cpu_time_per_frame.skill.yaml +59 -0
  2038. package/skills/atomic/cpu_topology_detection.skill.yaml +233 -0
  2039. package/skills/atomic/cpu_topology_view.skill.yaml +272 -0
  2040. package/skills/atomic/cpu_utilization_per_period.skill.yaml +55 -0
  2041. package/skills/atomic/device_state_snapshot.skill.yaml +171 -0
  2042. package/skills/atomic/device_state_timeline.skill.yaml +308 -0
  2043. package/skills/atomic/fence_wait_decomposition.skill.yaml +314 -0
  2044. package/skills/atomic/fpsgo_analysis.skill.yaml +80 -0
  2045. package/skills/atomic/frame_blocking_calls.skill.yaml +215 -0
  2046. package/skills/atomic/frame_overrun_summary.skill.yaml +68 -0
  2047. package/skills/atomic/frame_pipeline_variance.skill.yaml +124 -0
  2048. package/skills/atomic/frame_production_gap.skill.yaml +337 -0
  2049. package/skills/atomic/frame_ui_time_breakdown.skill.yaml +58 -0
  2050. package/skills/atomic/futex_wait_distribution.skill.yaml +117 -0
  2051. package/skills/atomic/game_fps_analysis.skill.yaml +385 -0
  2052. package/skills/atomic/game_main_loop_jank.skill.yaml +309 -0
  2053. package/skills/atomic/gc_events_in_range.skill.yaml +118 -0
  2054. package/skills/atomic/gl_standalone_swap_jank.skill.yaml +259 -0
  2055. package/skills/atomic/gpu_freq_in_range.skill.yaml +99 -0
  2056. package/skills/atomic/gpu_frequency_analysis.skill.yaml +94 -0
  2057. package/skills/atomic/gpu_metrics.skill.yaml +411 -0
  2058. package/skills/atomic/gpu_power_state_analysis.skill.yaml +117 -0
  2059. package/skills/atomic/gpu_render_in_range.skill.yaml +104 -0
  2060. package/skills/atomic/input_events_in_range.skill.yaml +130 -0
  2061. package/skills/atomic/input_to_frame_latency.skill.yaml +436 -0
  2062. package/skills/atomic/linux_irq_summary.skill.yaml +66 -0
  2063. package/skills/atomic/linux_perf_counter_hotspots.skill.yaml +108 -0
  2064. package/skills/atomic/linux_process_rss_swap_timeline.skill.yaml +96 -0
  2065. package/skills/atomic/linux_runqueue_depth_timeline.skill.yaml +132 -0
  2066. package/skills/atomic/linux_sched_latency_distribution.skill.yaml +130 -0
  2067. package/skills/atomic/lmk_kill_attribution.skill.yaml +72 -0
  2068. package/skills/atomic/lock_contention_in_range.skill.yaml +402 -0
  2069. package/skills/atomic/logcat_analysis.skill.yaml +85 -0
  2070. package/skills/atomic/main_thread_file_io_in_range.skill.yaml +116 -0
  2071. package/skills/atomic/main_thread_sched_latency_in_range.skill.yaml +91 -0
  2072. package/skills/atomic/main_thread_slices_in_range.skill.yaml +129 -0
  2073. package/skills/atomic/main_thread_states_in_range.skill.yaml +105 -0
  2074. package/skills/atomic/mali_gpu_power_state.skill.yaml +54 -0
  2075. package/skills/atomic/media_codec_activity.skill.yaml +236 -0
  2076. package/skills/atomic/memory_growth_detector.skill.yaml +146 -0
  2077. package/skills/atomic/memory_pressure_in_range.skill.yaml +382 -0
  2078. package/skills/atomic/memory_rss_high_watermark.skill.yaml +62 -0
  2079. package/skills/atomic/native_heap_breakdown.skill.yaml +80 -0
  2080. package/skills/atomic/oom_adjuster_score_timeline.skill.yaml +77 -0
  2081. package/skills/atomic/page_fault_in_range.skill.yaml +113 -0
  2082. package/skills/atomic/pipeline_4feature_scoring.skill.yaml +299 -0
  2083. package/skills/atomic/pipeline_key_slices_overlay.skill.yaml +108 -0
  2084. package/skills/atomic/present_fence_timing.skill.yaml +156 -0
  2085. package/skills/atomic/process_identity_resolver.skill.yaml +503 -0
  2086. package/skills/atomic/render_pipeline_latency.skill.yaml +120 -0
  2087. package/skills/atomic/render_thread_slices.skill.yaml +107 -0
  2088. package/skills/atomic/rendering_pipeline_detection.skill.yaml +770 -0
  2089. package/skills/atomic/rn_bridge_to_frame_jank.skill.yaml +209 -0
  2090. package/skills/atomic/rn_fabric_render_jank.skill.yaml +213 -0
  2091. package/skills/atomic/sched_latency_in_range.skill.yaml +94 -0
  2092. package/skills/atomic/scheduling_analysis.skill.yaml +103 -0
  2093. package/skills/atomic/scroll_response_latency.skill.yaml +131 -0
  2094. package/skills/atomic/sf_composition_in_range.skill.yaml +99 -0
  2095. package/skills/atomic/sf_frame_consumption.skill.yaml +133 -0
  2096. package/skills/atomic/sf_layer_count_in_range.skill.yaml +155 -0
  2097. package/skills/atomic/startup_binder_in_range.skill.yaml +106 -0
  2098. package/skills/atomic/startup_binder_pool_analysis.skill.yaml +115 -0
  2099. package/skills/atomic/startup_breakdown_in_range.skill.yaml +115 -0
  2100. package/skills/atomic/startup_class_loading_in_range.skill.yaml +93 -0
  2101. package/skills/atomic/startup_cpu_placement_timeline.skill.yaml +135 -0
  2102. package/skills/atomic/startup_critical_tasks.skill.yaml +247 -0
  2103. package/skills/atomic/startup_events_in_range.skill.yaml +251 -0
  2104. package/skills/atomic/startup_freq_rampup.skill.yaml +110 -0
  2105. package/skills/atomic/startup_gc_in_range.skill.yaml +97 -0
  2106. package/skills/atomic/startup_hot_slice_states.skill.yaml +116 -0
  2107. package/skills/atomic/startup_jit_analysis.skill.yaml +158 -0
  2108. package/skills/atomic/startup_main_thread_binder_blocking_in_range.skill.yaml +114 -0
  2109. package/skills/atomic/startup_main_thread_file_io_in_range.skill.yaml +117 -0
  2110. package/skills/atomic/startup_main_thread_slices_in_range.skill.yaml +138 -0
  2111. package/skills/atomic/startup_main_thread_states_in_range.skill.yaml +100 -0
  2112. package/skills/atomic/startup_main_thread_sync_binder_in_range.skill.yaml +103 -0
  2113. package/skills/atomic/startup_sched_latency_in_range.skill.yaml +93 -0
  2114. package/skills/atomic/startup_slow_reasons.skill.yaml +625 -0
  2115. package/skills/atomic/startup_thread_blocking_graph.skill.yaml +181 -0
  2116. package/skills/atomic/system_load_in_range.skill.yaml +95 -0
  2117. package/skills/atomic/task_migration_in_range.skill.yaml +115 -0
  2118. package/skills/atomic/textureview_producer_frame_timing.skill.yaml +302 -0
  2119. package/skills/atomic/thermal_predictor.skill.yaml +182 -0
  2120. package/skills/atomic/thread_affinity_violation.skill.yaml +139 -0
  2121. package/skills/atomic/touch_to_display_latency.skill.yaml +130 -0
  2122. package/skills/atomic/util_tracking_analysis.skill.yaml +89 -0
  2123. package/skills/atomic/vrr_detection.skill.yaml +301 -0
  2124. package/skills/atomic/vsync_alignment_in_range.skill.yaml +116 -0
  2125. package/skills/atomic/vsync_config.skill.yaml +147 -0
  2126. package/skills/atomic/vsync_period_detection.skill.yaml +178 -0
  2127. package/skills/atomic/vsync_phase_alignment.skill.yaml +255 -0
  2128. package/skills/atomic/wakelock_tracking.skill.yaml +276 -0
  2129. package/skills/atomic/wattson_app_startup_power.skill.yaml +66 -0
  2130. package/skills/atomic/wattson_rails_power_breakdown.skill.yaml +70 -0
  2131. package/skills/atomic/wattson_thread_power_attribution.skill.yaml +74 -0
  2132. package/skills/atomic/webview_v8_analysis.skill.yaml +297 -0
  2133. package/skills/comparison/multi_trace_result_comparison.skill.yaml +60 -0
  2134. package/skills/composite/anr_analysis.skill.yaml +889 -0
  2135. package/skills/composite/anr_detail.skill.yaml +796 -0
  2136. package/skills/composite/battery_drain_attribution.skill.yaml +134 -0
  2137. package/skills/composite/binder_analysis.skill.yaml +742 -0
  2138. package/skills/composite/binder_detail.skill.yaml +388 -0
  2139. package/skills/composite/block_io_analysis.skill.yaml +559 -0
  2140. package/skills/composite/click_response_analysis.skill.yaml +915 -0
  2141. package/skills/composite/click_response_detail.skill.yaml +800 -0
  2142. package/skills/composite/cpu_analysis.skill.yaml +960 -0
  2143. package/skills/composite/dmabuf_analysis.skill.yaml +622 -0
  2144. package/skills/composite/flutter_scrolling_analysis.skill.yaml +443 -0
  2145. package/skills/composite/gc_analysis.skill.yaml +744 -0
  2146. package/skills/composite/global_trace_sanity_check.skill.yaml +716 -0
  2147. package/skills/composite/gpu_analysis.skill.yaml +700 -0
  2148. package/skills/composite/io_pressure.skill.yaml +654 -0
  2149. package/skills/composite/irq_analysis.skill.yaml +696 -0
  2150. package/skills/composite/jank_frame_detail.skill.yaml +2065 -0
  2151. package/skills/composite/lmk_analysis.skill.yaml +626 -0
  2152. package/skills/composite/lock_binder_wait.skill.yaml +95 -0
  2153. package/skills/composite/lock_contention_analysis.skill.yaml +878 -0
  2154. package/skills/composite/memory_analysis.skill.yaml +718 -0
  2155. package/skills/composite/navigation_analysis.skill.yaml +901 -0
  2156. package/skills/composite/network_analysis.skill.yaml +760 -0
  2157. package/skills/composite/power_consumption_overview.skill.yaml +143 -0
  2158. package/skills/composite/scene_reconstruction.skill.yaml +2788 -0
  2159. package/skills/composite/scroll_session_analysis.skill.yaml +496 -0
  2160. package/skills/composite/scrolling_analysis.skill.yaml +3295 -0
  2161. package/skills/composite/startup_analysis.skill.yaml +1172 -0
  2162. package/skills/composite/startup_detail.skill.yaml +1339 -0
  2163. package/skills/composite/state_timeline.skill.yaml +1021 -0
  2164. package/skills/composite/surfaceflinger_analysis.skill.yaml +808 -0
  2165. package/skills/composite/suspend_wakeup_analysis.skill.yaml +698 -0
  2166. package/skills/composite/thermal_throttling.skill.yaml +964 -0
  2167. package/skills/composite/thermal_throttling_chain.skill.yaml +147 -0
  2168. package/skills/composite/webview_drawfunctor_jank_chain.skill.yaml +343 -0
  2169. package/skills/config/conclusion_scene_templates.base.yaml +181 -0
  2170. package/skills/config/conclusion_scene_templates.yaml +17 -0
  2171. package/skills/deep/callstack_analysis.skill.yaml +436 -0
  2172. package/skills/deep/cpu_profiling.skill.yaml +617 -0
  2173. package/skills/docs/scrolling.sop.md +312 -0
  2174. package/skills/docs/startup.sop.md +382 -0
  2175. package/skills/docs/upstream-perfetto-ai-skill-translation.sop.md +50 -0
  2176. package/skills/fragments/target_threads.sql +34 -0
  2177. package/skills/fragments/thread_states_quadrant.sql +26 -0
  2178. package/skills/fragments/vsync_config.sql +32 -0
  2179. package/skills/modules/app/launcher_module.skill.yaml +473 -0
  2180. package/skills/modules/app/systemui_module.skill.yaml +565 -0
  2181. package/skills/modules/app/third_party_module.skill.yaml +275 -0
  2182. package/skills/modules/framework/ams_module.skill.yaml +239 -0
  2183. package/skills/modules/framework/art_module.skill.yaml +266 -0
  2184. package/skills/modules/framework/choreographer_module.skill.yaml +419 -0
  2185. package/skills/modules/framework/input_module.skill.yaml +219 -0
  2186. package/skills/modules/framework/surfaceflinger_module.skill.yaml +343 -0
  2187. package/skills/modules/framework/wms_module.skill.yaml +356 -0
  2188. package/skills/modules/hardware/cpu_module.skill.yaml +300 -0
  2189. package/skills/modules/hardware/gpu_module.skill.yaml +229 -0
  2190. package/skills/modules/hardware/memory_module.skill.yaml +443 -0
  2191. package/skills/modules/hardware/power_module.skill.yaml +377 -0
  2192. package/skills/modules/hardware/thermal_module.skill.yaml +410 -0
  2193. package/skills/modules/kernel/binder_module.skill.yaml +223 -0
  2194. package/skills/modules/kernel/filesystem_module.skill.yaml +423 -0
  2195. package/skills/modules/kernel/lock_contention_module.skill.yaml +424 -0
  2196. package/skills/modules/kernel/scheduler_module.skill.yaml +247 -0
  2197. package/skills/pipelines/_base.skill.yaml +103 -0
  2198. package/skills/pipelines/android_pip_freeform.skill.yaml +224 -0
  2199. package/skills/pipelines/android_view_mixed.skill.yaml +305 -0
  2200. package/skills/pipelines/android_view_multi_window.skill.yaml +271 -0
  2201. package/skills/pipelines/android_view_software.skill.yaml +172 -0
  2202. package/skills/pipelines/android_view_standard_blast.skill.yaml +357 -0
  2203. package/skills/pipelines/android_view_standard_legacy.skill.yaml +233 -0
  2204. package/skills/pipelines/angle_gles_vulkan.skill.yaml +178 -0
  2205. package/skills/pipelines/camera_pipeline.skill.yaml +215 -0
  2206. package/skills/pipelines/chrome_browser_viz.skill.yaml +288 -0
  2207. package/skills/pipelines/compose_standard.skill.yaml +250 -0
  2208. package/skills/pipelines/flutter_surfaceview_impeller.skill.yaml +233 -0
  2209. package/skills/pipelines/flutter_surfaceview_skia.skill.yaml +194 -0
  2210. package/skills/pipelines/flutter_textureview.skill.yaml +219 -0
  2211. package/skills/pipelines/game_engine.skill.yaml +311 -0
  2212. package/skills/pipelines/hardware_buffer_renderer.skill.yaml +205 -0
  2213. package/skills/pipelines/imagereader_pipeline.skill.yaml +237 -0
  2214. package/skills/pipelines/index.yaml +122 -0
  2215. package/skills/pipelines/opengl_es.skill.yaml +185 -0
  2216. package/skills/pipelines/rn_new_arch.skill.yaml +126 -0
  2217. package/skills/pipelines/rn_old_arch.skill.yaml +137 -0
  2218. package/skills/pipelines/rn_skia.skill.yaml +115 -0
  2219. package/skills/pipelines/software_compositing.skill.yaml +203 -0
  2220. package/skills/pipelines/surface_control_api.skill.yaml +208 -0
  2221. package/skills/pipelines/surfaceview_blast.skill.yaml +210 -0
  2222. package/skills/pipelines/textureview_standard.skill.yaml +301 -0
  2223. package/skills/pipelines/variable_refresh_rate.skill.yaml +264 -0
  2224. package/skills/pipelines/video_overlay_hwc.skill.yaml +193 -0
  2225. package/skills/pipelines/vulkan_native.skill.yaml +215 -0
  2226. package/skills/pipelines/webview_gl_functor.skill.yaml +232 -0
  2227. package/skills/pipelines/webview_surface_control.skill.yaml +187 -0
  2228. package/skills/pipelines/webview_surfaceview_wrapper.skill.yaml +196 -0
  2229. package/skills/pipelines/webview_textureview_custom.skill.yaml +201 -0
  2230. package/skills/vendors/honor/startup.override.yaml +117 -0
  2231. package/skills/vendors/mtk/startup.override.yaml +133 -0
  2232. package/skills/vendors/oppo/startup.override.yaml +188 -0
  2233. package/skills/vendors/pixel/startup.override.yaml +163 -0
  2234. package/skills/vendors/qualcomm/startup.override.yaml +175 -0
  2235. package/skills/vendors/samsung/startup.override.yaml +161 -0
  2236. package/skills/vendors/vivo/startup.override.yaml +144 -0
  2237. package/skills/vendors/xiaomi/startup.override.yaml +120 -0
  2238. package/sql/smartperfetto/PACKAGE.json +24 -0
  2239. package/sql/smartperfetto/binder/victim_to_server.sql +36 -0
  2240. package/sql/smartperfetto/scrolling/jank_frames.sql +55 -0
  2241. package/strategies/anr.strategy.md +200 -0
  2242. package/strategies/arch-compose.template.md +10 -0
  2243. package/strategies/arch-flutter.template.md +17 -0
  2244. package/strategies/arch-standard.template.md +31 -0
  2245. package/strategies/arch-webview.template.md +9 -0
  2246. package/strategies/comparison-conclusion.template.md +36 -0
  2247. package/strategies/comparison-methodology.template.md +41 -0
  2248. package/strategies/comparison-result-methodology.template.md +35 -0
  2249. package/strategies/game.strategy.md +121 -0
  2250. package/strategies/general.strategy.md +48 -0
  2251. package/strategies/interaction.strategy.md +149 -0
  2252. package/strategies/knowledge-binder-ipc.template.md +59 -0
  2253. package/strategies/knowledge-cpu-scheduler.template.md +67 -0
  2254. package/strategies/knowledge-data-sources.template.md +738 -0
  2255. package/strategies/knowledge-gc-dynamics.template.md +65 -0
  2256. package/strategies/knowledge-harmonyos-rendering.template.md +54 -0
  2257. package/strategies/knowledge-harmonyos-tools.template.md +73 -0
  2258. package/strategies/knowledge-lock-contention.template.md +61 -0
  2259. package/strategies/knowledge-pipeline-anchors.template.md +136 -0
  2260. package/strategies/knowledge-pipeline-fences.template.md +158 -0
  2261. package/strategies/knowledge-rendering-pipeline.template.md +170 -0
  2262. package/strategies/knowledge-startup-root-causes.template.md +951 -0
  2263. package/strategies/knowledge-thermal-throttling.template.md +53 -0
  2264. package/strategies/linux.strategy.md +86 -0
  2265. package/strategies/media.strategy.md +75 -0
  2266. package/strategies/memory.strategy.md +94 -0
  2267. package/strategies/multi-trace-result-comparison.strategy.md +96 -0
  2268. package/strategies/network.strategy.md +80 -0
  2269. package/strategies/overview.strategy.md +139 -0
  2270. package/strategies/phase_hint_templates/misdiagnosis_vsync_vrr.template.yaml +37 -0
  2271. package/strategies/pipeline.strategy.md +208 -0
  2272. package/strategies/power.strategy.md +165 -0
  2273. package/strategies/prompt-complexity-classifier.template.md +26 -0
  2274. package/strategies/prompt-language-en.template.md +9 -0
  2275. package/strategies/prompt-language-zh.template.md +8 -0
  2276. package/strategies/prompt-methodology.template.md +183 -0
  2277. package/strategies/prompt-output-format.template.md +115 -0
  2278. package/strategies/prompt-quick.template.md +44 -0
  2279. package/strategies/prompt-role.template.md +13 -0
  2280. package/strategies/runtime-correctness.strategy.md +73 -0
  2281. package/strategies/scroll-response.strategy.md +236 -0
  2282. package/strategies/scrolling.strategy.md +467 -0
  2283. package/strategies/selection-area.template.md +46 -0
  2284. package/strategies/selection-slice.template.md +126 -0
  2285. package/strategies/startup.strategy.md +694 -0
  2286. package/strategies/teaching.strategy.md +176 -0
  2287. package/strategies/touch-tracking.strategy.md +213 -0
@@ -0,0 +1,3785 @@
1
+ "use strict";
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // Copyright (C) 2024-2026 Gracker (Chris)
4
+ // This file is part of SmartPerfetto. See LICENSE for details.
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.MIN_PHASE_SUMMARY_CHARS = exports.MCP_NAME_PREFIX = void 0;
40
+ exports.loadLearnedSqlFixPairs = loadLearnedSqlFixPairs;
41
+ exports.createClaudeMcpServer = createClaudeMcpServer;
42
+ const claude_agent_sdk_1 = require("@anthropic-ai/claude-agent-sdk");
43
+ const zod_1 = require("zod");
44
+ const crypto_1 = require("crypto");
45
+ const fs = __importStar(require("fs"));
46
+ const path = __importStar(require("path"));
47
+ const skillAnalysisAdapter_1 = require("../services/skillEngine/skillAnalysisAdapter");
48
+ const skillLoader_1 = require("../services/skillEngine/skillLoader");
49
+ const architectureDetector_1 = require("../agent/detectors/architectureDetector");
50
+ const dataContract_1 = require("../types/dataContract");
51
+ const types_1 = require("./types");
52
+ const sqlSummarizer_1 = require("./sqlSummarizer");
53
+ const analysisPatternMemory_1 = require("./analysisPatternMemory");
54
+ const skillNotesInjector_1 = require("./selfImprove/skillNotesInjector");
55
+ const perfettoStdlibScanner_1 = require("../services/perfettoStdlibScanner");
56
+ const perfettoSqlDocs_1 = require("../services/perfettoSqlDocs");
57
+ const traceProcessorConnectionModel_1 = require("../services/traceProcessorConnectionModel");
58
+ const identityGate_1 = require("../services/processIdentity/identityGate");
59
+ const sqlIncludeInjector_1 = require("./sqlIncludeInjector");
60
+ const rawSqlNormalizer_1 = require("./rawSqlNormalizer");
61
+ const strategyLoader_1 = require("./strategyLoader");
62
+ const phaseHintMatcher_1 = require("./phaseHintMatcher");
63
+ const activePhaseReminder_1 = require("./activePhaseReminder");
64
+ const scenePlanTemplates_1 = require("./scenePlanTemplates");
65
+ const toolCallSummary_1 = require("./toolCallSummary");
66
+ const toolNarration_1 = require("./toolNarration");
67
+ const outputLanguage_1 = require("./outputLanguage");
68
+ const ragStore_1 = require("../services/ragStore");
69
+ const baselineStore_1 = require("../services/baselineStore");
70
+ const baselineDiffer_1 = require("../services/baselineDiffer");
71
+ const projectMemory_1 = require("./projectMemory");
72
+ const caseLibrary_1 = require("../services/caseLibrary");
73
+ const scopedKnowledgeStore_1 = require("../services/scopedKnowledgeStore");
74
+ const mcpToolRegistry_1 = require("./mcpToolRegistry");
75
+ const runtimePaths_1 = require("../runtimePaths");
76
+ /**
77
+ * Process-wide RagStore singleton, lazily initialized on first MCP tool
78
+ * call. Backs the `lookup_blog_knowledge` tool (Plan 55) and will back
79
+ * the project-memory recall tool (Plan 44) when that lands.
80
+ *
81
+ * Storage path lives next to the existing analysis_*.json files so
82
+ * operators can find every long-lived agent state in one directory.
83
+ */
84
+ const RAG_STORE_PATH = (0, runtimePaths_1.backendLogPath)('rag_store.json');
85
+ let cachedRagStore = null;
86
+ function getRagStore() {
87
+ if (!cachedRagStore)
88
+ cachedRagStore = new ragStore_1.RagStore(RAG_STORE_PATH);
89
+ return cachedRagStore;
90
+ }
91
+ /** Process-wide BaselineStore singleton (Plan 50). Storage lives next
92
+ * to the other long-lived JSON files so operators have one mental
93
+ * model for agent state. */
94
+ const BASELINE_STORE_PATH = (0, runtimePaths_1.backendLogPath)('baselines.json');
95
+ let cachedBaselineStore = null;
96
+ function getBaselineStore() {
97
+ if (!cachedBaselineStore)
98
+ cachedBaselineStore = new baselineStore_1.BaselineStore(BASELINE_STORE_PATH);
99
+ return cachedBaselineStore;
100
+ }
101
+ function quoteLooseObjectKeys(value) {
102
+ let out = '';
103
+ let i = 0;
104
+ let inString = false;
105
+ let escaped = false;
106
+ while (i < value.length) {
107
+ const char = value[i];
108
+ if (inString) {
109
+ out += char;
110
+ if (escaped) {
111
+ escaped = false;
112
+ }
113
+ else if (char === '\\') {
114
+ escaped = true;
115
+ }
116
+ else if (char === '"') {
117
+ inString = false;
118
+ }
119
+ i++;
120
+ continue;
121
+ }
122
+ if (char === '"') {
123
+ inString = true;
124
+ out += char;
125
+ i++;
126
+ continue;
127
+ }
128
+ if (char === '{' || char === ',') {
129
+ out += char;
130
+ i++;
131
+ while (i < value.length && /\s/.test(value[i])) {
132
+ out += value[i++];
133
+ }
134
+ const keyStart = i;
135
+ if (/[A-Za-z_$]/.test(value[i] || '')) {
136
+ i++;
137
+ while (i < value.length && /[A-Za-z0-9_$]/.test(value[i]))
138
+ i++;
139
+ const keyEnd = i;
140
+ let hasDanglingClosingQuote = false;
141
+ if (value[i] === '"') {
142
+ let colonIndex = i + 1;
143
+ while (colonIndex < value.length && /\s/.test(value[colonIndex]))
144
+ colonIndex++;
145
+ if (value[colonIndex] === ':') {
146
+ hasDanglingClosingQuote = true;
147
+ }
148
+ }
149
+ if (hasDanglingClosingQuote) {
150
+ let colonIndex = i + 1;
151
+ while (colonIndex < value.length && /\s/.test(value[colonIndex]))
152
+ colonIndex++;
153
+ out += `"${value.slice(keyStart, keyEnd)}"`;
154
+ out += value.slice(keyEnd + 1, colonIndex + 1);
155
+ i = colonIndex + 1;
156
+ continue;
157
+ }
158
+ let colonIndex = i;
159
+ while (colonIndex < value.length && /\s/.test(value[colonIndex]))
160
+ colonIndex++;
161
+ if (value[colonIndex] === ':') {
162
+ out += `"${value.slice(keyStart, keyEnd)}"`;
163
+ out += value.slice(keyEnd, colonIndex + 1);
164
+ i = colonIndex + 1;
165
+ continue;
166
+ }
167
+ }
168
+ out += value.slice(keyStart, i);
169
+ continue;
170
+ }
171
+ out += char;
172
+ i++;
173
+ }
174
+ return out;
175
+ }
176
+ function parseToolArrayInput(value) {
177
+ if (Array.isArray(value))
178
+ return value;
179
+ if (typeof value !== 'string')
180
+ return null;
181
+ const trimmed = value.trim();
182
+ const withoutTrailingComma = trimmed.replace(/,\s*$/, '');
183
+ const candidates = [
184
+ trimmed,
185
+ withoutTrailingComma,
186
+ quoteLooseObjectKeys(trimmed),
187
+ quoteLooseObjectKeys(withoutTrailingComma),
188
+ ].filter((entry, index, all) => entry.length > 0 && all.indexOf(entry) === index);
189
+ for (const candidate of candidates) {
190
+ try {
191
+ const parsed = JSON.parse(candidate);
192
+ return Array.isArray(parsed) ? parsed : null;
193
+ }
194
+ catch {
195
+ // Try the next normalization variant.
196
+ }
197
+ }
198
+ return null;
199
+ }
200
+ function parseOptionalToolArrayInput(value) {
201
+ if (value === undefined || value === null)
202
+ return [];
203
+ if (typeof value === 'string') {
204
+ const trimmed = value.trim().toLowerCase();
205
+ if (!trimmed || trimmed === 'null' || trimmed === 'undefined')
206
+ return [];
207
+ }
208
+ return parseToolArrayInput(value);
209
+ }
210
+ function parseToolStringArrayInput(value) {
211
+ if (Array.isArray(value)) {
212
+ return value.filter((entry) => typeof entry === 'string' && entry.trim().length > 0);
213
+ }
214
+ if (typeof value !== 'string')
215
+ return [];
216
+ const trimmed = value.trim();
217
+ if (!trimmed)
218
+ return [];
219
+ const parsed = parseToolArrayInput(trimmed);
220
+ if (parsed) {
221
+ return parsed.filter((entry) => typeof entry === 'string' && entry.trim().length > 0);
222
+ }
223
+ return trimmed
224
+ .split(',')
225
+ .map(entry => entry.trim())
226
+ .filter(Boolean);
227
+ }
228
+ function coerceOptionalInteger(value, field, options) {
229
+ if (value === undefined || value === null || value === '') {
230
+ return {};
231
+ }
232
+ const numeric = typeof value === 'number'
233
+ ? value
234
+ : typeof value === 'string'
235
+ ? Number(value.trim())
236
+ : Number.NaN;
237
+ if (!Number.isInteger(numeric)) {
238
+ return { error: `${field} must be an integer` };
239
+ }
240
+ if (numeric < options.min) {
241
+ return { error: `${field} must be >= ${options.min}` };
242
+ }
243
+ if (options.max !== undefined && numeric > options.max) {
244
+ return { error: `${field} must be <= ${options.max}` };
245
+ }
246
+ return { value: numeric };
247
+ }
248
+ function normalizePlanPhaseToolInput(input) {
249
+ const expectedCalls = parseToolArrayInput(input.expectedCalls);
250
+ return {
251
+ id: input.id,
252
+ name: input.name,
253
+ goal: input.goal,
254
+ expectedTools: parseToolStringArrayInput(input.expectedTools),
255
+ ...(expectedCalls ? { expectedCalls } : {}),
256
+ };
257
+ }
258
+ function isConclusionLikePlanPhase(phase) {
259
+ const text = `${phase.id} ${phase.name} ${phase.goal}`.toLowerCase();
260
+ return /(综合结论|最终结论|结论输出|输出结论|输出最终报告|最终报告|综合报告|final conclusion|conclusion|final report|write final answer)/i
261
+ .test(text);
262
+ }
263
+ function moveConclusionPhasesLast(phases) {
264
+ const conclusionPhases = phases.filter(isConclusionLikePlanPhase);
265
+ if (conclusionPhases.length === 0)
266
+ return phases;
267
+ const nonConclusionPhases = phases.filter(phase => !isConclusionLikePlanPhase(phase));
268
+ return [...nonConclusionPhases, ...conclusionPhases];
269
+ }
270
+ const PHASE_SEMANTIC_LABELS = {
271
+ architecture: '架构检测',
272
+ overview: '概览采集',
273
+ global_context: '全局上下文',
274
+ root_drill: '根因深钻',
275
+ gap_detection: '缺帧检测',
276
+ conclusion: '综合结论',
277
+ };
278
+ const PHASE_SEMANTIC_PATTERNS = [
279
+ {
280
+ kind: 'conclusion',
281
+ pattern: /(综合结论|最终结论|结论输出|输出.*(?:结论|报告)|最终报告|优化建议|final conclusion|conclusion|final report|write final answer)/i,
282
+ },
283
+ {
284
+ kind: 'gap_detection',
285
+ pattern: /(缺帧|帧生产\s*gap|frame[_ -]?production[_ -]?gap|rt_no_drawframe|ui_no_frame|sf_backpressure|buffer stuffing 假阳性|gap 列表|gap overview)/i,
286
+ },
287
+ {
288
+ kind: 'root_drill',
289
+ pattern: /(根因深钻|根因诊断|代表帧|四象限|机制级|jank_frame_detail|blocking_chain|workload_heavy|lock_binder_wait|top slices?|主线程耗时|renderthread 耗时|root cause|drill)/i,
290
+ },
291
+ {
292
+ kind: 'global_context',
293
+ pattern: /(全局上下文|温控|thermal|视频|插帧|后台|background|干扰|系统干扰|global context)/i,
294
+ },
295
+ {
296
+ kind: 'architecture',
297
+ pattern: /(架构检测|渲染架构|textureview|surfaceview|webview|detect_architecture|architecture)/i,
298
+ },
299
+ {
300
+ kind: 'overview',
301
+ pattern: /(概览|批量根因分类|滑动性能概览|启动概览|启动事件|启动类型|数据质量|ttid|ttfd|dur\s*=|帧统计|掉帧分布|scrolling_analysis|startup_overview|overview|startup event|launch type)/i,
302
+ },
303
+ ];
304
+ function inferPhaseSemanticKinds(text) {
305
+ if (!text)
306
+ return [];
307
+ return PHASE_SEMANTIC_PATTERNS
308
+ .filter(({ pattern }) => pattern.test(text))
309
+ .map(({ kind }) => kind);
310
+ }
311
+ function findPhaseSemanticMismatch(plan, phase, summary) {
312
+ const summaryKinds = inferPhaseSemanticKinds(summary);
313
+ if (summaryKinds.length === 0)
314
+ return null;
315
+ const phaseKinds = new Set(inferPhaseSemanticKinds(`${phase.name} ${phase.goal}`));
316
+ if (phaseKinds.size === 0)
317
+ return null;
318
+ if (summaryKinds.some(kind => phaseKinds.has(kind)))
319
+ return null;
320
+ const mismatchedKind = summaryKinds.find(kind => !phaseKinds.has(kind));
321
+ if (!mismatchedKind)
322
+ return null;
323
+ const suggestedPhase = plan.phases.find(candidate => {
324
+ if (candidate.id === phase.id)
325
+ return false;
326
+ if (candidate.status === 'completed' || candidate.status === 'skipped')
327
+ return false;
328
+ return inferPhaseSemanticKinds(`${candidate.name} ${candidate.goal}`).includes(mismatchedKind);
329
+ });
330
+ return suggestedPhase ? { summaryKind: mismatchedKind, suggestedPhase } : null;
331
+ }
332
+ const TIMESTAMP_EXPRESSION_PARAM_KEYS = new Set([
333
+ 'ts',
334
+ 'start_ts',
335
+ 'end_ts',
336
+ 'frame_ts',
337
+ 'startTs',
338
+ 'endTs',
339
+ 'frameTs',
340
+ ]);
341
+ function normalizeTimestampExpression(value) {
342
+ if (typeof value !== 'string')
343
+ return value;
344
+ const trimmed = value.trim();
345
+ const match = trimmed.match(/^(\d{6,})([+-])(\d{1,15})$/);
346
+ if (!match)
347
+ return value;
348
+ try {
349
+ const left = BigInt(match[1]);
350
+ const right = BigInt(match[3]);
351
+ const result = match[2] === '+' ? left + right : left - right;
352
+ return result.toString();
353
+ }
354
+ catch {
355
+ return value;
356
+ }
357
+ }
358
+ /** Process-wide ProjectMemory singleton (Plan 44). Independent of the
359
+ * existing `analysisPatternMemory.ts` session-scope store. */
360
+ const PROJECT_MEMORY_PATH = (0, runtimePaths_1.backendLogPath)('analysis_project_memory.json');
361
+ let cachedProjectMemory = null;
362
+ function getProjectMemory() {
363
+ if (!cachedProjectMemory)
364
+ cachedProjectMemory = new projectMemory_1.ProjectMemory(PROJECT_MEMORY_PATH);
365
+ return cachedProjectMemory;
366
+ }
367
+ /** Process-wide CaseLibrary singleton (Plan 54). Storage path matches
368
+ * the other long-lived agent-state JSON files. */
369
+ const CASE_LIBRARY_PATH = (0, runtimePaths_1.backendLogPath)('case_library.json');
370
+ let cachedCaseLibrary = null;
371
+ function getCaseLibrary() {
372
+ if (!cachedCaseLibrary)
373
+ cachedCaseLibrary = new caseLibrary_1.CaseLibrary(CASE_LIBRARY_PATH);
374
+ return cachedCaseLibrary;
375
+ }
376
+ /** MCP tool name prefix — derived from the server name 'smartperfetto'.
377
+ * Re-exported from `mcpToolRegistry.ts` so consumers (claudeAgentDefinitions,
378
+ * tests) keep their existing import path. */
379
+ exports.MCP_NAME_PREFIX = mcpToolRegistry_1.MCP_NAME_PREFIX;
380
+ let sqlSchemaCache = null;
381
+ /**
382
+ * SQL structural keywords to exclude when computing Jaccard similarity
383
+ * for error-fix pair matching. Without this filter, any two Perfetto SQL
384
+ * queries match at >30% simply by sharing common keywords like SELECT/FROM/WHERE.
385
+ */
386
+ const SQL_STOP_WORDS = new Set([
387
+ // SQL structural keywords
388
+ 'select', 'from', 'where', 'and', 'or', 'not', 'in', 'is', 'as', 'on',
389
+ 'join', 'left', 'right', 'inner', 'outer', 'cross', 'full',
390
+ 'group', 'by', 'order', 'limit', 'having', 'offset',
391
+ 'with', 'case', 'when', 'then', 'else', 'end',
392
+ 'null', 'like', 'glob', 'between',
393
+ 'cast', 'count', 'sum', 'avg', 'max', 'min', 'round', 'coalesce',
394
+ 'lag', 'lead', 'over', 'partition', 'row_number', 'rank',
395
+ 'distinct', 'union', 'all', 'exists', 'into',
396
+ 'asc', 'desc', 'true', 'false', 'integer', 'text', 'real',
397
+ 'printf', 'substr', 'instr', 'replace', 'length', 'trim', 'upper', 'lower',
398
+ // Perfetto domain-structural tokens — appear in virtually all trace queries
399
+ // and inflate Jaccard similarity between unrelated queries
400
+ 'upid', 'utid', 'track_id', 'layer_name', 'jank_type', 'dur', 'name',
401
+ 'surface_frame_token', 'display_frame_token', 'frame_number',
402
+ 'process', 'thread', 'slice', 'counter', 'counter_track',
403
+ 'actual_frame_timeline_slice', 'expected_frame_timeline_slice',
404
+ ]);
405
+ /** Extract meaningful content tokens from SQL, filtering out structural keywords. */
406
+ function sqlContentTokens(sql) {
407
+ return new Set(sql.toLowerCase()
408
+ .split(/[\s,()=<>!+\-*/|;'"]+/)
409
+ .filter(t => t.length > 2 && !SQL_STOP_WORDS.has(t)));
410
+ }
411
+ const SQL_ERROR_LOG_DIR = (0, runtimePaths_1.backendLogPath)('sql_learning');
412
+ /**
413
+ * Load previously learned SQL error-fix pairs from disk.
414
+ * Returns only pairs that have a fixedSql (i.e., successfully corrected).
415
+ * Used to seed new sessions with cross-session learning.
416
+ */
417
+ /** TTL for error-fix pairs: 30 days. Older pairs may reference outdated schemas. */
418
+ const ERROR_FIX_PAIR_TTL_MS = 30 * 24 * 60 * 60 * 1000;
419
+ /**
420
+ * P0-G2: ReAct reasoning nudge — appended to successful data tool results.
421
+ * Prompts Claude to explicitly reason about observations before next action.
422
+ * Cost: ~20 tokens per data tool call, ~200-300 total per analysis.
423
+ */
424
+ const REASONING_NUDGE_ZH = '\n\n[REFLECT] 在执行下一步之前:这个数据的关键发现是什么?是否支持/反驳你的假设?如有重要推断,请用 submit_hypothesis 或 write_analysis_note 记录。';
425
+ const REASONING_NUDGE_EN = '\n\n[REFLECT] Before the next action: what is the key finding from this data? Does it support or refute your hypothesis? If there is an important inference, record it with submit_hypothesis or write_analysis_note.';
426
+ exports.MIN_PHASE_SUMMARY_CHARS = 15;
427
+ function sqlErrorLogFile(scope) {
428
+ if (!(0, scopedKnowledgeStore_1.enterpriseKnowledgeStoreEnabled)() && !scope) {
429
+ return path.join(SQL_ERROR_LOG_DIR, 'error_fix_pairs.json');
430
+ }
431
+ const resolved = (0, scopedKnowledgeStore_1.resolveKnowledgeScope)(scope);
432
+ return path.join(SQL_ERROR_LOG_DIR, resolved.tenantId, resolved.workspaceId, 'error_fix_pairs.json');
433
+ }
434
+ function loadLearnedSqlFixPairs(maxPairs = 10, scope) {
435
+ try {
436
+ const logFile = sqlErrorLogFile(scope);
437
+ if (!fs.existsSync(logFile))
438
+ return [];
439
+ const data = fs.readFileSync(logFile, 'utf-8');
440
+ const pairs = JSON.parse(data);
441
+ const cutoff = Date.now() - ERROR_FIX_PAIR_TTL_MS;
442
+ // Only return pairs that have successful fixes and are within TTL
443
+ return pairs
444
+ .filter(p => p.fixedSql && p.timestamp >= cutoff)
445
+ .slice(-maxPairs);
446
+ }
447
+ catch {
448
+ return [];
449
+ }
450
+ }
451
+ async function logSqlErrorFixPair(pair, scope) {
452
+ try {
453
+ const logFile = sqlErrorLogFile(scope);
454
+ let pairs = [];
455
+ try {
456
+ const data = await fs.promises.readFile(logFile, 'utf-8');
457
+ pairs = JSON.parse(data);
458
+ }
459
+ catch { /* fresh start */ }
460
+ // Deduplicate: if an equivalent error+fix pair already exists, update timestamp instead of appending
461
+ const existingIdx = pairs.findIndex(p => p.errorMessage === pair.errorMessage && p.fixedSql === pair.fixedSql);
462
+ if (existingIdx >= 0) {
463
+ pairs[existingIdx].timestamp = pair.timestamp;
464
+ }
465
+ else {
466
+ pairs.push(pair);
467
+ }
468
+ // Keep last 200 pairs
469
+ if (pairs.length > 200)
470
+ pairs = pairs.slice(-200);
471
+ await fs.promises.mkdir(path.dirname(logFile), { recursive: true });
472
+ // Atomic write: write to tmp file, then rename
473
+ const tmpFile = logFile + '.tmp';
474
+ await fs.promises.writeFile(tmpFile, JSON.stringify(pairs));
475
+ await fs.promises.rename(tmpFile, logFile);
476
+ }
477
+ catch (err) {
478
+ console.warn('[ClaudeMCP] Failed to log SQL error-fix pair:', err.message);
479
+ }
480
+ }
481
+ function loadSqlSchema() {
482
+ if (sqlSchemaCache)
483
+ return sqlSchemaCache;
484
+ const indexPath = path.resolve(__dirname, '../../data/perfettoSqlIndex.light.json');
485
+ try {
486
+ const raw = fs.readFileSync(indexPath, 'utf-8');
487
+ sqlSchemaCache = JSON.parse(raw);
488
+ }
489
+ catch (err) {
490
+ console.warn('[ClaudeMCP] Failed to load SQL schema index:', err.message);
491
+ sqlSchemaCache = { version: '0.0.0', generatedAt: '', templates: [] };
492
+ }
493
+ return sqlSchemaCache;
494
+ }
495
+ function compactSqlDocEntry(entry) {
496
+ const out = {
497
+ name: entry.name,
498
+ type: entry.type,
499
+ category: entry.category,
500
+ module: entry.module,
501
+ description: entry.description,
502
+ include: entry.include,
503
+ };
504
+ if (entry.tags?.length)
505
+ out.tags = entry.tags;
506
+ if (entry.columns?.length)
507
+ out.columns = entry.columns;
508
+ if (entry.params?.length)
509
+ out.params = entry.params;
510
+ if (entry.returnType)
511
+ out.returnType = entry.returnType;
512
+ if (entry.moduleIncludes?.length)
513
+ out.moduleIncludes = entry.moduleIncludes;
514
+ if (entry.transitiveIncludes?.length)
515
+ out.transitiveIncludes = entry.transitiveIncludes;
516
+ if (entry.lineage)
517
+ out.lineage = entry.lineage;
518
+ if (entry.dataCheckSql)
519
+ out.dataCheckSql = entry.dataCheckSql;
520
+ if (entry.sourcePath)
521
+ out.sourcePath = entry.sourcePath;
522
+ return out;
523
+ }
524
+ function compactLegacySqlSchemaEntry(entry) {
525
+ const out = {
526
+ name: entry.name,
527
+ type: entry.type,
528
+ category: entry.category,
529
+ description: entry.description,
530
+ };
531
+ if (entry.module)
532
+ out.module = entry.module;
533
+ if (entry.include)
534
+ out.include = entry.include;
535
+ if (entry.columns?.length)
536
+ out.columns = entry.columns;
537
+ if (entry.params?.length)
538
+ out.params = entry.params;
539
+ if (entry.returnType)
540
+ out.returnType = entry.returnType;
541
+ return out;
542
+ }
543
+ /**
544
+ * Normalize synthesizeData entry's `data` field into { columns, rows } format.
545
+ * synthesizeData entries can be:
546
+ * - Array of objects: [{ col1: val1, col2: val2 }, ...]
547
+ * - Already columnar: { columns: [...], rows: [[...], ...] }
548
+ * - Iterator results: [{ itemIndex, item, result: { ... } }]
549
+ * - Single object: { key: value, ... }
550
+ * All are normalized to { columns: string[], rows: any[][] } for ArtifactStore.
551
+ */
552
+ function normalizeSynthesizeDataForStorage(data) {
553
+ if (!data)
554
+ return { columns: [], rows: [] };
555
+ // Already columnar format
556
+ if (data.columns && Array.isArray(data.rows)) {
557
+ return { columns: data.columns, rows: data.rows };
558
+ }
559
+ // Array of objects
560
+ if (Array.isArray(data) && data.length > 0) {
561
+ const first = data[0];
562
+ // Iterator format: flatten item + result
563
+ if (first && typeof first === 'object' && 'itemIndex' in first && 'result' in first) {
564
+ const allKeys = new Set();
565
+ const flatRows = data.map((entry) => {
566
+ const flat = { itemIndex: entry.itemIndex };
567
+ // Merge item fields
568
+ if (entry.item && typeof entry.item === 'object') {
569
+ for (const [k, v] of Object.entries(entry.item)) {
570
+ flat[k] = v;
571
+ allKeys.add(k);
572
+ }
573
+ }
574
+ // Merge result fields (top-level scalars only, skip nested objects)
575
+ if (entry.result && typeof entry.result === 'object') {
576
+ for (const [k, v] of Object.entries(entry.result)) {
577
+ if (typeof v !== 'object' || v === null) {
578
+ flat[`result_${k}`] = v;
579
+ allKeys.add(`result_${k}`);
580
+ }
581
+ }
582
+ }
583
+ allKeys.add('itemIndex');
584
+ return flat;
585
+ });
586
+ const columns = ['itemIndex', ...Array.from(allKeys).filter(k => k !== 'itemIndex')];
587
+ const rows = flatRows.map((row) => columns.map(c => row[c] ?? null));
588
+ return { columns, rows };
589
+ }
590
+ // Plain array of objects
591
+ if (typeof first === 'object' && first !== null) {
592
+ const columns = Object.keys(first);
593
+ const rows = data.map((row) => columns.map(c => row[c] ?? null));
594
+ return { columns, rows };
595
+ }
596
+ // Array of primitives — single column
597
+ return { columns: ['value'], rows: data.map((v) => [v]) };
598
+ }
599
+ // Single object → single row
600
+ if (typeof data === 'object' && data !== null) {
601
+ const columns = Object.keys(data);
602
+ const rows = [columns.map(c => data[c] ?? null)];
603
+ return { columns, rows };
604
+ }
605
+ // Scalar
606
+ return { columns: ['value'], rows: [[data]] };
607
+ }
608
+ /**
609
+ * Creates an in-process MCP server scoped to a specific trace session.
610
+ * Exposes domain tools: execute_sql, invoke_skill, list_skills,
611
+ * detect_architecture, lookup_sql_schema, and optionally write_analysis_note.
612
+ */
613
+ function createClaudeMcpServer(options) {
614
+ const { traceId, traceProcessorService, skillExecutor, packageName, emitUpdate, onSkillResult, analysisNotes, artifactStore } = options;
615
+ const recentSqlErrors = options.recentSqlErrors || [];
616
+ const skillAdapter = (0, skillAnalysisAdapter_1.getSkillAnalysisAdapter)(traceProcessorService);
617
+ const watchdogRef = options.watchdogWarning;
618
+ const skillNotesBudget = options.skillNotesBudget;
619
+ const outputLanguage = options.outputLanguage ?? outputLanguage_1.DEFAULT_OUTPUT_LANGUAGE;
620
+ const knowledgeScope = options.knowledgeScope;
621
+ /** Normalize skill params: ensure process_name ↔ package are both set. */
622
+ function normalizeSkillParams(params, defaultPackage) {
623
+ const p = { ...params };
624
+ for (const key of Object.keys(p)) {
625
+ if (TIMESTAMP_EXPRESSION_PARAM_KEYS.has(key)) {
626
+ p[key] = normalizeTimestampExpression(p[key]);
627
+ }
628
+ }
629
+ if (defaultPackage && !p.process_name)
630
+ p.process_name = defaultPackage;
631
+ if (p.process_name && !p.package)
632
+ p.package = p.process_name;
633
+ if (p.package && !p.process_name)
634
+ p.process_name = p.package;
635
+ return p;
636
+ }
637
+ /**
638
+ * Consume and prepend any watchdog warning to a tool result.
639
+ * This is the feedback channel from runtime watchdog → Claude's execution context.
640
+ * When the watchdog detects repetitive tool failures, the warning appears
641
+ * in the NEXT tool result, which Claude reads and can act upon.
642
+ */
643
+ function consumeWatchdogWarning(resultText) {
644
+ if (watchdogRef?.current) {
645
+ const warning = watchdogRef.current;
646
+ watchdogRef.current = null; // consume once
647
+ return `⚠️ SYSTEM WARNING: ${warning}\n\n${resultText}`;
648
+ }
649
+ return resultText;
650
+ }
651
+ function rawSqlProcessIdentityWarning(sql) {
652
+ if (!(0, identityGate_1.sqlUsesProcessNameFilter)(sql))
653
+ return undefined;
654
+ return (0, outputLanguage_1.localize)(outputLanguage, 'Raw SQL 使用了进程/包名过滤;Process Identity Gate 只会自动保护 invoke_skill。信任这个 SQL 结论前,先用 process_identity_resolver 确认 canonical_package_name 与 recommended_process_name_param,或优先改用对应 Skill。', 'Raw SQL uses process/package-name filters; Process Identity Gate only protects invoke_skill automatically. Before trusting this SQL result, verify canonical_package_name and recommended_process_name_param with process_identity_resolver, or prefer the matching skill.');
655
+ }
656
+ function skipSqlQuotedText(sql, index, quote) {
657
+ let i = index + 1;
658
+ while (i < sql.length) {
659
+ if (sql[i] === quote) {
660
+ if (sql[i + 1] === quote) {
661
+ i += 2;
662
+ continue;
663
+ }
664
+ return i + 1;
665
+ }
666
+ i += 1;
667
+ }
668
+ return sql.length;
669
+ }
670
+ function skipSqlIgnoredText(sql, index) {
671
+ const char = sql[index];
672
+ const next = sql[index + 1];
673
+ if (char === '-' && next === '-') {
674
+ let i = index + 2;
675
+ while (i < sql.length && sql[i] !== '\n' && sql[i] !== '\r')
676
+ i += 1;
677
+ return i;
678
+ }
679
+ if (char === '/' && next === '*') {
680
+ let i = index + 2;
681
+ while (i < sql.length && !(sql[i] === '*' && sql[i + 1] === '/'))
682
+ i += 1;
683
+ return Math.min(sql.length, i + 2);
684
+ }
685
+ if (char === '\'' || char === '"' || char === '`')
686
+ return skipSqlQuotedText(sql, index, char);
687
+ if (char === '[') {
688
+ let i = index + 1;
689
+ while (i < sql.length && sql[i] !== ']')
690
+ i += 1;
691
+ return Math.min(sql.length, i + 1);
692
+ }
693
+ return index;
694
+ }
695
+ function readSqlIdentifierToken(sql, index) {
696
+ const char = sql[index];
697
+ if (char === '\'' || char === '"' || char === '`') {
698
+ const end = skipSqlQuotedText(sql, index, char);
699
+ const inner = sql.slice(index + 1, end - 1).split(`${char}${char}`).join(char);
700
+ return { value: inner, end };
701
+ }
702
+ if (char === '[') {
703
+ const end = skipSqlIgnoredText(sql, index);
704
+ return { value: sql.slice(index + 1, end - 1), end };
705
+ }
706
+ let i = index;
707
+ while (i < sql.length && /[A-Za-z0-9_$-]/.test(sql[i]))
708
+ i += 1;
709
+ if (i === index)
710
+ return null;
711
+ return { value: sql.slice(index, i), end: i };
712
+ }
713
+ function readSqlTableNameAfterFromOrJoin(sql, index) {
714
+ let i = index;
715
+ while (i < sql.length && /\s/.test(sql[i]))
716
+ i += 1;
717
+ if (sql[i] === '(')
718
+ return null;
719
+ let token = readSqlIdentifierToken(sql, i);
720
+ if (!token)
721
+ return null;
722
+ let tableName = token.value;
723
+ i = token.end;
724
+ while (i < sql.length && /\s/.test(sql[i]))
725
+ i += 1;
726
+ if (sql[i] === '.') {
727
+ i += 1;
728
+ while (i < sql.length && /\s/.test(sql[i]))
729
+ i += 1;
730
+ token = readSqlIdentifierToken(sql, i);
731
+ if (!token)
732
+ return { tableName, end: i };
733
+ tableName = token.value;
734
+ i = token.end;
735
+ }
736
+ return { tableName, end: i };
737
+ }
738
+ const tableAliasBoundaryWord = /^(WHERE|JOIN|LEFT|RIGHT|INNER|OUTER|CROSS|FULL|NATURAL|GROUP|ORDER|LIMIT|ON|USING|HAVING|UNION|EXCEPT|INTERSECT|WINDOW|QUALIFY|VALUES)$/i;
739
+ function readOptionalSqlAliasEnd(sql, index) {
740
+ let i = index;
741
+ while (i < sql.length && /\s/.test(sql[i]))
742
+ i += 1;
743
+ const asMatch = /^AS\b/i.exec(sql.slice(i));
744
+ if (asMatch) {
745
+ i += asMatch[0].length;
746
+ while (i < sql.length && /\s/.test(sql[i]))
747
+ i += 1;
748
+ }
749
+ const token = readSqlIdentifierToken(sql, i);
750
+ if (!token || tableAliasBoundaryWord.test(token.value))
751
+ return index;
752
+ return token.end;
753
+ }
754
+ function isArtifactPseudoTableName(tableName) {
755
+ const lower = tableName.toLowerCase();
756
+ return (lower !== '__intrinsic_batch_frame_root_cause' &&
757
+ (/^__intrinsic_[a-z_]\w*$/i.test(tableName) ||
758
+ /^art-\d+$/i.test(tableName) ||
759
+ lower === 'synthesizeartifacts' ||
760
+ lower === 'synthesize_artifacts' ||
761
+ lower === 'artifacts'));
762
+ }
763
+ function findArtifactPseudoTableNameInReference(sql, index) {
764
+ const table = readSqlTableNameAfterFromOrJoin(sql, index);
765
+ if (!table)
766
+ return { tableName: null, end: null };
767
+ const end = readOptionalSqlAliasEnd(sql, table.end);
768
+ return {
769
+ tableName: isArtifactPseudoTableName(table.tableName) ? table.tableName : null,
770
+ end: Math.max(table.end, end),
771
+ };
772
+ }
773
+ function findArtifactPseudoTableName(sql) {
774
+ let i = 0;
775
+ while (i < sql.length) {
776
+ const skipped = skipSqlIgnoredText(sql, i);
777
+ if (skipped !== i) {
778
+ i = skipped;
779
+ continue;
780
+ }
781
+ if (/[A-Za-z_]/.test(sql[i])) {
782
+ const wordStart = i;
783
+ while (i < sql.length && /[A-Za-z0-9_]/.test(sql[i]))
784
+ i += 1;
785
+ const word = sql.slice(wordStart, i);
786
+ if (/^FROM$/i.test(word)) {
787
+ while (i < sql.length) {
788
+ const reference = findArtifactPseudoTableNameInReference(sql, i);
789
+ if (reference.tableName)
790
+ return reference.tableName;
791
+ if (reference.end === null)
792
+ break;
793
+ i = reference.end;
794
+ while (i < sql.length && /\s/.test(sql[i]))
795
+ i += 1;
796
+ if (sql[i] !== ',')
797
+ break;
798
+ i += 1;
799
+ }
800
+ continue;
801
+ }
802
+ if (/^JOIN$/i.test(word)) {
803
+ const reference = findArtifactPseudoTableNameInReference(sql, i);
804
+ if (reference.tableName)
805
+ return reference.tableName;
806
+ if (reference.end !== null)
807
+ i = Math.max(i, reference.end);
808
+ }
809
+ continue;
810
+ }
811
+ i += 1;
812
+ }
813
+ return null;
814
+ }
815
+ function artifactSqlMisuseHint(sql, language) {
816
+ const tableName = findArtifactPseudoTableName(sql);
817
+ if (!tableName)
818
+ return null;
819
+ return {
820
+ success: false,
821
+ blocked: true,
822
+ error: (0, outputLanguage_1.localize)(language, `${tableName} 不是 trace_processor SQL 表。Skill 返回的 art-* / synthesizeArtifacts 是 SmartPerfetto artifact 引用,不能用 execute_sql 查询。`, `${tableName} is not a trace_processor SQL table. art-* / synthesizeArtifacts from Skill results are SmartPerfetto artifact references and cannot be queried with execute_sql.`),
823
+ action_required: 'fetch_artifact',
824
+ hint: 'Use fetch_artifact(artifactId="art-N", detail="rows", offset=0, limit=50) with the artifactId returned by invoke_skill.',
825
+ sql,
826
+ };
827
+ }
828
+ /**
829
+ * P0-G10: Enforce planning before analysis.
830
+ * Returns error JSON if plan is required but not yet submitted, null if OK.
831
+ * Only action tools (execute_sql, invoke_skill) are gated — informational
832
+ * and planning tools are exempt to allow plan formation.
833
+ */
834
+ const analysisPlanRef = options.analysisPlan;
835
+ /** Track submit_plan attempts for hard-gate: reject first incomplete plan, accept on retry. */
836
+ let planSubmitAttempts = 0;
837
+ function requirePlan(toolName) {
838
+ if (!analysisPlanRef)
839
+ return null; // Planning feature not enabled
840
+ if (analysisPlanRef.current)
841
+ return null; // Plan already submitted
842
+ return JSON.stringify({
843
+ success: false,
844
+ error: (0, outputLanguage_1.localize)(outputLanguage, `必须先调用 submit_plan 提交分析计划,然后才能使用 ${toolName}。请先制定你的分析计划,包含分析阶段、目标和预期工具。`, `You must call submit_plan before using ${toolName}. Create an analysis plan with phases, goals, and expected tools first.`),
845
+ action_required: 'submit_plan',
846
+ });
847
+ }
848
+ // Phase 1-C: Conditional REASONING_NUDGE — only append for first N data tool calls.
849
+ // After N calls, Claude should have internalized the reflect habit from system prompt.
850
+ const REASONING_NUDGE_MAX_CALLS = 4;
851
+ let dataToolCallCount = 0;
852
+ function getReasoningNudge() {
853
+ dataToolCallCount++;
854
+ if (dataToolCallCount > REASONING_NUDGE_MAX_CALLS)
855
+ return '';
856
+ return outputLanguage === 'en' ? REASONING_NUDGE_EN : REASONING_NUDGE_ZH;
857
+ }
858
+ let evidenceProducerOrdinal = 0;
859
+ function phaseHasToolExpectation(phase) {
860
+ return (phase.expectedCalls?.length || 0) > 0 || (phase.expectedTools?.length || 0) > 0;
861
+ }
862
+ function phaseMatchesToolInput(phase, toolName, input) {
863
+ const skillId = typeof input.skillId === 'string' ? input.skillId : undefined;
864
+ return (0, types_1.phaseMatchesCall)(phase, {
865
+ toolName,
866
+ timestamp: Date.now(),
867
+ skillId,
868
+ });
869
+ }
870
+ function phaseSemanticScore(phase, toolName, input) {
871
+ const skillId = typeof input.skillId === 'string' ? input.skillId : undefined;
872
+ const sql = typeof input.sql === 'string' ? input.sql : '';
873
+ const expected = [
874
+ ...(phase.expectedTools || []),
875
+ ...(phase.expectedCalls || []).map(call => call.skillId || call.tool),
876
+ ].join(' ');
877
+ const text = `${phase.id} ${phase.name} ${phase.goal} ${expected}`.toLowerCase();
878
+ const inputText = JSON.stringify(input ?? {}).toLowerCase();
879
+ let score = 0;
880
+ if (skillId) {
881
+ const id = skillId.toLowerCase();
882
+ if (text.includes(id))
883
+ score += 100;
884
+ if (text.includes(id.replace(/_/g, ' ')))
885
+ score += 60;
886
+ const hints = {
887
+ detect_architecture: ['架构', '渲染架构', '架构确认', '架构检测', '管线', 'pipeline', 'architecture'],
888
+ scrolling_analysis: ['滑动', 'scroll', '概览', '掉帧列表', '帧统计', '数据收集'],
889
+ startup_analysis: ['启动概览', '启动类型', '启动事件', 'startup', 'launch'],
890
+ startup_detail: ['启动详情', '四象限', '阻塞关系', '热点slice', '调度'],
891
+ startup_slow_reasons: ['慢原因', 'sr01', 'sr20', '交叉验证'],
892
+ memory_pressure_in_range: ['内存压力', 'memory', 'd状态', 'lmk', 'kswapd'],
893
+ blocking_chain_analysis: ['阻塞链', '阻塞关系', '唤醒', 'waker', 'blocked_functions', 'blocking_chain'],
894
+ lock_contention_in_range: ['锁竞争', 'futex', 'blocked_functions', '阻塞'],
895
+ binder_blocking_in_range: ['binder', '阻塞', '同步binder', 'ipc'],
896
+ jank_frame_detail: ['根因深钻', '单帧', '逐帧', 'jank_frame_detail', 'blocking_chain'],
897
+ frame_blocking_calls: ['根因深钻', '阻塞调用', 'frame_blocking_calls', 'blocking_chain'],
898
+ lock_binder_wait: ['根因深钻', '锁', 'binder', '阻塞', '等待', 'blocking_chain'],
899
+ frame_production_gap: ['缺帧', 'gap', '帧间', '隐形缺帧', '生产'],
900
+ batch_frame_root_cause: ['逐帧根因', 'reason_code', '根因分类'],
901
+ };
902
+ for (const hint of hints[id] || []) {
903
+ if (text.includes(hint.toLowerCase()))
904
+ score += 20;
905
+ }
906
+ if (id === 'jank_frame_detail') {
907
+ if (/根因深钻|深钻|单帧|代表帧|最严重帧|机制级|detail|drill/.test(text))
908
+ score += 60;
909
+ if (/分布|分类|聚合|统计|batch|reason_code/.test(text) && !/深钻|单帧|代表帧|最严重帧|机制级/.test(text))
910
+ score -= 15;
911
+ }
912
+ if (id === 'blocking_chain_analysis') {
913
+ if (/阻塞链|阻塞关系|唤醒|waker|blocked_functions|blocking_chain|锁竞争|binder/.test(text))
914
+ score += 70;
915
+ if (/根因|深钻|机制|代表帧|最严重帧|单帧|深入诊断|detail|drill|root cause/.test(text))
916
+ score += 60;
917
+ }
918
+ if (id === 'memory_pressure_in_range') {
919
+ if (/内存压力|memory|lmk|kswapd|reclaim|gc|根因|交叉验证|排除/.test(text))
920
+ score += 70;
921
+ }
922
+ if (id === 'startup_slow_reasons') {
923
+ if (/慢原因|启动慢|sr\d+|sr01|sr20|根因|交叉验证|已知原因/.test(text))
924
+ score += 70;
925
+ }
926
+ }
927
+ if (toolName === 'detect_architecture') {
928
+ if (/架构|渲染架构|架构确认|架构检测|管线|architecture|pipeline|trace 时间范围|time range/.test(text))
929
+ score += 120;
930
+ if (/缺帧检测|frame_production_gap|gap detection/.test(text))
931
+ score -= 120;
932
+ if (/综合结论|结论|conclusion|报告|report/.test(text))
933
+ score -= 40;
934
+ }
935
+ if (toolName === 'fetch_artifact') {
936
+ if (/fetch_artifact|artifact|分页|全量|完整|掉帧数据|batch_frame_root_cause|根因数据/.test(text) &&
937
+ /全量|完整|掉帧|root_cause|batch_frame_root_cause|reason_code|artifact/.test(inputText)) {
938
+ score += 120;
939
+ }
940
+ if (/全量|完整|分页|batch_frame_root_cause|根因数据/.test(text) &&
941
+ /全量|完整|batch_frame_root_cause|reason_code|根因分布/.test(inputText)) {
942
+ score += 90;
943
+ }
944
+ if (/根因深钻|深钻|代表帧|最严重帧|机制级|blocking|jank_frame_detail|frame_blocking/.test(text) &&
945
+ /阻塞|blocking|代表|最严重|top_slice|jank_frame_detail|frame_blocking|主线程/.test(inputText)) {
946
+ score += 85;
947
+ }
948
+ if (/根因深钻|深钻|代表帧|最严重帧|机制级/.test(text) &&
949
+ /全量|完整|根因分布|batch_frame_root_cause/.test(inputText) &&
950
+ !/代表|最严重|阻塞|blocking|top_slice/.test(inputText)) {
951
+ score -= 40;
952
+ }
953
+ if (/概览|overview|滑动区间|帧统计|掉帧分布/.test(text) &&
954
+ /概览|summary|滑动区间|session|jank_type|性能概览/.test(inputText)) {
955
+ score += 60;
956
+ }
957
+ if (/综合结论|结论|conclusion|报告|report/.test(text))
958
+ score -= 30;
959
+ }
960
+ if (toolName === 'execute_sql' || toolName === 'execute_sql_on') {
961
+ const sqlText = sql.toLowerCase();
962
+ const isFrameOverviewSql = /actual_frame_timeline_slice/.test(sqlText) &&
963
+ (/min\s*\(\s*ts\s*\)/.test(sqlText) ||
964
+ /max\s*\(\s*ts\s*\+\s*dur\s*\)/.test(sqlText) ||
965
+ /count\s*\(\s*\*\s*\)/.test(sqlText) ||
966
+ /\b(frame_count|total_frames|layer_count)\b/.test(sqlText));
967
+ const isTraceRangeSql = /actual_frame_timeline_slice/.test(sqlText) &&
968
+ /min\s*\(\s*ts\s*\)/.test(sqlText) &&
969
+ /max\s*\(\s*ts\s*\+\s*dur\s*\)/.test(sqlText);
970
+ const hasFrameOverviewPhaseHint = /概览|overview|数据收集|采集|帧统计|帧率统计|滑动区间|时间范围|time range/.test(text);
971
+ if (isTraceRangeSql) {
972
+ if (/trace|时间范围|时间边界|边界|time range|range/.test(text))
973
+ score += 180;
974
+ if (/架构确认|确认.*架构|架构检测|检测.*架构|detect.*architecture|architecture.*detect/.test(text))
975
+ score += 60;
976
+ if (/hwui|producer|surfaceflinger|sf|合成|链路/.test(text) && !hasFrameOverviewPhaseHint)
977
+ score -= 50;
978
+ if (/根因|深钻|逐帧|reason_code|综合结论|报告/.test(text) && !hasFrameOverviewPhaseHint)
979
+ score -= 50;
980
+ }
981
+ if (isFrameOverviewSql) {
982
+ if (hasFrameOverviewPhaseHint)
983
+ score += 80;
984
+ if (/根因|深钻|逐帧|diagnos|root cause/.test(text))
985
+ score -= 20;
986
+ }
987
+ const isRootCauseDrillSql = /\b(thread|thread_state|thread_slice|thread_track|slice|slice_self_dur|sched|futex|binder|blocking|root_cause|reason_code|top_slice|main_q4b|__intrinsic_batch_frame_root_cause)\b/.test(sqlText);
988
+ if (isRootCauseDrillSql) {
989
+ if (/根因|深钻|机制|阻塞|代表帧|逐帧|单帧|detail|drill|root cause|blocking/.test(text))
990
+ score += 80;
991
+ if (/概览|overview|帧统计|掉帧分布|数据收集|采集/.test(text))
992
+ score -= 10;
993
+ }
994
+ const isWebViewStartupSql = /webview|chromium|v8|crrenderermain|parsehtml|drawgl/.test(sqlText);
995
+ if (isWebViewStartupSql) {
996
+ if (/webview|chromium|v8|crrenderermain|parsehtml|drawgl|页面渲染/.test(text))
997
+ score += 140;
998
+ if (/综合结论|结论|conclusion|报告|report/.test(text) && !/webview|chromium|v8/.test(text))
999
+ score -= 30;
1000
+ }
1001
+ const sqlHints = [
1002
+ [/webview|chromium|v8|crrenderermain|parsehtml|drawgl/, ['webview', 'chromium', 'v8', '页面渲染']],
1003
+ [/actual_frame_timeline|expected_frame_timeline|jank|frame/, ['滑动', '掉帧', '帧', 'frame']],
1004
+ [/\bthread\b|thread_state|thread_slice|slice_self_dur|sched|cpu|freq/, ['线程', '调度', 'cpu', '频率', '热点', '主线程', '阻塞']],
1005
+ [/memory|lmk|kswapd|reclaim/, ['内存', 'memory', 'lmk']],
1006
+ ];
1007
+ for (const [pattern, hints] of sqlHints) {
1008
+ if (!pattern.test(sqlText))
1009
+ continue;
1010
+ for (const hint of hints) {
1011
+ if (text.includes(hint.toLowerCase()))
1012
+ score += 15;
1013
+ }
1014
+ }
1015
+ }
1016
+ return score;
1017
+ }
1018
+ function inferSemanticPhase(phases, toolName, input) {
1019
+ const scored = phases
1020
+ .map(phase => ({ phase, score: phaseSemanticScore(phase, toolName, input) }))
1021
+ .filter(item => item.score > 0)
1022
+ .sort((a, b) => b.score - a.score);
1023
+ if (scored.length === 0)
1024
+ return undefined;
1025
+ if (scored.length === 1 || scored[0].score > scored[1].score)
1026
+ return scored[0].phase;
1027
+ return undefined;
1028
+ }
1029
+ function autoStartPhaseForEvidence(phase, toolName, input) {
1030
+ const plan = analysisPlanRef?.current;
1031
+ if (!plan || phase.status !== 'pending')
1032
+ return false;
1033
+ closeSupersededInProgressPhases(plan, phase);
1034
+ phase.status = 'in_progress';
1035
+ phase.completedAt = undefined;
1036
+ phase.summary = undefined;
1037
+ const narration = (0, toolNarration_1.formatToolCallNarration)(toolName, input, outputLanguage);
1038
+ const summary = (0, outputLanguage_1.localize)(outputLanguage, `自动进入阶段:${narration}`, `Auto-started phase for: ${narration}`).slice(0, 260);
1039
+ emitUpdate?.({
1040
+ type: 'plan_phase_updated',
1041
+ content: { phaseId: phase.id, status: 'in_progress', summary, phaseName: phase.name },
1042
+ timestamp: Date.now(),
1043
+ });
1044
+ return true;
1045
+ }
1046
+ function autoClosedPhaseSummary(closedPhase, nextPhase) {
1047
+ const artifacts = typeof artifactStore?.serialize === 'function'
1048
+ ? artifactStore.serialize().filter(artifact => artifact.planPhaseId === closedPhase.id)
1049
+ : [];
1050
+ const titles = Array.from(new Set(artifacts
1051
+ .map(artifact => artifact.title || artifact.stepId)
1052
+ .filter((title) => typeof title === 'string' && title.trim().length > 0))).slice(0, 4);
1053
+ const skillIds = Array.from(new Set(artifacts
1054
+ .map(artifact => artifact.skillId)
1055
+ .filter((skillId) => typeof skillId === 'string' && skillId.trim().length > 0))).slice(0, 3);
1056
+ const moreCount = Math.max(0, artifacts.length - titles.length);
1057
+ const titleSummary = titles.length
1058
+ ? (0, outputLanguage_1.localize)(outputLanguage, `:${titles.join('、')}${moreCount > 0 ? `等 ${moreCount} 个` : ''}`, `: ${titles.join(', ')}${moreCount > 0 ? ` and ${moreCount} more` : ''}`)
1059
+ : '';
1060
+ const evidenceSummary = artifacts.length > 0
1061
+ ? (0, outputLanguage_1.localize)(outputLanguage, `本阶段已产生 ${artifacts.length} 个证据表${skillIds.length ? `(来源:${skillIds.join('、')})` : ''}${titleSummary}。`, `This phase produced ${artifacts.length} evidence table(s)${skillIds.length ? ` from ${skillIds.join(', ')}` : ''}${titleSummary}.`)
1062
+ : (0, outputLanguage_1.localize)(outputLanguage, `本阶段未记录 artifact,但已保留该阶段的工具调用和时间线事件。`, `This phase did not record artifacts, but its tool calls and timeline events remain available.`);
1063
+ return (0, outputLanguage_1.localize)(outputLanguage, `自动完成阶段「${closedPhase.name}」:已进入后续阶段「${nextPhase.name}」。${evidenceSummary}阶段目标:${closedPhase.goal}。上一阶段未收到显式完成摘要。`, `Auto-completed phase "${closedPhase.name}" after moving to "${nextPhase.name}". ${evidenceSummary} Phase goal: ${closedPhase.goal}. The previous phase did not provide an explicit completion summary.`);
1064
+ }
1065
+ function closeSupersededInProgressPhases(plan, nextPhase) {
1066
+ const nextIndex = plan.phases.findIndex(p => p.id === nextPhase.id);
1067
+ for (const other of plan.phases) {
1068
+ if (other.id === nextPhase.id || other.status !== 'in_progress')
1069
+ continue;
1070
+ const otherIndex = plan.phases.findIndex(p => p.id === other.id);
1071
+ if (otherIndex >= 0 && nextIndex >= 0 && otherIndex < nextIndex) {
1072
+ const summary = autoClosedPhaseSummary(other, nextPhase);
1073
+ other.status = 'completed';
1074
+ other.completedAt = Date.now();
1075
+ other.summary = summary;
1076
+ emitUpdate?.({
1077
+ type: 'plan_phase_updated',
1078
+ content: { phaseId: other.id, status: 'completed', summary, phaseName: other.name },
1079
+ timestamp: Date.now(),
1080
+ });
1081
+ }
1082
+ else {
1083
+ other.status = 'pending';
1084
+ other.completedAt = undefined;
1085
+ other.summary = undefined;
1086
+ }
1087
+ }
1088
+ }
1089
+ function laterInProgressPhase(plan, phase) {
1090
+ const phaseIndex = plan.phases.findIndex(p => p.id === phase.id);
1091
+ if (phaseIndex < 0)
1092
+ return undefined;
1093
+ return plan.phases.find((p, index) => p.status === 'in_progress' && index > phaseIndex);
1094
+ }
1095
+ function bindPendingPhaseForEvidence(phase, toolName, input) {
1096
+ const plan = analysisPlanRef?.current;
1097
+ const laterActive = plan ? laterInProgressPhase(plan, phase) : undefined;
1098
+ if (plan && phase.status === 'pending' && laterActive) {
1099
+ const narration = (0, toolNarration_1.formatToolCallNarration)(toolName, input, outputLanguage);
1100
+ const summary = (0, outputLanguage_1.localize)(outputLanguage, `自动补记阶段:收到本阶段证据(${narration}),但当前已在后续阶段「${laterActive.name}」。该阶段直接标记完成,证据以推断方式绑定。`, `Backfilled phase evidence (${narration}) while later phase "${laterActive.name}" was active. Marked this phase complete and bound the evidence as inferred.`).slice(0, 260);
1101
+ phase.status = 'completed';
1102
+ phase.completedAt = Date.now();
1103
+ phase.summary = summary;
1104
+ emitUpdate?.({
1105
+ type: 'plan_phase_updated',
1106
+ content: { phaseId: phase.id, status: 'completed', summary, phaseName: phase.name },
1107
+ timestamp: Date.now(),
1108
+ });
1109
+ return {
1110
+ phase,
1111
+ attribution: 'inferred',
1112
+ warning: (0, outputLanguage_1.localize)(outputLanguage, `证据语义匹配较早阶段 "${phase.name}",但当前已在后续阶段 "${laterActive.name}";已按补记阶段绑定,需要核对顺序。`, `Evidence semantically matched earlier phase "${phase.name}" while later phase "${laterActive.name}" was active; bound as a backfilled phase and should be checked for ordering.`),
1113
+ };
1114
+ }
1115
+ autoStartPhaseForEvidence(phase, toolName, input);
1116
+ return { phase, attribution: 'active' };
1117
+ }
1118
+ function activePlanPhaseForEvidence(toolName, input) {
1119
+ const plan = analysisPlanRef?.current;
1120
+ if (!plan)
1121
+ return { attribution: 'none' };
1122
+ const active = plan.phases.filter(p => p.status === 'in_progress');
1123
+ if (active.length === 0) {
1124
+ const isRawSqlTool = toolName === 'execute_sql' || toolName === 'execute_sql_on';
1125
+ if (isRawSqlTool) {
1126
+ const semanticPending = inferSemanticPhase(plan.phases.filter(p => p.status === 'pending'), toolName, input);
1127
+ if (semanticPending) {
1128
+ return bindPendingPhaseForEvidence(semanticPending, toolName, input);
1129
+ }
1130
+ const semanticRecentCompleted = inferSemanticPhase(plan.phases
1131
+ .filter(p => p.status === 'completed' &&
1132
+ typeof p.completedAt === 'number' &&
1133
+ Date.now() - p.completedAt <= 5 * 60 * 1000)
1134
+ .sort((a, b) => (b.completedAt || 0) - (a.completedAt || 0)), toolName, input);
1135
+ if (semanticRecentCompleted) {
1136
+ return {
1137
+ phase: semanticRecentCompleted,
1138
+ attribution: 'inferred',
1139
+ warning: (0, outputLanguage_1.localize)(outputLanguage, `当前没有明确进行中的 plan 阶段;已按 SQL 内容绑定到最近完成的阶段 "${semanticRecentCompleted.name}",需要核对。`, `No plan phase is explicitly in progress; bound to the recently completed phase "${semanticRecentCompleted.name}" by SQL content and should be verified.`),
1140
+ };
1141
+ }
1142
+ }
1143
+ const matchingPending = plan.phases.filter(p => p.status === 'pending' &&
1144
+ phaseHasToolExpectation(p) &&
1145
+ phaseMatchesToolInput(p, toolName, input));
1146
+ if (matchingPending.length === 1) {
1147
+ const phase = matchingPending[0];
1148
+ return bindPendingPhaseForEvidence(phase, toolName, input);
1149
+ }
1150
+ if (matchingPending.length > 1) {
1151
+ const phase = inferSemanticPhase(matchingPending, toolName, input);
1152
+ if (phase) {
1153
+ return bindPendingPhaseForEvidence(phase, toolName, input);
1154
+ }
1155
+ return {
1156
+ attribution: 'ambiguous',
1157
+ warning: (0, outputLanguage_1.localize)(outputLanguage, `当前没有明确进行中的 plan 阶段,且 ${matchingPending.length} 个待执行阶段都匹配 ${toolName};此数据未绑定具体阶段。`, `No plan phase is explicitly in progress and ${matchingPending.length} pending phases match ${toolName}; this data is not bound to a concrete phase.`),
1158
+ };
1159
+ }
1160
+ const recentCompleted = plan.phases
1161
+ .filter(p => p.status === 'completed' &&
1162
+ typeof p.completedAt === 'number' &&
1163
+ Date.now() - p.completedAt <= 5 * 60 * 1000 &&
1164
+ phaseHasToolExpectation(p) &&
1165
+ phaseMatchesToolInput(p, toolName, input))
1166
+ .sort((a, b) => (b.completedAt || 0) - (a.completedAt || 0));
1167
+ if (recentCompleted.length > 0) {
1168
+ const phase = inferSemanticPhase(recentCompleted, toolName, input) || recentCompleted[0];
1169
+ return {
1170
+ phase,
1171
+ attribution: 'inferred',
1172
+ warning: (0, outputLanguage_1.localize)(outputLanguage, `当前没有明确进行中的 plan 阶段;已绑定到最近完成且匹配工具的阶段 "${phase.name}",需要核对。`, `No plan phase is explicitly in progress; bound to the most recently completed matching phase "${phase.name}" and should be verified.`),
1173
+ };
1174
+ }
1175
+ const semanticPending = inferSemanticPhase(plan.phases.filter(p => p.status === 'pending' && phaseHasToolExpectation(p)), toolName, input);
1176
+ if (semanticPending) {
1177
+ return bindPendingPhaseForEvidence(semanticPending, toolName, input);
1178
+ }
1179
+ return {
1180
+ attribution: 'missing',
1181
+ warning: (0, outputLanguage_1.localize)(outputLanguage, '当前没有明确进行中的 plan 阶段;此数据未绑定具体阶段。', 'No plan phase is explicitly in progress; this data is not bound to a concrete phase.'),
1182
+ };
1183
+ }
1184
+ if (active.length > 1) {
1185
+ return {
1186
+ attribution: 'ambiguous',
1187
+ warning: (0, outputLanguage_1.localize)(outputLanguage, `当前有 ${active.length} 个 plan 阶段同时进行;此数据未绑定具体阶段。`, `${active.length} plan phases are in progress at the same time; this data is not bound to a concrete phase.`),
1188
+ };
1189
+ }
1190
+ const phase = active[0];
1191
+ const skillId = typeof input.skillId === 'string' ? input.skillId : undefined;
1192
+ if (phaseHasToolExpectation(phase) && !phaseMatchesToolInput(phase, toolName, input)) {
1193
+ const activeSemanticScore = phaseSemanticScore(phase, toolName, input);
1194
+ const matchingPending = plan.phases.filter(p => p.status === 'pending' &&
1195
+ phaseHasToolExpectation(p) &&
1196
+ phaseMatchesToolInput(p, toolName, input));
1197
+ const inferredPhase = matchingPending.length === 1
1198
+ ? matchingPending[0]
1199
+ : inferSemanticPhase(matchingPending, toolName, input);
1200
+ if (inferredPhase) {
1201
+ const inferredSemanticScore = phaseSemanticScore(inferredPhase, toolName, input);
1202
+ if (activeSemanticScore >= 50 && inferredSemanticScore < activeSemanticScore + 30) {
1203
+ return { phase, attribution: 'active' };
1204
+ }
1205
+ return bindPendingPhaseForEvidence(inferredPhase, toolName, input);
1206
+ }
1207
+ const semanticPending = inferSemanticPhase(plan.phases.filter(p => p.status === 'pending' && phaseHasToolExpectation(p)), toolName, input);
1208
+ if (semanticPending && phaseSemanticScore(semanticPending, toolName, input) >= 50) {
1209
+ return bindPendingPhaseForEvidence(semanticPending, toolName, input);
1210
+ }
1211
+ if (activeSemanticScore >= 50) {
1212
+ return { phase, attribution: 'active' };
1213
+ }
1214
+ return {
1215
+ phase,
1216
+ attribution: 'unexpected_tool',
1217
+ warning: (0, outputLanguage_1.localize)(outputLanguage, `当前阶段 "${phase.name}" 未声明会调用 ${toolName}${skillId ? `(${skillId})` : ''};此阶段归因需要人工核对。`, `Active phase "${phase.name}" did not declare ${toolName}${skillId ? `(${skillId})` : ''}; verify this phase attribution.`),
1218
+ };
1219
+ }
1220
+ const activeSemanticScore = phaseSemanticScore(phase, toolName, input);
1221
+ const semanticPending = inferSemanticPhase(plan.phases.filter(p => p.status === 'pending' && phaseHasToolExpectation(p)), toolName, input);
1222
+ if (semanticPending) {
1223
+ const pendingSemanticScore = phaseSemanticScore(semanticPending, toolName, input);
1224
+ if (pendingSemanticScore >= 50 && pendingSemanticScore >= activeSemanticScore + 30) {
1225
+ return bindPendingPhaseForEvidence(semanticPending, toolName, input);
1226
+ }
1227
+ }
1228
+ return { phase, attribution: 'active' };
1229
+ }
1230
+ function createEvidenceProducerContext(toolName, input, producerReason, suffix, phaseOverride) {
1231
+ const summary = (0, toolCallSummary_1.summarizeToolCallInput)(toolName, input);
1232
+ const phaseResolution = phaseOverride?.phaseId
1233
+ ? undefined
1234
+ : activePlanPhaseForEvidence(toolName, input);
1235
+ const phase = phaseResolution?.phase;
1236
+ const lightweightPhase = !phaseOverride?.phaseId && !phase?.id && options.lightweight
1237
+ ? {
1238
+ id: 'quick',
1239
+ name: (0, outputLanguage_1.localize)(outputLanguage, '快速回答', 'Quick answer'),
1240
+ goal: (0, outputLanguage_1.localize)(outputLanguage, '用轻量工具链快速回答当前问题', 'Answer the current question with the lightweight tool chain.'),
1241
+ }
1242
+ : undefined;
1243
+ const paramsHash = summary.paramsHash || evidenceHash(input);
1244
+ const ordinal = ++evidenceProducerOrdinal;
1245
+ const sourceToolCallId = [
1246
+ toolName,
1247
+ ordinal,
1248
+ paramsHash,
1249
+ suffix,
1250
+ ].filter(Boolean).join(':');
1251
+ return {
1252
+ sourceToolCallId,
1253
+ paramsHash,
1254
+ planPhaseId: phaseOverride?.phaseId ?? phase?.id ?? lightweightPhase?.id,
1255
+ planPhaseTitle: phaseOverride?.phaseTitle ?? phase?.name ?? lightweightPhase?.name,
1256
+ planPhaseGoal: phaseOverride?.phaseGoal ?? phase?.goal ?? lightweightPhase?.goal,
1257
+ planPhaseAttribution: phaseOverride?.attribution ?? (lightweightPhase ? 'active' : phaseResolution?.attribution),
1258
+ planPhaseWarning: phaseOverride?.warning ?? phaseResolution?.warning,
1259
+ toolNarration: (0, toolNarration_1.formatToolCallNarration)(toolName, input, outputLanguage),
1260
+ producerReason,
1261
+ };
1262
+ }
1263
+ async function detectArchitecturePayload() {
1264
+ if (options.cachedArchitecture) {
1265
+ const info = options.cachedArchitecture;
1266
+ return {
1267
+ type: info.type,
1268
+ confidence: info.confidence,
1269
+ evidence: (info.evidence ?? []).map(e => ({ source: e.source, type: e.type, weight: e.weight })),
1270
+ flutter: info.flutter,
1271
+ compose: info.compose,
1272
+ webview: info.webview,
1273
+ cached: true,
1274
+ };
1275
+ }
1276
+ const detector = (0, architectureDetector_1.createArchitectureDetector)();
1277
+ const info = await detector.detect({ traceId, traceProcessorService, packageName });
1278
+ return {
1279
+ type: info.type,
1280
+ confidence: info.confidence,
1281
+ evidence: (info.evidence ?? []).map(e => ({ source: e.source, type: e.type, weight: e.weight })),
1282
+ flutter: info.flutter,
1283
+ compose: info.compose,
1284
+ webview: info.webview,
1285
+ };
1286
+ }
1287
+ // Auto-inject `INCLUDE PERFETTO MODULE ...;` for stdlib tables/functions
1288
+ // referenced in raw SQL. Shared between execute_sql and execute_sql_on
1289
+ // so comparison-mode queries get the same treatment. See
1290
+ // sqlIncludeInjector.ts for the full rationale.
1291
+ async function runRawSqlWithIncludeInjection(targetTraceId, sql, traceSide = 'current') {
1292
+ const normalized = (0, rawSqlNormalizer_1.normalizeRawSql)(sql);
1293
+ const { sql: finalSql, injected } = (0, sqlIncludeInjector_1.injectStdlibIncludes)(normalized.sql);
1294
+ const traceProvenance = (0, traceProcessorConnectionModel_1.buildTraceProcessorQueryProvenance)({
1295
+ traceId: targetTraceId,
1296
+ traceSide,
1297
+ });
1298
+ if (emitUpdate && injected.length > 0) {
1299
+ emitUpdate({
1300
+ type: 'progress',
1301
+ content: {
1302
+ phase: 'analyzing',
1303
+ message: (0, outputLanguage_1.localize)(outputLanguage, `自动加载 stdlib 模块: ${injected.join(', ')}`, `Auto-loaded stdlib module(s): ${injected.join(', ')}`),
1304
+ },
1305
+ timestamp: Date.now(),
1306
+ });
1307
+ }
1308
+ const result = await traceProcessorService.query(targetTraceId, finalSql);
1309
+ return {
1310
+ result,
1311
+ finalSql,
1312
+ injected,
1313
+ traceProvenance,
1314
+ normalizedSql: normalized.sql,
1315
+ sqlRewrites: normalized.rewrites,
1316
+ };
1317
+ }
1318
+ const executeSql = (0, claude_agent_sdk_1.tool)('execute_sql', 'Execute a raw SQL query against the Perfetto trace_processor for the currently loaded trace. ' +
1319
+ 'Returns columnar results. Set summary=true for large result sets to get column statistics + sample rows.\n\n' +
1320
+ 'Use when: ad-hoc queries not covered by existing skills, verifying hypotheses with specific SQL, checking raw data.\n' +
1321
+ 'Don\'t use when: a matching skill exists (use invoke_skill instead — richer layered output), or you need schema info (use lookup_sql_schema first).\n\n' +
1322
+ 'SQL safety rules: qualify duplicate column names after JOINs. Do not write bare SELECT name/ts/dur when joining slice/thread/process; use s.name AS slice_name, s.ts, s.dur, t.name AS thread_name, p.name AS process_name, or prefer the thread_slice stdlib view. FrameTimeline rows expose upid, not utid/process_name; use JOIN process USING(upid) for actual_frame_timeline_slice. thread_slice does not expose self_dur directly; JOIN slice_self_dur USING(id) when self time is needed. When using thread_slice, read thread_name and process_name directly; do not write t.name or p.name unless JOIN thread t or JOIN process p is present. The thread table main-thread column is is_main_thread, not main_thread. Do not query __intrinsic_* names or skill step names such as batch_frame_root_cause as SQL tables; they are skill artifacts, use fetch_artifact for those rows.\n\n' +
1323
+ 'Examples:\n' +
1324
+ '1. Count jank frames: sql="SELECT COUNT(*) as jank_count FROM actual_frame_timeline_slice WHERE jank_type != \'None\'", summary=false\n' +
1325
+ '2. CPU frequency overview: sql="SELECT cpu, MIN(value) as min_freq, MAX(value) as max_freq, AVG(value) as avg_freq FROM counter JOIN counter_track ON counter.track_id=counter_track.id WHERE counter_track.name GLOB \'cpu*freq\' GROUP BY cpu", summary=true\n' +
1326
+ '3. Thread state in time range: sql="SELECT state, SUM(dur)/1e6 as total_ms FROM thread_state WHERE utid=123 AND ts BETWEEN 1000 AND 2000 GROUP BY state", summary=false', {
1327
+ sql: zod_1.z.string().describe('The SQL query to execute. Use Perfetto stdlib tables/functions (e.g. android_jank_cuj, slice, thread, process).'),
1328
+ summary: zod_1.z.boolean().optional().describe('When true, returns column statistics (min/max/avg/percentiles) + 10 most interesting sample rows instead of full results. Use for large result sets where you need aggregate understanding, not row-level data. Default: false.'),
1329
+ }, async ({ sql, summary }) => {
1330
+ // P0-G10: Block analysis tools until plan is submitted
1331
+ const planError = requirePlan('execute_sql');
1332
+ if (planError) {
1333
+ return { content: [{ type: 'text', text: planError }] };
1334
+ }
1335
+ const artifactSqlHint = artifactSqlMisuseHint(sql, outputLanguage);
1336
+ if (artifactSqlHint) {
1337
+ return {
1338
+ content: [{ type: 'text', text: JSON.stringify(artifactSqlHint) }],
1339
+ isError: true,
1340
+ };
1341
+ }
1342
+ const producer = createEvidenceProducerContext('execute_sql', { sql, summary }, (0, outputLanguage_1.localize)(outputLanguage, '执行当前 Trace SQL,验证本阶段的具体数据点。', 'Run SQL on the current trace to verify this phase of evidence.'));
1343
+ try {
1344
+ const sqlStart = Date.now();
1345
+ const { result, finalSql, injected, traceProvenance, normalizedSql, sqlRewrites } = await runRawSqlWithIncludeInjection(traceId, sql, 'current');
1346
+ const processIdentityWarning = rawSqlProcessIdentityWarning(normalizedSql);
1347
+ const truncated = result.rows.length > 200;
1348
+ const rows = truncated ? result.rows.slice(0, 200) : result.rows;
1349
+ const success = !result.error;
1350
+ const sqlDuration = Date.now() - sqlStart;
1351
+ if (emitUpdate && sqlDuration > 500) {
1352
+ emitUpdate({
1353
+ type: 'progress',
1354
+ content: {
1355
+ phase: 'analyzing',
1356
+ message: (0, outputLanguage_1.localize)(outputLanguage, `SQL 查询完成 (${result.rows.length} 行, ${sqlDuration}ms)`, `SQL query completed (${result.rows.length} rows, ${sqlDuration}ms)`),
1357
+ },
1358
+ timestamp: Date.now(),
1359
+ });
1360
+ }
1361
+ let emittedEvidence;
1362
+ if (emitUpdate && !success && result.error) {
1363
+ emitUpdate({
1364
+ type: 'progress',
1365
+ content: {
1366
+ phase: 'analyzing',
1367
+ message: (0, outputLanguage_1.localize)(outputLanguage, `SQL 查询错误: ${result.error.substring(0, 200)}`, `SQL query error: ${result.error.substring(0, 200)}`),
1368
+ },
1369
+ timestamp: Date.now(),
1370
+ });
1371
+ }
1372
+ // SQL error-fix pair learning: capture errors and match subsequent fixes
1373
+ if (!success && result.error) {
1374
+ recentSqlErrors.push({ errorSql: sql, errorMessage: result.error, timestamp: Date.now() });
1375
+ // Keep only last 10 errors in memory
1376
+ if (recentSqlErrors.length > 10)
1377
+ recentSqlErrors.shift();
1378
+ }
1379
+ else if (success && recentSqlErrors.length > 0) {
1380
+ // Match error-fix pairs by timestamp proximity (same turn, within 60s)
1381
+ // and structural similarity (>30% token overlap via Jaccard similarity).
1382
+ // SQL structural keywords + Perfetto domain tokens are excluded to avoid
1383
+ // false matches between unrelated queries that share common vocabulary.
1384
+ const matchingError = recentSqlErrors.find(e => {
1385
+ // Must be within 60 seconds (covers multi-turn reasoning gaps)
1386
+ if (Date.now() - e.timestamp > 60000)
1387
+ return false;
1388
+ // Require reasonable structural similarity (not a totally different query)
1389
+ const errorTokens = sqlContentTokens(e.errorSql);
1390
+ const fixTokens = sqlContentTokens(sql);
1391
+ if (errorTokens.size === 0)
1392
+ return false;
1393
+ let intersection = 0;
1394
+ for (const t of errorTokens) {
1395
+ if (fixTokens.has(t))
1396
+ intersection++;
1397
+ }
1398
+ const union = new Set([...errorTokens, ...fixTokens]).size;
1399
+ const jaccard = union > 0 ? intersection / union : 0;
1400
+ return jaccard > 0.3; // At least 30% token overlap
1401
+ });
1402
+ if (matchingError) {
1403
+ await logSqlErrorFixPair({ ...matchingError, fixedSql: sql }, knowledgeScope);
1404
+ const idx = recentSqlErrors.indexOf(matchingError);
1405
+ if (idx >= 0)
1406
+ recentSqlErrors.splice(idx, 1);
1407
+ }
1408
+ }
1409
+ // Summary mode: return column statistics + sample rows instead of raw data
1410
+ if (summary && success && rows.length > 0) {
1411
+ const summaryResult = (0, sqlSummarizer_1.summarizeSqlResult)(result.columns, result.rows);
1412
+ if (emitUpdate) {
1413
+ emittedEvidence = emitSqlSummaryDataEnvelope(emitUpdate, summaryResult, finalSql, injected, traceProvenance, producer);
1414
+ }
1415
+ return {
1416
+ content: [{
1417
+ type: 'text',
1418
+ text: consumeWatchdogWarning(JSON.stringify({
1419
+ success: true,
1420
+ mode: 'summary',
1421
+ totalRows: summaryResult.totalRows,
1422
+ columns: summaryResult.columns,
1423
+ columnStats: summaryResult.columnStats,
1424
+ sampleRows: summaryResult.sampleRows,
1425
+ durationMs: result.durationMs,
1426
+ traceSide: traceProvenance.traceSide,
1427
+ traceId: traceProvenance.traceId,
1428
+ traceProvenance,
1429
+ evidenceRefId: emittedEvidence?.evidenceRefId,
1430
+ sourceToolCallId: producer.sourceToolCallId,
1431
+ paramsHash: producer.paramsHash,
1432
+ planPhaseId: producer.planPhaseId,
1433
+ executableSql: finalSql,
1434
+ ...(sqlRewrites.length > 0 ? { sqlRewrites } : {}),
1435
+ stdlibInjectedModules: injected,
1436
+ ...(processIdentityWarning ? { processIdentityWarning } : {}),
1437
+ })) + getReasoningNudge(),
1438
+ }],
1439
+ };
1440
+ }
1441
+ if (emitUpdate && success && result.columns.length > 0) {
1442
+ emittedEvidence = emitSqlDataEnvelope(emitUpdate, result.columns, rows, finalSql, injected, traceProvenance, producer);
1443
+ }
1444
+ else if (emitUpdate && !success) {
1445
+ emittedEvidence = emitSqlDiagnosticDataEnvelope(emitUpdate, result.error || (0, outputLanguage_1.localize)(outputLanguage, 'SQL 执行失败', 'SQL execution failed'), finalSql, injected, traceProvenance, producer, outputLanguage);
1446
+ }
1447
+ return {
1448
+ content: [{
1449
+ type: 'text',
1450
+ text: consumeWatchdogWarning(JSON.stringify({
1451
+ success,
1452
+ columns: result.columns,
1453
+ rows,
1454
+ totalRows: result.rows.length,
1455
+ truncated,
1456
+ durationMs: result.durationMs,
1457
+ traceSide: traceProvenance.traceSide,
1458
+ traceId: traceProvenance.traceId,
1459
+ traceProvenance,
1460
+ evidenceRefId: emittedEvidence?.evidenceRefId,
1461
+ sourceToolCallId: producer.sourceToolCallId,
1462
+ paramsHash: producer.paramsHash,
1463
+ planPhaseId: producer.planPhaseId,
1464
+ executableSql: finalSql,
1465
+ ...(sqlRewrites.length > 0 ? { sqlRewrites } : {}),
1466
+ stdlibInjectedModules: injected,
1467
+ ...(processIdentityWarning ? { processIdentityWarning } : {}),
1468
+ ...(result.error ? { error: result.error } : {}),
1469
+ })) + (success ? getReasoningNudge() : ''),
1470
+ }],
1471
+ };
1472
+ }
1473
+ catch (err) {
1474
+ const errMsg = err.message;
1475
+ const traceProvenance = (0, traceProcessorConnectionModel_1.buildTraceProcessorQueryProvenance)({
1476
+ traceId,
1477
+ traceSide: 'current',
1478
+ });
1479
+ const emittedEvidence = emitUpdate ? emitSqlDiagnosticDataEnvelope(emitUpdate, errMsg, sql, undefined, traceProvenance, producer, outputLanguage) : undefined;
1480
+ emitUpdate?.({
1481
+ type: 'progress',
1482
+ content: {
1483
+ phase: 'analyzing',
1484
+ message: (0, outputLanguage_1.localize)(outputLanguage, `SQL 查询失败: ${errMsg}`, `SQL query failed: ${errMsg}`),
1485
+ },
1486
+ timestamp: Date.now(),
1487
+ });
1488
+ return {
1489
+ content: [{ type: 'text', text: JSON.stringify({
1490
+ success: false,
1491
+ traceSide: 'current',
1492
+ traceId,
1493
+ traceProvenance,
1494
+ evidenceRefId: emittedEvidence?.evidenceRefId,
1495
+ sourceToolCallId: producer.sourceToolCallId,
1496
+ paramsHash: producer.paramsHash,
1497
+ planPhaseId: producer.planPhaseId,
1498
+ error: errMsg,
1499
+ }) }],
1500
+ isError: true,
1501
+ };
1502
+ }
1503
+ }, { annotations: { readOnlyHint: true } });
1504
+ const invokeSkill = (0, claude_agent_sdk_1.tool)('invoke_skill', 'Execute a named SmartPerfetto skill pipeline against the current trace. ' +
1505
+ 'Skills are pre-built analysis routines that produce layered results (overview → list → diagnosis → deep). ' +
1506
+ 'Use list_skills first to find the right skill ID.\n\n' +
1507
+ 'Use when: a pre-built skill covers your analysis need — always prefer this over raw SQL for supported scenarios.\n' +
1508
+ 'Don\'t use when: you need a custom query not covered by any skill (use execute_sql), or exploring what skills exist (use list_skills).\n\n' +
1509
+ 'Examples:\n' +
1510
+ '1. Full scrolling analysis: skillId="scrolling_analysis", params={process_name: "com.example.app"}\n' +
1511
+ '2. Single jank frame detail: skillId="jank_frame_detail", params={frame_number: 42, process_name: "com.example.app"}\n' +
1512
+ '3. Startup analysis: skillId="startup_analysis", params={process_name: "com.example.app"}', {
1513
+ skillId: zod_1.z.string().describe('Skill identifier (e.g. "scrolling_analysis", "jank_frame_detail", "cpu_analysis")'),
1514
+ params: zod_1.z.record(zod_1.z.string(), zod_1.z.any()).optional().describe('Optional parameters to pass to the skill. Common: { process_name, start_ts, end_ts, max_frames_per_session }'),
1515
+ }, async ({ skillId, params }) => {
1516
+ // P0-G10: Block analysis tools until plan is submitted
1517
+ const skillPlanError = requirePlan('invoke_skill');
1518
+ if (skillPlanError) {
1519
+ return { content: [{ type: 'text', text: skillPlanError }] };
1520
+ }
1521
+ if (skillId === 'detect_architecture') {
1522
+ const effectiveParams = normalizeSkillParams(params, packageName);
1523
+ const producer = createEvidenceProducerContext('invoke_skill', { skillId, params: effectiveParams }, (0, outputLanguage_1.localize)(outputLanguage, '调用 Skill detect_architecture,确认渲染架构并决定后续分析链路。', 'Run Skill detect_architecture to identify the rendering pipeline for later analysis.'));
1524
+ try {
1525
+ emitUpdate?.({
1526
+ type: 'progress',
1527
+ content: {
1528
+ phase: 'analyzing',
1529
+ message: (0, outputLanguage_1.localize)(outputLanguage, '检测渲染架构...', 'Detecting rendering architecture...'),
1530
+ },
1531
+ timestamp: Date.now(),
1532
+ });
1533
+ const payload = await detectArchitecturePayload();
1534
+ emitUpdate?.({
1535
+ type: 'progress',
1536
+ content: {
1537
+ phase: 'analyzing',
1538
+ message: (0, outputLanguage_1.localize)(outputLanguage, `架构检测完成: ${String(payload.type ?? 'unknown')} (置信度 ${Math.round(Number(payload.confidence ?? 0) * 100)}%)`, `Architecture detection completed: ${String(payload.type ?? 'unknown')} (${Math.round(Number(payload.confidence ?? 0) * 100)}% confidence)`),
1539
+ },
1540
+ timestamp: Date.now(),
1541
+ });
1542
+ return {
1543
+ content: [{
1544
+ type: 'text',
1545
+ text: consumeWatchdogWarning(JSON.stringify({
1546
+ success: true,
1547
+ skillId: 'detect_architecture',
1548
+ delegatedTool: 'detect_architecture',
1549
+ sourceToolCallId: producer.sourceToolCallId,
1550
+ paramsHash: producer.paramsHash,
1551
+ planPhaseId: producer.planPhaseId,
1552
+ ...payload,
1553
+ })) + getReasoningNudge(),
1554
+ }],
1555
+ };
1556
+ }
1557
+ catch (err) {
1558
+ const errMsg = err.message;
1559
+ return {
1560
+ content: [{ type: 'text', text: JSON.stringify({
1561
+ success: false,
1562
+ skillId,
1563
+ sourceToolCallId: producer.sourceToolCallId,
1564
+ paramsHash: producer.paramsHash,
1565
+ planPhaseId: producer.planPhaseId,
1566
+ error: errMsg,
1567
+ }) }],
1568
+ isError: true,
1569
+ };
1570
+ }
1571
+ }
1572
+ // Guard: metadata-only skills are not executable single-trace analysis skills
1573
+ const skillDef = skillLoader_1.skillRegistry.getSkill(skillId);
1574
+ if (skillDef?.type === 'pipeline_definition' || skillDef?.type === 'comparison') {
1575
+ const useHint = skillDef.type === 'comparison'
1576
+ ? 'It describes analysis result comparison. Use the multi-trace comparison API/tools instead.'
1577
+ : 'Use `detect_architecture` to detect the rendering pipeline, or call a composite analysis skill like `scrolling_analysis`, `gpu_analysis`, etc.';
1578
+ return {
1579
+ content: [{
1580
+ type: 'text',
1581
+ text: JSON.stringify({
1582
+ success: false,
1583
+ error: `Skill "${skillId}" is metadata-only and cannot be used for single-trace analysis. ${useHint}`,
1584
+ }),
1585
+ }],
1586
+ };
1587
+ }
1588
+ try {
1589
+ const effectiveParams = normalizeSkillParams(params, packageName);
1590
+ const producer = createEvidenceProducerContext('invoke_skill', { skillId, params: effectiveParams }, (0, outputLanguage_1.localize)(outputLanguage, `调用 Skill ${skillId},收集本阶段结构化证据。`, `Run Skill ${skillId} to collect structured evidence for this phase.`));
1591
+ emitUpdate?.({
1592
+ type: 'progress',
1593
+ content: {
1594
+ phase: 'analyzing',
1595
+ message: (0, outputLanguage_1.localize)(outputLanguage, `运行分析技能: ${skillId}...`, `Running analysis skill: ${skillId}...`),
1596
+ },
1597
+ timestamp: Date.now(),
1598
+ });
1599
+ const skillStart = Date.now();
1600
+ const result = await skillExecutor.execute(skillId, traceId, effectiveParams);
1601
+ const skillDuration = Date.now() - skillStart;
1602
+ emitUpdate?.({
1603
+ type: 'progress',
1604
+ content: {
1605
+ phase: 'analyzing',
1606
+ message: (0, outputLanguage_1.localize)(outputLanguage, `技能 ${skillId} 完成 (${skillDuration}ms, ${result.displayResults?.length || 0} 个结果层)`, `Skill ${skillId} completed (${skillDuration}ms, ${result.displayResults?.length || 0} result layers)`),
1607
+ },
1608
+ timestamp: Date.now(),
1609
+ });
1610
+ // Capture skill SQL errors in the learning system — skill SQL is the most complex
1611
+ // and most likely to break across Perfetto versions.
1612
+ // P1-3: Also persist to disk for cross-session learning (same as execute_sql errors).
1613
+ if (!result.success && result.error && result.error.includes('SQL')) {
1614
+ const errorPair = {
1615
+ errorSql: `[skill:${skillId}] ${JSON.stringify(effectiveParams)}`,
1616
+ errorMessage: result.error,
1617
+ timestamp: Date.now(),
1618
+ };
1619
+ recentSqlErrors.push(errorPair);
1620
+ if (recentSqlErrors.length > 10)
1621
+ recentSqlErrors.shift();
1622
+ // Persist to disk (fire-and-forget) for cross-session learning
1623
+ logSqlErrorFixPair(errorPair, knowledgeScope).catch(() => { });
1624
+ }
1625
+ if (emitUpdate && result.displayResults?.length) {
1626
+ emitSkillDataEnvelopes(result.displayResults, result.skillId || skillId, emitUpdate, undefined, producer);
1627
+ }
1628
+ if (onSkillResult && result.success && result.displayResults?.length) {
1629
+ onSkillResult({ skillId: result.skillId || skillId, displayResults: result.displayResults });
1630
+ }
1631
+ // Prepend skill notes when the per-analysis budget allows. Notes
1632
+ // only attach on the success path so a failed skill doesn't pollute
1633
+ // the agent's context with unrelated guidance.
1634
+ let skillNotesPrefix = '';
1635
+ if (skillNotesBudget && result.success) {
1636
+ try {
1637
+ const candidates = (0, skillNotesInjector_1.loadSkillNotes)(result.skillId || skillId);
1638
+ if (candidates.length > 0) {
1639
+ const consumed = skillNotesBudget.tryConsume(result.skillId || skillId, candidates);
1640
+ if (consumed)
1641
+ skillNotesPrefix = `${consumed.text}\n\n`;
1642
+ }
1643
+ }
1644
+ catch (err) {
1645
+ console.warn('[invoke_skill] skill notes injection failed:', err.message);
1646
+ }
1647
+ }
1648
+ // Vendor override hint: if a vendor is detected and overrides exist for this skill,
1649
+ // include a hint in the result so Claude can consider vendor-specific analysis steps.
1650
+ let vendorOverrideHint;
1651
+ const detectedVendor = options.cachedVendor;
1652
+ if (detectedVendor && detectedVendor !== 'aosp' && result.success) {
1653
+ const vendorOverride = skillLoader_1.skillRegistry.getVendorOverride(skillId, detectedVendor);
1654
+ if (vendorOverride && vendorOverride.additionalSteps.length > 0) {
1655
+ vendorOverrideHint = {
1656
+ vendor: vendorOverride.vendor,
1657
+ displayName: vendorOverride.displayName,
1658
+ additionalStepIds: vendorOverride.additionalSteps
1659
+ .map((s) => s.id || s.name)
1660
+ .filter(Boolean),
1661
+ };
1662
+ }
1663
+ }
1664
+ // Artifact mode: store displayResults AND synthesizeData as artifacts, return compact references
1665
+ if (artifactStore && result.displayResults?.length) {
1666
+ const artifacts = result.displayResults.map(dr => {
1667
+ const artId = artifactStore.store({
1668
+ skillId: result.skillId || skillId,
1669
+ stepId: dr.stepId,
1670
+ layer: dr.layer,
1671
+ title: dr.title,
1672
+ data: dr.data,
1673
+ diagnostics: undefined,
1674
+ planPhaseId: producer.planPhaseId,
1675
+ planPhaseTitle: producer.planPhaseTitle,
1676
+ planPhaseGoal: producer.planPhaseGoal,
1677
+ sourceToolCallId: producer.sourceToolCallId,
1678
+ paramsHash: producer.paramsHash,
1679
+ });
1680
+ const summary = artifactStore.generateCompactSummary(artId);
1681
+ return summary;
1682
+ });
1683
+ // Store diagnostics as a separate artifact if present
1684
+ let diagnosticsArtifactId;
1685
+ if (result.diagnostics && Array.isArray(result.diagnostics) && result.diagnostics.length > 0) {
1686
+ diagnosticsArtifactId = artifactStore.store({
1687
+ skillId: result.skillId || skillId,
1688
+ stepId: '_diagnostics',
1689
+ layer: 'diagnosis',
1690
+ title: `${skillId} diagnostics`,
1691
+ data: { columns: ['diagnostic'], rows: result.diagnostics.map((d) => [d]) },
1692
+ diagnostics: result.diagnostics,
1693
+ planPhaseId: producer.planPhaseId,
1694
+ planPhaseTitle: producer.planPhaseTitle,
1695
+ planPhaseGoal: producer.planPhaseGoal,
1696
+ sourceToolCallId: producer.sourceToolCallId,
1697
+ paramsHash: producer.paramsHash,
1698
+ });
1699
+ }
1700
+ // Store synthesizeData entries as artifacts too — these contain the raw step data
1701
+ // (e.g. batch_frame_root_cause with 487 rows) that would otherwise overflow token limits.
1702
+ // Claude can fetch them on demand via fetch_artifact with pagination.
1703
+ let synthesizeArtifacts;
1704
+ if (result.synthesizeData && Array.isArray(result.synthesizeData) && result.synthesizeData.length > 0) {
1705
+ synthesizeArtifacts = result.synthesizeData
1706
+ .filter((sd) => sd.data && sd.success !== false)
1707
+ .map((sd) => {
1708
+ // synthesizeData entries have data as array-of-objects or { columns, rows }
1709
+ const normalizedData = normalizeSynthesizeDataForStorage(sd.data);
1710
+ const artId = artifactStore.store({
1711
+ skillId: result.skillId || skillId,
1712
+ stepId: sd.stepId,
1713
+ layer: sd.layer || 'synthesize',
1714
+ title: sd.stepName || sd.stepId,
1715
+ data: normalizedData,
1716
+ planPhaseId: producer.planPhaseId,
1717
+ planPhaseTitle: producer.planPhaseTitle,
1718
+ planPhaseGoal: producer.planPhaseGoal,
1719
+ sourceToolCallId: producer.sourceToolCallId,
1720
+ paramsHash: producer.paramsHash,
1721
+ });
1722
+ return {
1723
+ artifactId: artId,
1724
+ stepId: sd.stepId,
1725
+ rowCount: normalizedData.rows?.length ?? 0,
1726
+ columns: normalizedData.columns ?? [],
1727
+ };
1728
+ });
1729
+ }
1730
+ return {
1731
+ content: [{
1732
+ type: 'text',
1733
+ text: skillNotesPrefix + consumeWatchdogWarning(JSON.stringify({
1734
+ success: result.success,
1735
+ skillId: result.skillId,
1736
+ skillName: result.skillName,
1737
+ ...(result.error ? { error: result.error } : {}),
1738
+ artifacts,
1739
+ ...(diagnosticsArtifactId ? { diagnosticsArtifactId } : {}),
1740
+ ...(synthesizeArtifacts && synthesizeArtifacts.length > 0
1741
+ ? { synthesizeArtifacts }
1742
+ : {}),
1743
+ ...(vendorOverrideHint ? { vendorOverride: vendorOverrideHint } : {}),
1744
+ hint: 'Use fetch_artifact(artifactId=<id>, detail="rows", offset=0, limit=50) to page through large datasets. All data is accessible — use offset/limit to paginate.',
1745
+ })) + (result.success ? getReasoningNudge() : ''),
1746
+ }],
1747
+ };
1748
+ }
1749
+ // Default: return full displayResults (backward compatible)
1750
+ return {
1751
+ content: [{
1752
+ type: 'text',
1753
+ text: skillNotesPrefix + consumeWatchdogWarning(JSON.stringify({
1754
+ success: result.success,
1755
+ skillId: result.skillId,
1756
+ skillName: result.skillName,
1757
+ ...(result.error ? { error: result.error } : {}),
1758
+ ...(vendorOverrideHint ? { vendorOverride: vendorOverrideHint } : {}),
1759
+ displayResults: result.displayResults?.map(dr => ({
1760
+ stepId: dr.stepId,
1761
+ title: dr.title,
1762
+ layer: dr.layer,
1763
+ data: dr.data,
1764
+ })),
1765
+ diagnostics: result.diagnostics,
1766
+ synthesizeData: result.synthesizeData,
1767
+ })) + (result.success ? getReasoningNudge() : ''),
1768
+ }],
1769
+ };
1770
+ }
1771
+ catch (err) {
1772
+ const errMsg = err.message;
1773
+ emitUpdate?.({
1774
+ type: 'progress',
1775
+ content: {
1776
+ phase: 'analyzing',
1777
+ message: (0, outputLanguage_1.localize)(outputLanguage, `技能 ${skillId} 执行失败: ${errMsg}`, `Skill ${skillId} failed: ${errMsg}`),
1778
+ },
1779
+ timestamp: Date.now(),
1780
+ });
1781
+ return {
1782
+ content: [{ type: 'text', text: JSON.stringify({ success: false, error: errMsg }) }],
1783
+ isError: true,
1784
+ };
1785
+ }
1786
+ }, { annotations: { readOnlyHint: true } });
1787
+ const listSkills = (0, claude_agent_sdk_1.tool)('list_skills', 'List all available SmartPerfetto analysis skills. ' +
1788
+ 'Use this to discover which skills exist before invoking one. ' +
1789
+ 'Filter by category to narrow results (e.g. "scrolling", "startup", "cpu", "memory").', {
1790
+ category: zod_1.z.string().optional().describe('Optional filter: only return skills whose keywords or tags match this category'),
1791
+ }, async ({ category }) => {
1792
+ try {
1793
+ const allSkills = await skillAdapter.listSkills();
1794
+ const filtered = category
1795
+ ? allSkills.filter(s => s.keywords.some(k => k.toLowerCase().includes(category.toLowerCase())) ||
1796
+ s.tags?.some(t => t.toLowerCase().includes(category.toLowerCase())) ||
1797
+ s.id.toLowerCase().includes(category.toLowerCase()))
1798
+ : allSkills;
1799
+ return {
1800
+ content: [{
1801
+ type: 'text',
1802
+ text: JSON.stringify(filtered.map(s => ({
1803
+ id: s.id,
1804
+ displayName: s.displayName,
1805
+ description: s.description,
1806
+ type: s.type,
1807
+ keywords: s.keywords.slice(0, 5),
1808
+ }))),
1809
+ }],
1810
+ };
1811
+ }
1812
+ catch (err) {
1813
+ return {
1814
+ content: [{ type: 'text', text: JSON.stringify({ success: false, error: err.message }) }],
1815
+ isError: true,
1816
+ };
1817
+ }
1818
+ }, { annotations: { readOnlyHint: true } });
1819
+ const detectArchitecture = (0, claude_agent_sdk_1.tool)('detect_architecture', 'Detect the rendering architecture of the app in the current trace. ' +
1820
+ 'Returns architecture type (STANDARD/FLUTTER/COMPOSE/WEBVIEW/etc.), confidence, and evidence. ' +
1821
+ 'Call this early to understand which analysis approach to use.', {}, async () => {
1822
+ const producer = createEvidenceProducerContext('detect_architecture', {}, (0, outputLanguage_1.localize)(outputLanguage, '检测渲染架构,确定后续分析路径。', 'Detect rendering architecture to choose the later analysis path.'));
1823
+ try {
1824
+ const payload = await detectArchitecturePayload();
1825
+ return {
1826
+ content: [{
1827
+ type: 'text',
1828
+ text: JSON.stringify({
1829
+ ...payload,
1830
+ sourceToolCallId: producer.sourceToolCallId,
1831
+ paramsHash: producer.paramsHash,
1832
+ planPhaseId: producer.planPhaseId,
1833
+ }),
1834
+ }],
1835
+ };
1836
+ }
1837
+ catch (err) {
1838
+ return {
1839
+ content: [{ type: 'text', text: JSON.stringify({
1840
+ success: false,
1841
+ sourceToolCallId: producer.sourceToolCallId,
1842
+ paramsHash: producer.paramsHash,
1843
+ planPhaseId: producer.planPhaseId,
1844
+ error: err.message,
1845
+ }) }],
1846
+ isError: true,
1847
+ };
1848
+ }
1849
+ }, { annotations: { readOnlyHint: true } });
1850
+ const lookupSqlSchema = (0, claude_agent_sdk_1.tool)('lookup_sql_schema', 'Search the Perfetto SQL stdlib index for table, view, and function definitions matching a keyword. ' +
1851
+ 'Use this to discover available SQL entities before writing raw SQL queries.\n\n' +
1852
+ 'Use when: you need to find table/view/function names before writing SQL, or verifying column names exist.\n' +
1853
+ 'Don\'t use when: you already know the exact table name, or need the full stdlib module list (use list_stdlib_modules).\n\n' +
1854
+ 'Examples:\n' +
1855
+ '1. Find frame-related tables: keyword="frame_timeline"\n' +
1856
+ '2. Find binder tables: keyword="binder"\n' +
1857
+ '3. Find thread state columns: keyword="thread_state"', {
1858
+ keyword: zod_1.z.string().describe('Search keyword (e.g. "jank", "slice", "thread_state", "android_frames")'),
1859
+ }, async ({ keyword }) => {
1860
+ const schema = loadSqlSchema();
1861
+ const lower = keyword.toLowerCase();
1862
+ const docResults = (0, perfettoSqlDocs_1.searchPerfettoSqlDocs)(keyword, { limit: 30 });
1863
+ // P2-G8: Token-based fuzzy matching — split keyword into tokens and match independently
1864
+ const tokens = lower.split(/[\s_]+/).filter(t => t.length >= 2);
1865
+ // Scoring function: exact substring match scores highest, token prefix matches next
1866
+ function scoreEntry(t) {
1867
+ const name = t.name.toLowerCase();
1868
+ const cat = t.category.toLowerCase();
1869
+ const desc = t.description.toLowerCase();
1870
+ const searchable = `${name} ${cat} ${desc}`;
1871
+ // Exact substring match (original behavior)
1872
+ if (name.includes(lower) || cat.includes(lower) || desc.includes(lower))
1873
+ return 10;
1874
+ // Token-based matching: count how many query tokens match
1875
+ if (tokens.length <= 1)
1876
+ return 0;
1877
+ let matchedTokens = 0;
1878
+ for (const tok of tokens) {
1879
+ if (searchable.includes(tok))
1880
+ matchedTokens++;
1881
+ // Prefix match on name segments (e.g., "frame_time" matches "frame_timeline")
1882
+ else if (name.split('_').some(seg => seg.startsWith(tok)))
1883
+ matchedTokens += 0.5;
1884
+ }
1885
+ return matchedTokens >= tokens.length * 0.5 ? matchedTokens : 0;
1886
+ }
1887
+ const scored = schema.templates
1888
+ .map(t => ({ entry: t, score: scoreEntry(t) }))
1889
+ .filter(s => s.score > 0)
1890
+ .sort((a, b) => b.score - a.score);
1891
+ const merged = new Map();
1892
+ for (const result of docResults) {
1893
+ const key = `${result.entry.module}\n${result.entry.name}\n${result.entry.type}`;
1894
+ merged.set(key, {
1895
+ score: result.score + 1000,
1896
+ source: 'stdlib_docs',
1897
+ entry: compactSqlDocEntry(result.entry),
1898
+ });
1899
+ }
1900
+ for (const legacy of scored) {
1901
+ const module = legacy.entry.module || '';
1902
+ const key = `${module}\n${legacy.entry.name}\n${legacy.entry.type}`;
1903
+ if (merged.has(key))
1904
+ continue;
1905
+ merged.set(key, {
1906
+ score: legacy.score,
1907
+ source: 'legacy_index',
1908
+ entry: compactLegacySqlSchemaEntry(legacy.entry),
1909
+ });
1910
+ }
1911
+ const entries = Array.from(merged.values())
1912
+ .sort((a, b) => b.score - a.score)
1913
+ .slice(0, 30)
1914
+ .map(item => ({ ...item.entry, source: item.source }));
1915
+ return {
1916
+ content: [{
1917
+ type: 'text',
1918
+ text: JSON.stringify({
1919
+ totalMatches: entries.length,
1920
+ sources: {
1921
+ stdlibDocs: docResults.length,
1922
+ legacyIndex: scored.length,
1923
+ },
1924
+ entries,
1925
+ }),
1926
+ }],
1927
+ };
1928
+ }, { annotations: { readOnlyHint: true } });
1929
+ // Conditional tool: write_analysis_note (only available when analysisNotes array is provided)
1930
+ const MAX_NOTES = 20;
1931
+ const writeAnalysisNote = analysisNotes ? (0, claude_agent_sdk_1.tool)('write_analysis_note', 'Persist a structured analysis note that survives context compression. ' +
1932
+ 'Use this for important cross-domain observations, hypotheses, or findings that you want to reference later. ' +
1933
+ 'Do NOT overuse — only record observations that would be lost if context is compressed.', {
1934
+ section: zod_1.z.enum(['hypothesis', 'finding', 'observation', 'next_step']).describe('Note category: hypothesis (untested theory), finding (confirmed result), observation (data point), next_step (planned action)'),
1935
+ content: zod_1.z.string().describe('The note content — be specific, include data references'),
1936
+ priority: zod_1.z.enum(['high', 'medium', 'low']).optional().describe('Priority for retention when notes exceed limit. Default: medium'),
1937
+ }, async ({ section, content, priority }) => {
1938
+ const note = { section, content, priority: priority || 'medium', timestamp: Date.now() };
1939
+ analysisNotes.push(note);
1940
+ // Evict notes when over limit.
1941
+ // Priority order: next_step (ephemeral) → low (oldest first) → medium (oldest first) → oldest high
1942
+ if (analysisNotes.length > MAX_NOTES) {
1943
+ const priorityRank = { low: 0, medium: 1, high: 2 };
1944
+ // Find the best candidate to evict: lowest priority, then oldest timestamp
1945
+ let evictIdx = -1;
1946
+ let evictRank = Infinity;
1947
+ let evictTs = Infinity;
1948
+ for (let i = 0; i < analysisNotes.length; i++) {
1949
+ const n = analysisNotes[i];
1950
+ // Always prefer evicting next_step (ephemeral planning notes)
1951
+ if (n.section === 'next_step') {
1952
+ evictIdx = i;
1953
+ break;
1954
+ }
1955
+ const rank = priorityRank[n.priority] ?? 1;
1956
+ if (rank < evictRank || (rank === evictRank && n.timestamp < evictTs)) {
1957
+ evictRank = rank;
1958
+ evictTs = n.timestamp;
1959
+ evictIdx = i;
1960
+ }
1961
+ }
1962
+ if (evictIdx >= 0)
1963
+ analysisNotes.splice(evictIdx, 1);
1964
+ }
1965
+ return {
1966
+ content: [{
1967
+ type: 'text',
1968
+ text: JSON.stringify({ success: true, totalNotes: analysisNotes.length, section, priority: priority || 'medium' }),
1969
+ }],
1970
+ };
1971
+ }) : null;
1972
+ // Conditional tool: fetch_artifact (only available when artifactStore is provided)
1973
+ const fetchArtifact = artifactStore ? (0, claude_agent_sdk_1.tool)('fetch_artifact', 'Retrieve detailed data for a previously stored artifact from invoke_skill results. ' +
1974
+ 'Supports pagination for large datasets — use offset/limit to page through rows without token overflow. ' +
1975
+ 'Response includes totalRows and hasMore to guide pagination. ALL data is accessible; nothing is hidden.\n\n' +
1976
+ 'Use when: you need detailed data from a previous invoke_skill result (artifacts are referenced by ID in skill responses).\n' +
1977
+ 'Don\'t use when: you need new data (use invoke_skill or execute_sql instead).\n' +
1978
+ 'Always set purpose to one short sentence explaining why this artifact is needed for the current plan phase.\n\n' +
1979
+ 'Examples:\n' +
1980
+ '1. Get summary of skill result: artifactId="art-1", detail="summary"\n' +
1981
+ '2. Page through jank frames: artifactId="art-2", detail="rows", offset=0, limit=50\n' +
1982
+ '3. Get next page: artifactId="art-2", detail="rows", offset=50, limit=50', {
1983
+ artifactId: zod_1.z.string().describe('Artifact ID (e.g. "art-1") from a previous invoke_skill response'),
1984
+ detail: zod_1.z.enum(['summary', 'rows', 'full']).optional().describe('Detail level: summary (default, compact stats), rows (paginated data rows), full (complete original structure — use with caution on large artifacts)'),
1985
+ offset: zod_1.z.coerce.number().int().min(0).optional().describe('Row offset for pagination (detail="rows" only). Default: 0. Use with limit to page through large datasets.'),
1986
+ limit: zod_1.z.coerce.number().int().min(1).max(200).optional().describe('Maximum rows to return (detail="rows" only). Default: 50. Increase up to 200 if you need more rows per page.'),
1987
+ purpose: zod_1.z.string().optional().describe('One short sentence explaining why this artifact is needed for the current plan phase. Used in the user-visible timeline.'),
1988
+ }, async ({ artifactId, detail, offset, limit, purpose }) => {
1989
+ const effectiveDetail = detail || 'summary';
1990
+ const normalizedOffset = coerceOptionalInteger(offset, 'offset', { min: 0 });
1991
+ const normalizedLimit = coerceOptionalInteger(limit, 'limit', { min: 1, max: 200 });
1992
+ const paginationErrors = [normalizedOffset.error, normalizedLimit.error].filter(Boolean);
1993
+ const producerReason = purpose || (0, outputLanguage_1.localize)(outputLanguage, '读取前序证据表的明细数据,用于当前阶段判断。', 'Read detailed rows from a previous evidence artifact for the current phase.');
1994
+ if (paginationErrors.length > 0) {
1995
+ const producer = createEvidenceProducerContext('fetch_artifact', { artifactId, detail: effectiveDetail, offset, limit, purpose }, producerReason);
1996
+ return {
1997
+ content: [{ type: 'text', text: JSON.stringify({
1998
+ success: false,
1999
+ error: `Invalid pagination arguments: ${paginationErrors.join('; ')}`,
2000
+ }) }],
2001
+ isError: true,
2002
+ };
2003
+ }
2004
+ const result = artifactStore.fetch(artifactId, effectiveDetail, normalizedOffset.value, normalizedLimit.value);
2005
+ const originPhase = result?.planPhaseId
2006
+ ? {
2007
+ phaseId: result.planPhaseId,
2008
+ phaseTitle: result.planPhaseTitle,
2009
+ phaseGoal: result.planPhaseGoal,
2010
+ attribution: 'inferred',
2011
+ }
2012
+ : undefined;
2013
+ const producer = createEvidenceProducerContext('fetch_artifact', {
2014
+ artifactId,
2015
+ detail: effectiveDetail,
2016
+ offset,
2017
+ limit,
2018
+ purpose,
2019
+ artifactPlanPhaseId: result?.planPhaseId,
2020
+ artifactPlanPhaseTitle: result?.planPhaseTitle,
2021
+ artifactTitle: result?.title,
2022
+ artifactStepId: result?.stepId,
2023
+ }, producerReason, undefined, originPhase);
2024
+ if (!result) {
2025
+ return {
2026
+ content: [{ type: 'text', text: JSON.stringify({
2027
+ success: false,
2028
+ error: `Artifact ${artifactId} not found — it may have been evicted (LRU cap: 50) or lost after a backend restart. Use invoke_skill to re-execute the skill if you need this data again.`,
2029
+ sourceToolCallId: producer.sourceToolCallId,
2030
+ paramsHash: producer.paramsHash,
2031
+ planPhaseId: producer.planPhaseId,
2032
+ }) }],
2033
+ isError: true,
2034
+ };
2035
+ }
2036
+ // Phase 3-4 of v2.1 — high-risk path recitation. `full` and `rows` detail
2037
+ // levels return large payloads that push the agent's working memory; in
2038
+ // those cases append a one-line plan reminder so the agent doesn't drift
2039
+ // away from the active phase's constraints. Summary mode skips the
2040
+ // reminder (compact responses already keep the agent on-track).
2041
+ const reminder = (effectiveDetail === 'full' || effectiveDetail === 'rows')
2042
+ ? (0, activePhaseReminder_1.buildActivePhaseReminder)(analysisPlanRef?.current, options.sceneType)
2043
+ : '';
2044
+ const payload = JSON.stringify({
2045
+ success: true,
2046
+ detail: effectiveDetail,
2047
+ ...result,
2048
+ sourceToolCallId: producer.sourceToolCallId,
2049
+ paramsHash: producer.paramsHash,
2050
+ planPhaseId: producer.planPhaseId,
2051
+ planPhaseTitle: producer.planPhaseTitle,
2052
+ planPhaseGoal: producer.planPhaseGoal,
2053
+ planPhaseAttribution: producer.planPhaseAttribution,
2054
+ sourceArtifactId: artifactId,
2055
+ ...(purpose ? { purpose } : {}),
2056
+ });
2057
+ return {
2058
+ content: [{
2059
+ type: 'text',
2060
+ text: reminder ? payload + reminder : payload,
2061
+ }],
2062
+ };
2063
+ }, { annotations: { readOnlyHint: true } }) : null;
2064
+ // list_stdlib_modules: Expose Perfetto stdlib module inventory to the agent.
2065
+ // Enables Claude to discover available stdlib modules by namespace (e.g., "android.frames", "sched").
2066
+ const listStdlibModules = (0, claude_agent_sdk_1.tool)('list_stdlib_modules', 'List available Perfetto SQL stdlib modules by namespace. Use this to discover what pre-built tables, views, and functions ' +
2067
+ 'are available before writing custom SQL. Modules can be loaded via INCLUDE PERFETTO MODULE <name> in SQL queries. ' +
2068
+ 'Core modules (android.frames.timeline, android.startup.startups, android.binder) are pre-loaded; ' +
2069
+ 'others load on-demand via skill prerequisites or INCLUDE PERFETTO MODULE in your SQL.', {
2070
+ namespace: zod_1.z.string().optional().describe('Filter by namespace prefix (e.g., "android", "android.frames", "sched", "chrome", "wattson"). Omit to list all.'),
2071
+ }, async ({ namespace }) => {
2072
+ const allModules = (0, perfettoStdlibScanner_1.getPerfettoStdlibModules)();
2073
+ const docsModules = (0, perfettoSqlDocs_1.listPerfettoSqlModuleDocs)(namespace);
2074
+ // Enforce dot-boundary matching to avoid "android" matching a hypothetical "androidos.*"
2075
+ const filtered = namespace
2076
+ ? allModules.filter(m => m === namespace || m.startsWith(namespace + '.'))
2077
+ : allModules;
2078
+ // Group by top-level namespace
2079
+ const grouped = {};
2080
+ for (const mod of filtered) {
2081
+ const ns = mod.split('.')[0];
2082
+ if (!grouped[ns])
2083
+ grouped[ns] = [];
2084
+ grouped[ns].push(mod);
2085
+ }
2086
+ return {
2087
+ content: [{
2088
+ type: 'text',
2089
+ text: JSON.stringify({
2090
+ totalModules: filtered.length,
2091
+ namespaces: Object.keys(grouped).sort(),
2092
+ // When filtering by namespace, return full module list.
2093
+ // When unfiltered, return only counts per namespace to save context tokens (~1500 tokens).
2094
+ modules: namespace
2095
+ ? filtered.sort()
2096
+ : Object.fromEntries(Object.entries(grouped).map(([ns, mods]) => [ns, mods.length])),
2097
+ moduleDocs: namespace
2098
+ ? docsModules.slice(0, 50).map(mod => ({
2099
+ module: mod.module,
2100
+ description: mod.moduleDoc,
2101
+ tags: mod.tags,
2102
+ includes: mod.includes,
2103
+ transitiveIncludes: mod.transitiveIncludes,
2104
+ symbols: mod.symbols.slice(0, 30),
2105
+ missingIncludes: mod.missingIncludes,
2106
+ errors: mod.errors,
2107
+ sourcePath: mod.sourcePath,
2108
+ }))
2109
+ : undefined,
2110
+ hint: namespace
2111
+ ? 'Use lookup_sql_schema to find specific tables/views/functions within a module.'
2112
+ : 'Call again with a namespace (e.g., "android.frames") to see full module list. ' +
2113
+ 'Critical modules (android.frames.*, android.binder*, android.startup.*, sched.*) are pre-loaded.',
2114
+ }),
2115
+ }],
2116
+ };
2117
+ }, { annotations: { readOnlyHint: true } });
2118
+ // lookup_knowledge: Load background knowledge on performance analysis topics on demand.
2119
+ // The agent calls this when it needs to explain a root cause mechanism to the user.
2120
+ // Topics are auto-discovered from knowledge-*.template.md files in the strategies directory.
2121
+ const knowledgeTopics = (() => {
2122
+ const strategiesDir = path.resolve(__dirname, '../../../strategies');
2123
+ try {
2124
+ return fs.readdirSync(strategiesDir)
2125
+ .filter(f => f.startsWith('knowledge-') && f.endsWith('.template.md'))
2126
+ .map(f => f.replace('knowledge-', '').replace('.template.md', ''))
2127
+ .sort();
2128
+ }
2129
+ catch {
2130
+ return ['rendering-pipeline', 'binder-ipc', 'gc-dynamics', 'cpu-scheduler', 'thermal-throttling', 'lock-contention'];
2131
+ }
2132
+ })();
2133
+ const lookupKnowledge = (0, claude_agent_sdk_1.tool)('lookup_knowledge', 'Load background knowledge about a performance analysis topic. Use this when you discover a root cause ' +
2134
+ 'and want to explain the underlying mechanism to the user. Returns concise explanations of how the ' +
2135
+ 'system works, common trace signatures, and typical solutions. ' +
2136
+ `Available topics: ${knowledgeTopics.join(', ')}.`, {
2137
+ topic: zod_1.z.string().describe(`Knowledge topic: ${knowledgeTopics.map(t => `"${t}"`).join(' | ')}`),
2138
+ }, async ({ topic }) => {
2139
+ const content = (0, strategyLoader_1.loadPromptTemplate)('knowledge-' + topic);
2140
+ if (!content) {
2141
+ return {
2142
+ content: [{
2143
+ type: 'text',
2144
+ text: JSON.stringify({
2145
+ success: false,
2146
+ error: `Unknown topic "${topic}". Available: ${knowledgeTopics.join(', ')}`,
2147
+ }),
2148
+ }],
2149
+ isError: true,
2150
+ };
2151
+ }
2152
+ return {
2153
+ content: [{ type: 'text', text: content }],
2154
+ };
2155
+ }, { annotations: { readOnlyHint: true } });
2156
+ // lookup_blog_knowledge (Plan 55): retrieve indexed chunks from
2157
+ // androidperformance.com (and, once Plan 44 lands, world memory).
2158
+ // Read-only — calls ragStore.search() which never writes. The index
2159
+ // is populated by the M2 admin route + ingester; until then the
2160
+ // search returns `unsupportedReason='index empty'` so the agent
2161
+ // never invents content.
2162
+ const lookupBlogKnowledge = (0, claude_agent_sdk_1.tool)('lookup_blog_knowledge', 'Retrieve indexed knowledge chunks from androidperformance.com to ground analysis claims in published material. ' +
2163
+ 'Returns ranked snippets matching the query plus provenance (chunkId, uri, title, author) so the agent can cite. ' +
2164
+ 'When the result carries an `unsupportedReason` (e.g. "index empty", "all chunks blocked by unsupportedReason"), ' +
2165
+ 'the agent must say the source is unavailable and must NOT summarize, paraphrase, or invent content from this source.', {
2166
+ query: zod_1.z.string().describe('Search query — natural language is fine; tokens are lowercased and matched against snippet + title.'),
2167
+ top_k: zod_1.z.number().int().min(1).max(20).optional().describe('Maximum hits returned (1-20, default 5).'),
2168
+ }, async ({ query, top_k }) => {
2169
+ const store = getRagStore();
2170
+ const result = store.search(query, {
2171
+ topK: top_k ?? 5,
2172
+ kinds: ['androidperformance.com'],
2173
+ scope: knowledgeScope,
2174
+ });
2175
+ return {
2176
+ content: [{ type: 'text', text: JSON.stringify(result) }],
2177
+ };
2178
+ }, { annotations: { readOnlyHint: true } });
2179
+ // lookup_baseline (Plan 50): fetch a stored App/Device/Build/CUJ
2180
+ // baseline by id or by composite key. Read-only — no store mutation.
2181
+ // The agent uses this to pull the canonical "what this app/device
2182
+ // historically does" record before making regression claims.
2183
+ const lookupBaseline = (0, claude_agent_sdk_1.tool)('lookup_baseline', 'Fetch a stored App/Device/Build/CUJ baseline. ' +
2184
+ 'Pass either `baseline_id` (canonical "appId/deviceId/buildId/cuj") OR all four key components. ' +
2185
+ 'Returns the BaselineRecord with metrics, status, redactionState, and curatorNote. ' +
2186
+ 'When the baseline does not exist, the result carries `success: false` and the agent must NOT fabricate baseline values.', {
2187
+ baseline_id: zod_1.z.string().optional().describe('Canonical baselineId, e.g. "com.example.feed/pixel-9-android-15/main-abc/scroll_feed".'),
2188
+ app_id: zod_1.z.string().optional().describe('Component appId; required when baseline_id is omitted.'),
2189
+ device_id: zod_1.z.string().optional().describe('Component deviceId; required when baseline_id is omitted.'),
2190
+ build_id: zod_1.z.string().optional().describe('Component buildId; required when baseline_id is omitted.'),
2191
+ cuj: zod_1.z.string().optional().describe('Component CUJ id; required when baseline_id is omitted.'),
2192
+ }, async ({ baseline_id, app_id, device_id, build_id, cuj }) => {
2193
+ const store = getBaselineStore();
2194
+ let id = baseline_id;
2195
+ if (!id) {
2196
+ if (app_id && device_id && build_id && cuj) {
2197
+ id = (0, baselineStore_1.deriveBaselineId)({ appId: app_id, deviceId: device_id, buildId: build_id, cuj });
2198
+ }
2199
+ else {
2200
+ return {
2201
+ content: [{
2202
+ type: 'text',
2203
+ text: JSON.stringify({
2204
+ success: false,
2205
+ error: 'Provide either `baseline_id` or all four key components (app_id, device_id, build_id, cuj).',
2206
+ }),
2207
+ }],
2208
+ isError: true,
2209
+ };
2210
+ }
2211
+ }
2212
+ const baseline = store.getBaseline(id, knowledgeScope);
2213
+ if (!baseline) {
2214
+ return {
2215
+ content: [{
2216
+ type: 'text',
2217
+ text: JSON.stringify({ success: false, error: `Baseline '${id}' not found` }),
2218
+ }],
2219
+ };
2220
+ }
2221
+ return {
2222
+ content: [{ type: 'text', text: JSON.stringify({ success: true, baseline }) }],
2223
+ };
2224
+ }, { annotations: { readOnlyHint: true } });
2225
+ // compare_baselines (Plan 50): diff two stored baselines and
2226
+ // optionally evaluate a CI-style regression gate. Read-only —
2227
+ // computes from the stored baselines without mutating either.
2228
+ // Trace-vs-baseline (compare_to_baseline) is deferred until the
2229
+ // trace metric extraction pipeline is built.
2230
+ const compareBaselines = (0, claude_agent_sdk_1.tool)('compare_baselines', 'Diff two stored baselines and (optionally) evaluate a regression gate. ' +
2231
+ 'Returns a BaselineDiffArtifact with per-metric deltas plus an optional RegressionGateResult when `rules` are supplied. ' +
2232
+ 'Per-metric `severity` is one of none / info / warning / regression / unsupported; consult `unsupportedReason` whenever severity is "unsupported" — the agent must NOT treat unsupported metrics as confirming or refuting a regression claim.', {
2233
+ base_baseline_id: zod_1.z.string().describe('Canonical baselineId for the historical/reference side.'),
2234
+ candidate_baseline_id: zod_1.z.string().describe('Canonical baselineId for the candidate/new side.'),
2235
+ rules: zod_1.z.array(zod_1.z.object({
2236
+ metric_id: zod_1.z.string().describe('Metric id to gate on.'),
2237
+ threshold: zod_1.z.number().describe('Maximum allowed absolute fractional delta. 0.10 == 10%.'),
2238
+ expect_increase: zod_1.z.boolean().optional().describe('When false, gate fails on improvements (must-decrease metrics). Defaults to true.'),
2239
+ })).optional().describe('Optional gate rules. When supplied a RegressionGateResult is returned alongside the diff.'),
2240
+ gate_id: zod_1.z.string().optional().describe('Stable id for the gate result. Required when `rules` is supplied; otherwise ignored.'),
2241
+ }, async ({ base_baseline_id, candidate_baseline_id, rules, gate_id }) => {
2242
+ const store = getBaselineStore();
2243
+ const base = store.getBaseline(base_baseline_id, knowledgeScope);
2244
+ const candidate = store.getBaseline(candidate_baseline_id, knowledgeScope);
2245
+ if (!base) {
2246
+ return {
2247
+ content: [{
2248
+ type: 'text',
2249
+ text: JSON.stringify({ success: false, error: `Base baseline '${base_baseline_id}' not found` }),
2250
+ }],
2251
+ };
2252
+ }
2253
+ if (!candidate) {
2254
+ return {
2255
+ content: [{
2256
+ type: 'text',
2257
+ text: JSON.stringify({ success: false, error: `Candidate baseline '${candidate_baseline_id}' not found` }),
2258
+ }],
2259
+ };
2260
+ }
2261
+ const diff = (0, baselineDiffer_1.computeBaselineDiff)(base, candidate);
2262
+ let gate = undefined;
2263
+ if (rules && rules.length > 0) {
2264
+ if (!gate_id) {
2265
+ return {
2266
+ content: [{
2267
+ type: 'text',
2268
+ text: JSON.stringify({ success: false, error: '`gate_id` is required when `rules` is supplied.' }),
2269
+ }],
2270
+ isError: true,
2271
+ };
2272
+ }
2273
+ const mappedRules = rules.map(r => ({
2274
+ metricId: r.metric_id,
2275
+ threshold: r.threshold,
2276
+ ...(r.expect_increase !== undefined ? { expectIncrease: r.expect_increase } : {}),
2277
+ }));
2278
+ gate = (0, baselineDiffer_1.evaluateRegressionGate)(base_baseline_id, diff, mappedRules, { gateId: gate_id });
2279
+ }
2280
+ return {
2281
+ content: [{
2282
+ type: 'text',
2283
+ text: JSON.stringify({ success: true, diff, ...(gate ? { gate } : {}) }),
2284
+ }],
2285
+ };
2286
+ }, { annotations: { readOnlyHint: true } });
2287
+ // lookup_aosp_source (Plan 55 M1): retrieve indexed AOSP source
2288
+ // chunks. Public read-only. License gate at ingestion guarantees
2289
+ // every retrieved chunk carries an explicit license; the agent
2290
+ // contract still applies — when the result is `unsupportedReason
2291
+ // === 'license_blocked'` (or empty index), do NOT summarize, do
2292
+ // NOT cite as evidence, say the source is unavailable.
2293
+ const lookupAospSource = (0, claude_agent_sdk_1.tool)('lookup_aosp_source', 'Retrieve indexed AOSP source chunks (frameworks/base, system/, etc.) to ground analysis claims in the actual implementation. ' +
2294
+ 'Returns ranked snippets with license + commit-anchored chunkId. ' +
2295
+ 'When the result carries `unsupportedReason` (license_blocked, index empty), the agent must say the source is unavailable and must NOT summarize, paraphrase, or invent content.', {
2296
+ query: zod_1.z.string().describe('Search query — typically a function or class name, or a behavior description.'),
2297
+ top_k: zod_1.z.number().int().min(1).max(20).optional().describe('Maximum hits returned (1-20, default 5).'),
2298
+ }, async ({ query, top_k }) => {
2299
+ const store = getRagStore();
2300
+ const result = store.search(query, {
2301
+ topK: top_k ?? 5,
2302
+ kinds: ['aosp'],
2303
+ scope: knowledgeScope,
2304
+ });
2305
+ return {
2306
+ content: [{ type: 'text', text: JSON.stringify(result) }],
2307
+ };
2308
+ }, { annotations: { readOnlyHint: true } });
2309
+ // lookup_oem_sdk (Plan 55 M2): retrieve indexed OEM SDK chunks
2310
+ // (MTK / Qualcomm / Samsung tuning docs etc.). Public read-only.
2311
+ // Same agent contract as lookup_aosp_source: blocked / empty
2312
+ // results must NOT be paraphrased or fabricated.
2313
+ const lookupOemSdk = (0, claude_agent_sdk_1.tool)('lookup_oem_sdk', 'Retrieve indexed OEM SDK / tuning documentation chunks. Optionally restrict by vendor via the URI prefix (`oem://<vendor>/...`). ' +
2314
+ 'Read-only over the RagStore. When the result carries `unsupportedReason` (license_blocked, index empty), the agent must say the source is unavailable and must NOT summarize or invent.', {
2315
+ query: zod_1.z.string().describe('Search query — typically a tuning concept or vendor-specific knob.'),
2316
+ top_k: zod_1.z.number().int().min(1).max(20).optional().describe('Maximum hits returned (1-20, default 5).'),
2317
+ }, async ({ query, top_k }) => {
2318
+ const store = getRagStore();
2319
+ const result = store.search(query, {
2320
+ topK: top_k ?? 5,
2321
+ kinds: ['oem_sdk'],
2322
+ scope: knowledgeScope,
2323
+ });
2324
+ return {
2325
+ content: [{ type: 'text', text: JSON.stringify(result) }],
2326
+ };
2327
+ }, { annotations: { readOnlyHint: true } });
2328
+ // recall_project_memory (Plan 44): pure-read recall over project +
2329
+ // world memory entries. Strict invariant: handler MUST NOT cause any
2330
+ // disk writes; ProjectMemory.recallProjectMemory() is enforced via
2331
+ // the "1000 calls / mtime unchanged" unit test in projectMemory.test.ts.
2332
+ // Use this when the agent wants to ground claims in past analysis
2333
+ // insights for the same project (or in world-scope insights consolidated
2334
+ // by reviewer approval). The session-scope `recall_patterns` tool is a
2335
+ // separate path that runs against the existing analysisPatternMemory store.
2336
+ const recallProjectMemory = (0, claude_agent_sdk_1.tool)('recall_project_memory', 'Recall project- or world-scope memory entries by tag overlap with the query. Read-only — never writes. ' +
2337
+ 'Returns up to top_k hits ranked by tag-overlap score; entries with `unsupportedReason` (evicted, retracted) are skipped. ' +
2338
+ 'Session-scope memory lives elsewhere (use `recall_patterns` for that path).', {
2339
+ tags: zod_1.z.array(zod_1.z.string()).optional().describe('Tags to score against. Without tags, entries rank by their stored confidence.'),
2340
+ project_key: zod_1.z.string().optional().describe('Restrict to entries created under this project key (e.g. "appId/deviceId").'),
2341
+ scope: zod_1.z.enum(['project', 'world']).optional().describe('Restrict to a scope. Defaults to both project and world.'),
2342
+ top_k: zod_1.z.number().int().min(1).max(20).optional().describe('Maximum hits returned (1-20, default 5).'),
2343
+ }, async ({ tags, project_key, scope, top_k }) => {
2344
+ const memory = getProjectMemory();
2345
+ const hits = memory.recallProjectMemory({
2346
+ tags,
2347
+ projectKey: project_key,
2348
+ scope,
2349
+ topK: top_k ?? 5,
2350
+ }, knowledgeScope);
2351
+ return {
2352
+ content: [{
2353
+ type: 'text',
2354
+ text: JSON.stringify({ success: true, hits, count: hits.length }),
2355
+ }],
2356
+ };
2357
+ }, { annotations: { readOnlyHint: true } });
2358
+ // recall_similar_case (Plan 54): pure-read recall over the case
2359
+ // library. The agent uses this to ground claims in prior curated
2360
+ // cases ("similar root cause to case-...") instead of repeating
2361
+ // analysis. Read-only. Note: `cite_case_in_report` (the session-side
2362
+ // writer counterpart) is intentionally deferred — it requires
2363
+ // deeper integration with the report generation path and lands as
2364
+ // its own commit later.
2365
+ const recallSimilarCase = (0, claude_agent_sdk_1.tool)('recall_similar_case', 'Recall published or reviewed cases that share tags with the current trace, optionally restricted to the same App/Device/Build/CUJ key. ' +
2366
+ 'Read-only over the case library. Returns up to top_k cases ranked by tag-overlap score; published cases rank above reviewed when scores tie. ' +
2367
+ 'When the result is empty the agent must NOT fabricate prior cases — say "no matching prior case in the library" explicitly.', {
2368
+ tags: zod_1.z.array(zod_1.z.string()).optional().describe('Tag tokens to score against. Without tags, results rank by published > reviewed > others.'),
2369
+ app_id: zod_1.z.string().optional().describe('Restrict to cases whose key.appId matches.'),
2370
+ device_id: zod_1.z.string().optional().describe('Restrict to cases whose key.deviceId matches.'),
2371
+ cuj: zod_1.z.string().optional().describe('Restrict to cases whose key.cuj matches.'),
2372
+ include_unpublished: zod_1.z.boolean().optional().describe('Include reviewed/draft cases (default false — only published surface to the agent).'),
2373
+ top_k: zod_1.z.number().int().min(1).max(20).optional().describe('Maximum cases returned (1-20, default 5).'),
2374
+ }, async ({ tags, app_id, device_id, cuj, include_unpublished, top_k }) => {
2375
+ const library = getCaseLibrary();
2376
+ const wantedTags = tags ? new Set(tags) : null;
2377
+ const limit = top_k ?? 5;
2378
+ // Pull either published-only or published+reviewed depending on the
2379
+ // include_unpublished flag. Drafts and private cases never surface
2380
+ // through this tool — those are operator-side concerns.
2381
+ const allCases = include_unpublished
2382
+ ? [
2383
+ ...library.listCases({ status: 'published' }, knowledgeScope),
2384
+ ...library.listCases({ status: 'reviewed' }, knowledgeScope),
2385
+ ]
2386
+ : library.listCases({ status: 'published' }, knowledgeScope);
2387
+ const candidates = [];
2388
+ for (const c of allCases) {
2389
+ if (app_id && c.key?.appId !== app_id)
2390
+ continue;
2391
+ if (device_id && c.key?.deviceId !== device_id)
2392
+ continue;
2393
+ if (cuj && c.key?.cuj !== cuj)
2394
+ continue;
2395
+ let score = 0;
2396
+ if (wantedTags) {
2397
+ for (const t of c.tags)
2398
+ if (wantedTags.has(t))
2399
+ score += 1;
2400
+ if (score === 0)
2401
+ continue;
2402
+ score = score / Math.max(wantedTags.size, 1);
2403
+ }
2404
+ else {
2405
+ // Without tags, prefer published over reviewed; both above 0.
2406
+ score = c.status === 'published' ? 1 : 0.5;
2407
+ }
2408
+ candidates.push({ caseScore: score, case: c });
2409
+ }
2410
+ candidates.sort((a, b) => {
2411
+ if (a.caseScore !== b.caseScore)
2412
+ return b.caseScore - a.caseScore;
2413
+ // Tie-break: published before reviewed before others.
2414
+ const rank = (s) => s === 'published' ? 0 : s === 'reviewed' ? 1 : 2;
2415
+ return rank(a.case.status) - rank(b.case.status);
2416
+ });
2417
+ const hits = candidates.slice(0, limit).map(c => ({
2418
+ caseId: c.case.caseId,
2419
+ score: c.caseScore,
2420
+ title: c.case.title,
2421
+ status: c.case.status,
2422
+ tags: c.case.tags,
2423
+ findings: c.case.findings,
2424
+ traceArtifactId: c.case.traceArtifactId,
2425
+ traceUnavailableReason: c.case.traceUnavailableReason,
2426
+ }));
2427
+ return {
2428
+ content: [{
2429
+ type: 'text',
2430
+ text: JSON.stringify({ success: true, hits, count: hits.length }),
2431
+ }],
2432
+ };
2433
+ }, { annotations: { readOnlyHint: true } });
2434
+ // query_perfetto_source: Search the Perfetto stdlib for SQL patterns and usage examples.
2435
+ // Enables Claude to self-learn by finding how official code uses tables/functions.
2436
+ const queryPerfettoSource = (0, claude_agent_sdk_1.tool)('query_perfetto_source', 'Search the Perfetto SQL stdlib source code for usage patterns. Packaged builds fall back to the bundled SQL schema index when the source tree is unavailable. Use this when you encounter an unfamiliar table/function, get an SQL error, or need to find how the official codebase uses a specific table or column.', {
2437
+ keyword: zod_1.z.string().describe('Search keyword (table name, function name, column name, or SQL pattern)'),
2438
+ max_results: zod_1.z.number().optional().describe('Maximum number of matching files to return (default: 5)'),
2439
+ }, async ({ keyword, max_results }) => {
2440
+ const maxFiles = max_results ?? 5;
2441
+ const stdlibDir = (0, perfettoStdlibScanner_1.getPerfettoStdlibPath)();
2442
+ const docsMatches = (0, perfettoSqlDocs_1.searchPerfettoSqlDocs)(keyword, { limit: maxFiles });
2443
+ const compactDocs = docsMatches.map(result => compactSqlDocEntry(result.entry));
2444
+ if (!fs.existsSync(stdlibDir)) {
2445
+ const lowerKeyword = keyword.toLowerCase();
2446
+ const schema = loadSqlSchema();
2447
+ const results = schema.templates
2448
+ .filter(t => {
2449
+ const searchable = `${t.name} ${t.category} ${t.description ?? ''}`.toLowerCase();
2450
+ return searchable.includes(lowerKeyword);
2451
+ })
2452
+ .slice(0, maxFiles)
2453
+ .map(t => ({
2454
+ file: t.id,
2455
+ matches: [
2456
+ [
2457
+ `name: ${t.name}`,
2458
+ `category: ${t.category}`,
2459
+ `type: ${t.type ?? 'unknown'}`,
2460
+ `description: ${t.description ?? ''}`,
2461
+ ].join('\n'),
2462
+ ],
2463
+ }));
2464
+ return {
2465
+ content: [{
2466
+ type: 'text',
2467
+ text: JSON.stringify({
2468
+ success: true,
2469
+ keyword,
2470
+ source: 'bundled_schema_index',
2471
+ docs: compactDocs,
2472
+ matchedFiles: results.length,
2473
+ results: results.map(r => ({
2474
+ file: r.file,
2475
+ matchCount: r.matches.length,
2476
+ matches: r.matches,
2477
+ })),
2478
+ note: 'Perfetto stdlib source tree is unavailable in this runtime; returned bundled schema-index matches instead.',
2479
+ }),
2480
+ }],
2481
+ };
2482
+ }
2483
+ try {
2484
+ const results = [];
2485
+ const lowerKeyword = keyword.toLowerCase();
2486
+ // Recursively search .sql files (async to avoid blocking event loop)
2487
+ const searchDir = async (dir) => {
2488
+ if (results.length >= maxFiles)
2489
+ return;
2490
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
2491
+ for (const entry of entries) {
2492
+ if (results.length >= maxFiles)
2493
+ return;
2494
+ const fullPath = path.join(dir, entry.name);
2495
+ if (entry.isDirectory()) {
2496
+ await searchDir(fullPath);
2497
+ }
2498
+ else if (entry.name.endsWith('.sql')) {
2499
+ const content = await fs.promises.readFile(fullPath, 'utf-8');
2500
+ if (content.toLowerCase().includes(lowerKeyword)) {
2501
+ const relPath = path.relative(stdlibDir, fullPath);
2502
+ const lines = content.split('\n');
2503
+ const matchLines = [];
2504
+ for (let i = 0; i < lines.length; i++) {
2505
+ if (lines[i].toLowerCase().includes(lowerKeyword)) {
2506
+ // Include 1 line of context before and after
2507
+ const start = Math.max(0, i - 1);
2508
+ const end = Math.min(lines.length - 1, i + 1);
2509
+ const context = lines.slice(start, end + 1)
2510
+ .map((l, j) => `${start + j + 1}: ${l}`)
2511
+ .join('\n');
2512
+ matchLines.push(context);
2513
+ if (matchLines.length >= 8)
2514
+ break; // Cap matches per file
2515
+ }
2516
+ }
2517
+ results.push({ file: relPath, matches: matchLines });
2518
+ }
2519
+ }
2520
+ }
2521
+ };
2522
+ await searchDir(stdlibDir);
2523
+ return {
2524
+ content: [{
2525
+ type: 'text',
2526
+ text: JSON.stringify({
2527
+ success: true,
2528
+ keyword,
2529
+ source: 'stdlib_source',
2530
+ docs: compactDocs,
2531
+ matchedFiles: results.length,
2532
+ results: results.map(r => ({
2533
+ file: r.file,
2534
+ matchCount: r.matches.length,
2535
+ matches: r.matches,
2536
+ })),
2537
+ }),
2538
+ }],
2539
+ };
2540
+ }
2541
+ catch (err) {
2542
+ return {
2543
+ content: [{ type: 'text', text: JSON.stringify({ success: false, error: err.message }) }],
2544
+ isError: true,
2545
+ };
2546
+ }
2547
+ }, { annotations: { readOnlyHint: true } });
2548
+ // P1-G11: Scene plan templates extracted to `./scenePlanTemplates` (Phase 0.2 of
2549
+ // v2.1). The previous inline `'touch-tracking'` key (hyphen) silently disabled
2550
+ // hard-gate for the touch_tracking scene because strategy frontmatter uses
2551
+ // underscore-form `scene: touch_tracking`; coverage test now guards this.
2552
+ // Planning tools: submit_plan + update_plan_phase (P0-1: Explicit planning capability)
2553
+ // analysisPlanRef is declared above (P0-G10) and shared with planning tools
2554
+ const submitPlan = analysisPlanRef ? (0, claude_agent_sdk_1.tool)('submit_plan', 'Submit your structured analysis plan BEFORE starting any analysis. ' +
2555
+ 'Define phases with goals and expected tools. The system tracks plan adherence and warns on deviation. ' +
2556
+ 'You MUST call this tool as your first action in every analysis.\n\n' +
2557
+ 'Use when: starting any new analysis — this is mandatory before execute_sql or invoke_skill.\n' +
2558
+ 'Don\'t use when: plan already submitted (use revise_plan to modify, update_plan_phase to track progress).\n\n' +
2559
+ 'Examples:\n' +
2560
+ '1. Scrolling plan: phases=[{id:"p1", name:"概览采集", goal:"获取帧统计和卡顿分布", expectedTools:["invoke_skill"]}, ' +
2561
+ '{id:"p2", name:"根因分析", goal:"逐帧诊断卡顿原因", expectedTools:["invoke_skill","execute_sql"]}, ' +
2562
+ '{id:"p3", name:"深入验证", goal:"验证根因假设", expectedTools:["execute_sql","fetch_artifact"]}], ' +
2563
+ 'successCriteria="识别卡顿根因并提供量化证据"', {
2564
+ phases: zod_1.z.array(zod_1.z.object({
2565
+ id: zod_1.z.string().describe('Phase identifier (e.g. "p1", "p2")'),
2566
+ name: zod_1.z.string().describe('Phase name (e.g. "Overview Collection")'),
2567
+ goal: zod_1.z.string().describe('What this phase aims to achieve'),
2568
+ expectedTools: zod_1.z.array(zod_1.z.string()).describe('Tool names this phase will use (e.g. ["invoke_skill", "execute_sql"])'),
2569
+ expectedCalls: zod_1.z.array(zod_1.z.object({
2570
+ tool: zod_1.z.string().describe('Short tool name without prefix (e.g. "invoke_skill")'),
2571
+ skillId: zod_1.z.string().optional().describe('For invoke_skill, the required skillId'),
2572
+ })).optional().describe('Optional structured matchers — preferred over expectedTools when set. Use to require a specific skillId, e.g. [{tool:"invoke_skill", skillId:"startup_slow_reasons"}].'),
2573
+ })).min(1).describe('Ordered list of analysis phases (at least 1 phase required)'),
2574
+ successCriteria: zod_1.z.string().describe('What constitutes a successful analysis (e.g. "Identify root cause of jank frames with evidence")'),
2575
+ waivers: zod_1.z.array(zod_1.z.object({
2576
+ aspectId: zod_1.z.string().describe('Mandatory aspect id to opt out of (matches a `missingAspectIds` entry from a prior reject).'),
2577
+ reason: zod_1.z.string().describe(`Justification for why this aspect cannot be covered. MUST be at least ${scenePlanTemplates_1.MIN_WAIVER_REASON_CHARS} characters.`),
2578
+ })).optional().describe('Optional opt-outs for scene-template aspects when the trace genuinely cannot support them.'),
2579
+ }, async ({ phases, successCriteria, waivers }) => {
2580
+ const phaseInputs = parseToolArrayInput(phases);
2581
+ if (!phaseInputs) {
2582
+ return {
2583
+ content: [{
2584
+ type: 'text',
2585
+ text: JSON.stringify({
2586
+ success: false,
2587
+ error: (0, outputLanguage_1.localize)(outputLanguage, 'submit_plan 参数 phases 必须是数组或 JSON 数组字符串。', 'submit_plan argument phases must be an array or JSON array string.'),
2588
+ }),
2589
+ }],
2590
+ isError: true,
2591
+ };
2592
+ }
2593
+ const waiverInputs = parseOptionalToolArrayInput(waivers);
2594
+ if (!waiverInputs) {
2595
+ return {
2596
+ content: [{
2597
+ type: 'text',
2598
+ text: JSON.stringify({
2599
+ success: false,
2600
+ error: (0, outputLanguage_1.localize)(outputLanguage, 'submit_plan 参数 waivers 必须是数组或 JSON 数组字符串。', 'submit_plan argument waivers must be an array or JSON array string.'),
2601
+ }),
2602
+ }],
2603
+ isError: true,
2604
+ };
2605
+ }
2606
+ const normalizedPhases = moveConclusionPhasesLast(phaseInputs.map(normalizePlanPhaseToolInput));
2607
+ // P1-G11: Validate against the scene template, honouring agent waivers.
2608
+ const validation = (0, scenePlanTemplates_1.validatePlanAgainstSceneTemplate)(normalizedPhases, options.sceneType, waiverInputs);
2609
+ const { warnings: planWarnings, missingAspectIds } = validation;
2610
+ // Track only waivers whose reason met the minimum threshold; the rest
2611
+ // are reported back so the agent knows they didn't count.
2612
+ const acceptedWaivers = waiverInputs.filter(w => typeof w.reason === 'string' && w.reason.trim().length >= scenePlanTemplates_1.MIN_WAIVER_REASON_CHARS);
2613
+ const tooShortWaivers = waiverInputs.filter(w => !acceptedWaivers.some(a => a.aspectId === w.aspectId));
2614
+ planSubmitAttempts++;
2615
+ // Phase 2.3: 真硬拦截 — keep rejecting until plan covers all aspects
2616
+ // or supplies a substantial waiver. After MAX_PLAN_ATTEMPTS the gate
2617
+ // gives up and force-accepts, but missing aspects are persisted to
2618
+ // `unresolvedAspects` so `verifyPlanAdherence` still flags the gap.
2619
+ const MAX_PLAN_ATTEMPTS = 5;
2620
+ if (planWarnings.length > 0 && planSubmitAttempts < MAX_PLAN_ATTEMPTS) {
2621
+ console.log(`[MCP] Plan rejected (attempt ${planSubmitAttempts}/${MAX_PLAN_ATTEMPTS}): missing ${missingAspectIds.length} aspects for ${options.sceneType ?? 'unknown scene'}`);
2622
+ return {
2623
+ content: [{
2624
+ type: 'text',
2625
+ text: JSON.stringify({
2626
+ success: false,
2627
+ error: (0, outputLanguage_1.localize)(outputLanguage, `计划缺少 ${options.sceneType ?? '当前'} 场景的必要分析阶段`, `The plan is missing mandatory analysis phases for the ${options.sceneType ?? 'current'} scene`),
2628
+ missingAspectIds,
2629
+ missingAspectSuggestions: planWarnings,
2630
+ attempt: planSubmitAttempts,
2631
+ maxAttempts: MAX_PLAN_ATTEMPTS,
2632
+ tooShortWaivers: tooShortWaivers.length > 0 ? tooShortWaivers : undefined,
2633
+ hint: (0, outputLanguage_1.localize)(outputLanguage, `修复 plan 添加缺失阶段并重新调用 submit_plan,或在 waivers 中给出 ≥${scenePlanTemplates_1.MIN_WAIVER_REASON_CHARS} 字符的理由说明为什么无法覆盖。`, `Add the missing phases and call submit_plan again, or provide a waiver reason of at least ${scenePlanTemplates_1.MIN_WAIVER_REASON_CHARS} characters explaining why it cannot be covered.`),
2634
+ }),
2635
+ }],
2636
+ isError: true,
2637
+ };
2638
+ }
2639
+ const forcedAccept = planWarnings.length > 0; // hit the attempt cap
2640
+ const plan = {
2641
+ phases: normalizedPhases.map((p) => ({
2642
+ ...p,
2643
+ status: 'pending',
2644
+ })),
2645
+ successCriteria,
2646
+ submittedAt: Date.now(),
2647
+ toolCallLog: [],
2648
+ ...(acceptedWaivers.length > 0 ? { waivers: acceptedWaivers } : {}),
2649
+ ...(forcedAccept ? { unresolvedAspects: missingAspectIds } : {}),
2650
+ };
2651
+ analysisPlanRef.current = plan;
2652
+ if (forcedAccept) {
2653
+ console.warn(`[MCP] Plan force-accepted at attempt ${planSubmitAttempts} with ${missingAspectIds.length} unresolved aspects: ${missingAspectIds.join(', ')}`);
2654
+ }
2655
+ emitUpdate?.({
2656
+ type: 'plan_submitted',
2657
+ content: {
2658
+ phases: plan.phases.map(p => ({ id: p.id, name: p.name, goal: p.goal, status: p.status })),
2659
+ successCriteria,
2660
+ },
2661
+ timestamp: Date.now(),
2662
+ });
2663
+ const response = { success: true };
2664
+ if (acceptedWaivers.length > 0) {
2665
+ response.acceptedWaivers = acceptedWaivers.map(w => w.aspectId);
2666
+ }
2667
+ if (tooShortWaivers.length > 0) {
2668
+ response.tooShortWaivers = tooShortWaivers;
2669
+ response.waiverHint = (0, outputLanguage_1.localize)(outputLanguage, `已忽略 ${tooShortWaivers.length} 条理由不足 ${scenePlanTemplates_1.MIN_WAIVER_REASON_CHARS} 字符的 waiver。`, `Ignored ${tooShortWaivers.length} waiver(s) whose reason is shorter than ${scenePlanTemplates_1.MIN_WAIVER_REASON_CHARS} characters.`);
2670
+ }
2671
+ if (forcedAccept) {
2672
+ response.unresolvedAspects = missingAspectIds;
2673
+ response.warning = (0, outputLanguage_1.localize)(outputLanguage, `已强制接受 plan(达到第 ${MAX_PLAN_ATTEMPTS} 次尝试上限),但未覆盖的 aspect 会在最终 verifier 中报错。`, `Plan force-accepted after reaching the ${MAX_PLAN_ATTEMPTS}-attempt limit, but uncovered aspects will be reported by the final verifier.`);
2674
+ }
2675
+ return {
2676
+ content: [{
2677
+ type: 'text',
2678
+ text: JSON.stringify(response),
2679
+ }],
2680
+ };
2681
+ }) : null;
2682
+ const updatePlanPhase = analysisPlanRef ? (0, claude_agent_sdk_1.tool)('update_plan_phase', 'Update the status of a plan phase. Call this when transitioning between phases or when skipping a phase. ' +
2683
+ 'This helps track analysis progress and enables plan adherence verification. ' +
2684
+ 'When completing a phase, you MUST provide a summary with key evidence collected (e.g. "发现 5 帧卡顿,主因是 RenderThread 阻塞,最长耗时 45ms"). ' +
2685
+ 'When skipping, explain why (e.g. "trace 中无启动数据,跳过启动分析").', {
2686
+ phaseId: zod_1.z.string().describe('Phase ID to update (e.g. "p1")'),
2687
+ status: zod_1.z.enum(['in_progress', 'completed', 'skipped', 'active']).describe('New phase status. "active" is accepted as an alias for "in_progress".'),
2688
+ summary: zod_1.z.string().optional().describe('REQUIRED for completed/skipped: key evidence or reason. Must include specific data (numbers, names, findings).'),
2689
+ }, async ({ phaseId, status, summary }) => {
2690
+ const plan = analysisPlanRef.current;
2691
+ if (!plan) {
2692
+ return {
2693
+ content: [{
2694
+ type: 'text',
2695
+ text: JSON.stringify({
2696
+ success: false,
2697
+ error: (0, outputLanguage_1.localize)(outputLanguage, '还没有提交 plan,请先调用 submit_plan。', 'No plan submitted yet. Call submit_plan first.'),
2698
+ }),
2699
+ }],
2700
+ isError: true,
2701
+ };
2702
+ }
2703
+ const phase = plan.phases.find(p => p.id === phaseId);
2704
+ if (!phase) {
2705
+ return {
2706
+ content: [{
2707
+ type: 'text',
2708
+ text: JSON.stringify({
2709
+ success: false,
2710
+ error: (0, outputLanguage_1.localize)(outputLanguage, `plan 中没有找到阶段 "${phaseId}"`, `Phase "${phaseId}" not found in plan`),
2711
+ }),
2712
+ }],
2713
+ isError: true,
2714
+ };
2715
+ }
2716
+ const trimmedSummary = summary?.trim();
2717
+ const normalizedStatus = status === 'active' ? 'in_progress' : status;
2718
+ if ((normalizedStatus === 'completed' || normalizedStatus === 'skipped') &&
2719
+ (!trimmedSummary || trimmedSummary.length < exports.MIN_PHASE_SUMMARY_CHARS)) {
2720
+ return {
2721
+ content: [{
2722
+ type: 'text',
2723
+ text: JSON.stringify({
2724
+ success: false,
2725
+ error: (0, outputLanguage_1.localize)(outputLanguage, `阶段 ${phaseId} 的 summary 太短。完成/跳过阶段时必须给出具体证据、数据或原因,至少 ${exports.MIN_PHASE_SUMMARY_CHARS} 个字符。`, `Phase ${phaseId} summary is too brief. Completed/skipped phases require concrete evidence, data, or reason with at least ${exports.MIN_PHASE_SUMMARY_CHARS} characters.`),
2726
+ action_required: 'retry_update_plan_phase_with_evidence',
2727
+ }),
2728
+ }],
2729
+ isError: true,
2730
+ };
2731
+ }
2732
+ if (normalizedStatus === 'skipped' && isConclusionLikePlanPhase(phase)) {
2733
+ return {
2734
+ content: [{
2735
+ type: 'text',
2736
+ text: JSON.stringify({
2737
+ success: false,
2738
+ error: (0, outputLanguage_1.localize)(outputLanguage, `阶段 ${phaseId} 是最终结论阶段,不能标记为 skipped。请先补齐必要证据,然后将该阶段标记为 completed,并输出最终结论。`, `Phase ${phaseId} is the final conclusion phase and cannot be skipped. Collect the required evidence first, then mark it completed and produce the final conclusion.`),
2739
+ action_required: 'complete_final_conclusion_phase',
2740
+ currentPhaseId: phase.id,
2741
+ currentPhaseName: phase.name,
2742
+ }),
2743
+ }],
2744
+ isError: true,
2745
+ };
2746
+ }
2747
+ const semanticMismatch = findPhaseSemanticMismatch(plan, phase, trimmedSummary);
2748
+ if (semanticMismatch) {
2749
+ return {
2750
+ content: [{
2751
+ type: 'text',
2752
+ text: JSON.stringify({
2753
+ success: false,
2754
+ error: (0, outputLanguage_1.localize)(outputLanguage, `阶段 ${phaseId} 是「${phase.name}」,但 summary 更像「${PHASE_SEMANTIC_LABELS[semanticMismatch.summaryKind]}」。请改用阶段 ${semanticMismatch.suggestedPhase.id}(${semanticMismatch.suggestedPhase.name})或重写 summary。`, `Phase ${phaseId} is "${phase.name}", but the summary looks like "${PHASE_SEMANTIC_LABELS[semanticMismatch.summaryKind]}". Use phase ${semanticMismatch.suggestedPhase.id} (${semanticMismatch.suggestedPhase.name}) or rewrite the summary.`),
2755
+ action_required: 'retry_update_plan_phase_with_correct_phase',
2756
+ currentPhaseId: phase.id,
2757
+ currentPhaseName: phase.name,
2758
+ suggestedPhaseId: semanticMismatch.suggestedPhase.id,
2759
+ suggestedPhaseName: semanticMismatch.suggestedPhase.name,
2760
+ detectedSummaryKind: semanticMismatch.summaryKind,
2761
+ }),
2762
+ }],
2763
+ isError: true,
2764
+ };
2765
+ }
2766
+ if (normalizedStatus === 'in_progress') {
2767
+ closeSupersededInProgressPhases(plan, phase);
2768
+ phase.completedAt = undefined;
2769
+ phase.summary = undefined;
2770
+ }
2771
+ phase.status = normalizedStatus;
2772
+ if (normalizedStatus === 'completed' || normalizedStatus === 'skipped') {
2773
+ phase.completedAt = Date.now();
2774
+ phase.summary = trimmedSummary;
2775
+ }
2776
+ emitUpdate?.({
2777
+ type: 'plan_phase_updated',
2778
+ content: { phaseId, status: normalizedStatus, summary: trimmedSummary || '', phaseName: phase.name },
2779
+ timestamp: Date.now(),
2780
+ });
2781
+ // Report overall plan progress
2782
+ const allPhasesClosed = plan.phases.every(p => p.status === 'completed' || p.status === 'skipped');
2783
+ const nextPhase = plan.phases.find(p => p.status === 'pending');
2784
+ // Compact return: only include feedback when needed (normal path = minimal ACK)
2785
+ const response = { success: true };
2786
+ if (allPhasesClosed)
2787
+ response.allPhasesComplete = true;
2788
+ // Restatement injection: leverage tool response's high-attention position
2789
+ // to re-state next-phase constraints from strategy frontmatter phase_hints.
2790
+ // Match logic lives in `phaseHintMatcher` so it can be unit tested.
2791
+ const shouldReportNextPhase = normalizedStatus === 'completed' || normalizedStatus === 'skipped';
2792
+ if (shouldReportNextPhase && nextPhase && options.sceneType) {
2793
+ const hints = (0, strategyLoader_1.getPhaseHints)(options.sceneType);
2794
+ const matchedHint = (0, phaseHintMatcher_1.matchPhaseHintForNextPhase)({
2795
+ hints,
2796
+ nextPhase: { name: nextPhase.name, goal: nextPhase.goal },
2797
+ finishedPhases: plan.phases.map(p => ({
2798
+ name: p.name,
2799
+ goal: p.goal,
2800
+ summary: p.summary,
2801
+ status: p.status,
2802
+ })),
2803
+ });
2804
+ if (matchedHint) {
2805
+ response.next_phase_reminder = {
2806
+ phaseId: nextPhase.id,
2807
+ name: nextPhase.name,
2808
+ constraints: matchedHint.constraints,
2809
+ criticalTools: matchedHint.criticalTools,
2810
+ };
2811
+ console.log(`[MCP] Phase hint injected: ${matchedHint.id} for ${options.sceneType}`);
2812
+ }
2813
+ else if (hints.length > 0) {
2814
+ console.log(`[MCP] Phase hint not found for: "${nextPhase.name}" in ${options.sceneType}`);
2815
+ }
2816
+ // Always include basic next phase info for non-hint scenarios
2817
+ if (!response.next_phase_reminder) {
2818
+ response.next = {
2819
+ phaseId: nextPhase.id,
2820
+ name: nextPhase.name,
2821
+ expectedTools: nextPhase.expectedTools,
2822
+ };
2823
+ }
2824
+ }
2825
+ return {
2826
+ content: [{
2827
+ type: 'text',
2828
+ text: JSON.stringify(response),
2829
+ }],
2830
+ };
2831
+ }) : null;
2832
+ // P1-3: Dynamic replan — allows Claude to revise the plan mid-analysis when new information emerges
2833
+ const revisePlan = analysisPlanRef ? (0, claude_agent_sdk_1.tool)('revise_plan', 'Revise your analysis plan mid-execution when new information changes priorities. ' +
2834
+ 'Use this when initial data reveals unexpected conditions (e.g., discovered Flutter architecture but planned for Standard, ' +
2835
+ 'or found ANR signals in a scrolling query). Preserves completed phases and audit trail.', {
2836
+ reason: zod_1.z.string().describe('Why the plan needs revision (what new information triggered this)'),
2837
+ updatedPhases: zod_1.z.array(zod_1.z.object({
2838
+ id: zod_1.z.string().describe('Phase identifier (keep existing IDs for unchanged phases, use new IDs for added phases)'),
2839
+ name: zod_1.z.string().describe('Phase name'),
2840
+ goal: zod_1.z.string().describe('What this phase aims to achieve'),
2841
+ expectedTools: zod_1.z.array(zod_1.z.string()).describe('Tool names this phase will use'),
2842
+ expectedCalls: zod_1.z.array(zod_1.z.object({
2843
+ tool: zod_1.z.string(),
2844
+ skillId: zod_1.z.string().optional(),
2845
+ })).optional().describe('Optional structured matchers — see submit_plan for semantics.'),
2846
+ status: zod_1.z.enum(['pending', 'in_progress', 'completed', 'skipped']).optional()
2847
+ .describe('Phase status. Omit for new/pending phases. Completed/skipped phases from original plan are preserved.'),
2848
+ })).describe('The revised phase list. Must include all completed/in-progress phases from original plan.'),
2849
+ updatedSuccessCriteria: zod_1.z.string().optional().describe('Updated success criteria (only if the goal changed)'),
2850
+ }, async ({ reason, updatedPhases, updatedSuccessCriteria }) => {
2851
+ const updatedPhaseInputs = parseToolArrayInput(updatedPhases);
2852
+ if (!updatedPhaseInputs) {
2853
+ return {
2854
+ content: [{
2855
+ type: 'text',
2856
+ text: JSON.stringify({
2857
+ success: false,
2858
+ error: (0, outputLanguage_1.localize)(outputLanguage, 'revise_plan 参数 updatedPhases 必须是数组或 JSON 数组字符串。', 'revise_plan argument updatedPhases must be an array or JSON array string.'),
2859
+ }),
2860
+ }],
2861
+ isError: true,
2862
+ };
2863
+ }
2864
+ const normalizedUpdatedPhases = moveConclusionPhasesLast(updatedPhaseInputs.map((p) => ({
2865
+ ...normalizePlanPhaseToolInput(p),
2866
+ status: p.status,
2867
+ })));
2868
+ // Reset submit attempts so a revised plan can trigger hard-gate validation again
2869
+ planSubmitAttempts = 0;
2870
+ const plan = analysisPlanRef.current;
2871
+ if (!plan) {
2872
+ return {
2873
+ content: [{
2874
+ type: 'text',
2875
+ text: JSON.stringify({
2876
+ success: false,
2877
+ error: (0, outputLanguage_1.localize)(outputLanguage, '还没有提交 plan,请先调用 submit_plan。', 'No plan submitted yet. Call submit_plan first.'),
2878
+ }),
2879
+ }],
2880
+ isError: true,
2881
+ };
2882
+ }
2883
+ // Validate: completed phases from original plan must be preserved
2884
+ const originalCompleted = plan.phases.filter(p => p.status === 'completed' || p.status === 'skipped');
2885
+ const preservedIds = new Set(normalizedUpdatedPhases.map(p => p.id));
2886
+ const missingCompleted = originalCompleted.filter(p => !preservedIds.has(p.id));
2887
+ if (missingCompleted.length > 0) {
2888
+ return {
2889
+ content: [{
2890
+ type: 'text',
2891
+ text: JSON.stringify({
2892
+ success: false,
2893
+ error: (0, outputLanguage_1.localize)(outputLanguage, `已完成阶段必须保留: ${missingCompleted.map(p => p.id).join(', ')}。请把它们放入 updatedPhases。`, `Completed phases must be preserved: ${missingCompleted.map(p => p.id).join(', ')}. Include them in updatedPhases.`),
2894
+ }),
2895
+ }],
2896
+ isError: true,
2897
+ };
2898
+ }
2899
+ // Save revision history for audit trail
2900
+ const revision = {
2901
+ revisedAt: Date.now(),
2902
+ reason,
2903
+ previousPhases: plan.phases.map(p => ({ ...p })),
2904
+ };
2905
+ if (!plan.revisionHistory)
2906
+ plan.revisionHistory = [];
2907
+ plan.revisionHistory.push(revision);
2908
+ // Apply revision: merge completed phase data (summary, completedAt) with updated structure
2909
+ plan.phases = normalizedUpdatedPhases.map((up) => {
2910
+ const original = plan.phases.find(p => p.id === up.id);
2911
+ if (original && (original.status === 'completed' || original.status === 'skipped')) {
2912
+ // Preserve completed phase data
2913
+ return { ...original };
2914
+ }
2915
+ return {
2916
+ id: up.id,
2917
+ name: up.name,
2918
+ goal: up.goal,
2919
+ expectedTools: up.expectedTools,
2920
+ expectedCalls: up.expectedCalls,
2921
+ status: (up.status || 'pending'),
2922
+ };
2923
+ });
2924
+ if (updatedSuccessCriteria) {
2925
+ plan.successCriteria = updatedSuccessCriteria;
2926
+ }
2927
+ emitUpdate?.({
2928
+ type: 'plan_revised',
2929
+ content: {
2930
+ reason,
2931
+ phases: plan.phases.map(p => ({ id: p.id, name: p.name, goal: p.goal, status: p.status })),
2932
+ revisionCount: plan.revisionHistory.length,
2933
+ },
2934
+ timestamp: Date.now(),
2935
+ });
2936
+ const pending = plan.phases.filter(p => p.status === 'pending');
2937
+ // P1-G11: Run scene-template validation on the revised plan too — otherwise
2938
+ // an agent could submit a compliant plan and then revise mandatory phases
2939
+ // away to bypass the hard-gate. Phase 2.3 will upgrade these warnings to
2940
+ // a real reject when sceneType is known.
2941
+ const { warnings: revisedPlanWarnings } = (0, scenePlanTemplates_1.validatePlanAgainstSceneTemplate)(plan.phases, options.sceneType);
2942
+ const reviseResponse = {
2943
+ success: true,
2944
+ message: (0, outputLanguage_1.localize)(outputLanguage, `Plan 已修订(第 ${plan.revisionHistory.length} 次): ${reason}`, `Plan revised (revision #${plan.revisionHistory.length}): ${reason}`),
2945
+ totalPhases: plan.phases.length,
2946
+ pendingPhases: pending.length,
2947
+ nextPhase: pending[0]?.id,
2948
+ };
2949
+ if (revisedPlanWarnings.length > 0) {
2950
+ reviseResponse.sceneWarnings = revisedPlanWarnings;
2951
+ console.log(`[MCP] Revised plan has ${revisedPlanWarnings.length} unmet aspects for ${options.sceneType ?? 'unknown scene'}`);
2952
+ }
2953
+ return {
2954
+ content: [{
2955
+ type: 'text',
2956
+ text: JSON.stringify(reviseResponse),
2957
+ }],
2958
+ };
2959
+ }) : null;
2960
+ // P0-G4: Hypothesis-verify cycle tools
2961
+ const hypothesesRef = options.hypotheses;
2962
+ let hypothesisCounter = 0;
2963
+ const submitHypothesis = hypothesesRef ? (0, claude_agent_sdk_1.tool)('submit_hypothesis', 'Record a formal hypothesis that needs verification through data. ' +
2964
+ 'Use this when you form a testable theory about the root cause of a performance issue. ' +
2965
+ 'Every hypothesis MUST be resolved (confirmed/rejected with evidence) before concluding.', {
2966
+ id: zod_1.z.string().optional().describe('Optional caller-provided hypothesis ID (e.g., "h1"). If omitted, the system assigns one.'),
2967
+ statement: zod_1.z.string().optional().describe('The hypothesis statement (e.g., "RenderThread is blocked by Binder transactions causing jank frames"). Alias: title.'),
2968
+ title: zod_1.z.string().optional().describe('Alias for statement, accepted for Claude SDK argument compatibility.'),
2969
+ basis: zod_1.z.string().optional().describe('What observation prompted this hypothesis (e.g., "Observed 3 frames with RenderThread in sleeping state"). Alias: reasoning.'),
2970
+ reasoning: zod_1.z.string().optional().describe('Alias for basis, accepted for Claude SDK argument compatibility.'),
2971
+ }, async ({ id, statement, title, basis, reasoning }) => {
2972
+ const effectiveStatement = (statement ?? title)?.trim();
2973
+ const effectiveBasis = (basis ?? reasoning)?.trim();
2974
+ if (!effectiveStatement) {
2975
+ return {
2976
+ content: [{
2977
+ type: 'text',
2978
+ text: JSON.stringify({
2979
+ success: false,
2980
+ error: 'submit_hypothesis requires statement (or title)',
2981
+ }),
2982
+ }],
2983
+ isError: true,
2984
+ };
2985
+ }
2986
+ const requestedId = id?.trim();
2987
+ const existing = requestedId ? hypothesesRef.find(h => h.id === requestedId) : undefined;
2988
+ if (existing) {
2989
+ if (existing.status === 'formed') {
2990
+ existing.statement = effectiveStatement;
2991
+ existing.basis = effectiveBasis;
2992
+ }
2993
+ return {
2994
+ content: [{
2995
+ type: 'text',
2996
+ text: JSON.stringify({
2997
+ success: true,
2998
+ hypothesisId: existing.id,
2999
+ reused: true,
3000
+ }),
3001
+ }],
3002
+ };
3003
+ }
3004
+ const hypothesisId = requestedId || `h${++hypothesisCounter}`;
3005
+ const numericId = /^h(\d+)$/i.exec(hypothesisId);
3006
+ if (numericId) {
3007
+ hypothesisCounter = Math.max(hypothesisCounter, Number(numericId[1]));
3008
+ }
3009
+ const hypothesis = {
3010
+ id: hypothesisId,
3011
+ statement: effectiveStatement,
3012
+ status: 'formed',
3013
+ basis: effectiveBasis,
3014
+ formedAt: Date.now(),
3015
+ };
3016
+ hypothesesRef.push(hypothesis);
3017
+ return {
3018
+ content: [{
3019
+ type: 'text',
3020
+ text: JSON.stringify({
3021
+ success: true,
3022
+ hypothesisId,
3023
+ }),
3024
+ }],
3025
+ };
3026
+ }) : null;
3027
+ const resolveHypothesis = hypothesesRef ? (0, claude_agent_sdk_1.tool)('resolve_hypothesis', 'Resolve a previously submitted hypothesis as confirmed or rejected. ' +
3028
+ 'Provide the evidence that supports your conclusion. ' +
3029
+ 'All hypotheses MUST be resolved before writing your final conclusion.', {
3030
+ hypothesisId: zod_1.z.string().optional().describe('Hypothesis ID to resolve (e.g., "h1"). Alias: id.'),
3031
+ id: zod_1.z.string().optional().describe('Alias for hypothesisId, accepted for Claude SDK argument compatibility.'),
3032
+ status: zod_1.z.enum(['confirmed', 'rejected']).optional().describe('Resolution: confirmed (evidence supports) or rejected (evidence contradicts). Alias: verdict.'),
3033
+ verdict: zod_1.z.enum(['confirmed', 'rejected']).optional().describe('Alias for status, accepted for Claude SDK argument compatibility.'),
3034
+ evidence: zod_1.z.string().describe('The evidence supporting this resolution (specific data, timestamps, tool results)'),
3035
+ }, async ({ hypothesisId, id, status, verdict, evidence }) => {
3036
+ const effectiveHypothesisId = (hypothesisId ?? id)?.trim();
3037
+ const effectiveStatus = status ?? verdict;
3038
+ if (!effectiveHypothesisId || !effectiveStatus) {
3039
+ return {
3040
+ content: [{
3041
+ type: 'text',
3042
+ text: JSON.stringify({
3043
+ success: false,
3044
+ error: 'resolve_hypothesis requires hypothesisId (or id) and status (or verdict)',
3045
+ }),
3046
+ }],
3047
+ isError: true,
3048
+ };
3049
+ }
3050
+ const hypothesis = hypothesesRef.find(h => h.id === effectiveHypothesisId);
3051
+ if (!hypothesis) {
3052
+ const now = Date.now();
3053
+ const backfilled = {
3054
+ id: effectiveHypothesisId,
3055
+ statement: `Backfilled hypothesis ${effectiveHypothesisId}`,
3056
+ status: effectiveStatus,
3057
+ basis: 'resolve_hypothesis was called before submit_hypothesis; preserving the resolution evidence instead of failing the run.',
3058
+ evidence,
3059
+ formedAt: now,
3060
+ resolvedAt: now,
3061
+ };
3062
+ hypothesesRef.push(backfilled);
3063
+ const numericId = /^h(\d+)$/i.exec(effectiveHypothesisId);
3064
+ if (numericId) {
3065
+ hypothesisCounter = Math.max(hypothesisCounter, Number(numericId[1]));
3066
+ }
3067
+ const unresolvedCount = hypothesesRef.filter(h => h.status === 'formed').length;
3068
+ return {
3069
+ content: [{
3070
+ type: 'text',
3071
+ text: JSON.stringify({
3072
+ success: true,
3073
+ hypothesisId: effectiveHypothesisId,
3074
+ status: effectiveStatus,
3075
+ backfilled: true,
3076
+ unresolvedCount,
3077
+ }),
3078
+ }],
3079
+ };
3080
+ }
3081
+ if (hypothesis.status !== 'formed') {
3082
+ return {
3083
+ content: [{ type: 'text', text: JSON.stringify({ success: false, error: `Hypothesis "${effectiveHypothesisId}" already resolved as ${hypothesis.status}` }) }],
3084
+ isError: true,
3085
+ };
3086
+ }
3087
+ hypothesis.status = effectiveStatus;
3088
+ hypothesis.evidence = evidence;
3089
+ hypothesis.resolvedAt = Date.now();
3090
+ const unresolvedCount = hypothesesRef.filter(h => h.status === 'formed').length;
3091
+ return {
3092
+ content: [{
3093
+ type: 'text',
3094
+ text: JSON.stringify({
3095
+ success: true,
3096
+ hypothesisId: effectiveHypothesisId,
3097
+ status: effectiveStatus,
3098
+ unresolvedCount,
3099
+ }),
3100
+ }],
3101
+ };
3102
+ }) : null;
3103
+ // ── P1-G1: flag_uncertainty — non-blocking human interaction ──
3104
+ const uncertaintyFlagsRef = options.uncertaintyFlags;
3105
+ const flagUncertainty = uncertaintyFlagsRef ? (0, claude_agent_sdk_1.tool)('flag_uncertainty', 'Signal that you are uncertain about an aspect and making an assumption to proceed. ' +
3106
+ 'Use this when you encounter ambiguity (e.g., unclear which process is the focus app, ' +
3107
+ 'multiple possible root causes, unclear user intent). Analysis continues without blocking — ' +
3108
+ 'the user sees your flag and can provide clarification in the next turn.', {
3109
+ topic: zod_1.z.string().describe('What aspect you are uncertain about'),
3110
+ assumption: zod_1.z.string().describe('What assumption you are making to proceed'),
3111
+ question: zod_1.z.string().describe('What you would ask the user if you could'),
3112
+ }, async ({ topic, assumption, question }) => {
3113
+ const flag = { topic, assumption, question, timestamp: Date.now() };
3114
+ uncertaintyFlagsRef.push(flag);
3115
+ // Emit as SSE event so the user sees it in real-time
3116
+ emitUpdate?.({
3117
+ type: 'progress',
3118
+ content: {
3119
+ phase: 'analyzing',
3120
+ message: (0, outputLanguage_1.localize)(outputLanguage, `⚠️ 不确定性标记: ${topic}\n假设: ${assumption}\n建议确认: ${question}`, `⚠️ Uncertainty flagged: ${topic}\nAssumption: ${assumption}\nSuggested confirmation: ${question}`),
3121
+ },
3122
+ timestamp: Date.now(),
3123
+ });
3124
+ return {
3125
+ content: [{
3126
+ type: 'text',
3127
+ text: JSON.stringify({
3128
+ success: true,
3129
+ message: (0, outputLanguage_1.localize)(outputLanguage, `已标记不确定性。将基于假设继续: "${assumption}"。用户会看到该标记,并可在下一轮纠正。`, `Uncertainty flagged. Proceeding with assumption: "${assumption}". The user will see this flag and can correct it in the next turn.`),
3130
+ flagCount: uncertaintyFlagsRef.length,
3131
+ }),
3132
+ }],
3133
+ };
3134
+ }) : null;
3135
+ // ── P1-G19: recall_patterns — agent-queryable long-term memory ──
3136
+ const recallPatterns = (0, claude_agent_sdk_1.tool)('recall_patterns', 'Query long-term analysis pattern memory for insights from past sessions with similar traces. ' +
3137
+ 'Use this when you want to check if similar traces have been analyzed before and what was discovered. ' +
3138
+ 'Provide trace characteristics like architecture type, scene type, and domain keywords.', {
3139
+ architectureType: zod_1.z.string().optional().describe('Architecture type (e.g., "standard", "flutter_surfaceview", "compose")'),
3140
+ sceneType: zod_1.z.string().optional().describe('Scene type (e.g., "scrolling", "startup", "anr")'),
3141
+ keywords: zod_1.z.array(zod_1.z.string()).optional().describe('Domain keywords (e.g., ["jank", "binder", "gpu"])'),
3142
+ }, async ({ architectureType, sceneType: querySceneType, keywords }) => {
3143
+ const features = (0, analysisPatternMemory_1.extractTraceFeatures)({
3144
+ architectureType,
3145
+ sceneType: querySceneType,
3146
+ packageName,
3147
+ });
3148
+ // Add extra keyword features if provided
3149
+ if (keywords) {
3150
+ for (const kw of keywords) {
3151
+ features.push(`domain:${kw.toLowerCase()}`);
3152
+ }
3153
+ }
3154
+ const positiveMatches = (0, analysisPatternMemory_1.matchPatterns)(features, knowledgeScope);
3155
+ const negativeMatches = (0, analysisPatternMemory_1.matchNegativePatterns)(features, knowledgeScope);
3156
+ if (positiveMatches.length === 0 && negativeMatches.length === 0) {
3157
+ return {
3158
+ content: [{ type: 'text', text: JSON.stringify({
3159
+ success: true,
3160
+ message: 'No matching patterns found in memory. This may be a novel trace configuration.',
3161
+ positivePatterns: [],
3162
+ negativePatterns: [],
3163
+ }) }],
3164
+ };
3165
+ }
3166
+ const positive = positiveMatches.map(m => ({
3167
+ sceneType: m.sceneType,
3168
+ architectureType: m.architectureType,
3169
+ score: Math.round(m.score * 100),
3170
+ insights: m.keyInsights.slice(0, 3),
3171
+ matchCount: m.matchCount,
3172
+ }));
3173
+ const negative = negativeMatches.flatMap(m => m.failedApproaches.slice(0, 3).map(a => ({
3174
+ type: a.type,
3175
+ approach: a.approach,
3176
+ reason: a.reason,
3177
+ workaround: a.workaround,
3178
+ })));
3179
+ // P1-10: Also include verifier's learned misdiagnosis patterns
3180
+ let learnedMisdiagnosis = [];
3181
+ try {
3182
+ const learnedPatternsFile = (0, runtimePaths_1.backendLogPath)('learned_misdiagnosis_patterns.json');
3183
+ if (fs.existsSync(learnedPatternsFile)) {
3184
+ const raw = JSON.parse(fs.readFileSync(learnedPatternsFile, 'utf-8'));
3185
+ const cutoff = Date.now() - 60 * 24 * 60 * 60 * 1000; // 60-day TTL
3186
+ learnedMisdiagnosis = raw
3187
+ .filter((p) => p.createdAt >= cutoff && p.occurrences >= 2)
3188
+ .slice(0, 10)
3189
+ .map((p) => ({
3190
+ keywords: p.keywords,
3191
+ message: p.message,
3192
+ occurrences: p.occurrences,
3193
+ }));
3194
+ }
3195
+ }
3196
+ catch { /* non-fatal */ }
3197
+ return {
3198
+ content: [{ type: 'text', text: JSON.stringify({
3199
+ success: true,
3200
+ positivePatterns: positive,
3201
+ negativePatterns: negative,
3202
+ learnedMisdiagnosis: learnedMisdiagnosis.length > 0 ? learnedMisdiagnosis : undefined,
3203
+ message: `Found ${positive.length} positive and ${negative.length} negative patterns from past sessions.` +
3204
+ (learnedMisdiagnosis.length > 0 ? ` Also ${learnedMisdiagnosis.length} learned misdiagnosis avoidance patterns.` : ''),
3205
+ }) }],
3206
+ };
3207
+ }, { annotations: { readOnlyHint: true } });
3208
+ // ---------------------------------------------------------------------------
3209
+ // Comparison mode tools — conditional on referenceTraceId
3210
+ // ---------------------------------------------------------------------------
3211
+ const { referenceTraceId, comparisonContext } = options;
3212
+ const executeSqlOn = referenceTraceId ? (0, claude_agent_sdk_1.tool)('execute_sql_on', 'Execute a SQL query against a specific trace in comparison mode. ' +
3213
+ 'Use "current" for the primary trace, "reference" for the comparison trace.\n\n' +
3214
+ 'Use when: you need to drill into a specific trace during comparison analysis, ' +
3215
+ 'or verify a finding from compare_skill with more targeted SQL.\n\n' +
3216
+ 'SQL safety rules: qualify duplicate column names after JOINs. Do not write bare SELECT name/ts/dur when joining slice/thread/process; use s.name AS slice_name, s.ts, s.dur, t.name AS thread_name, p.name AS process_name, or prefer the thread_slice stdlib view. FrameTimeline rows expose upid, not utid/process_name; use JOIN process USING(upid) for actual_frame_timeline_slice. thread_slice does not expose self_dur directly; JOIN slice_self_dur USING(id) when self time is needed. When using thread_slice, read thread_name and process_name directly; do not write t.name or p.name unless JOIN thread t or JOIN process p is present. The thread table main-thread column is is_main_thread, not main_thread.\n\n' +
3217
+ 'Examples:\n' +
3218
+ '1. Check reference trace jank: trace="reference", sql="SELECT COUNT(*) FROM actual_frame_timeline_slice WHERE jank_type != \'None\'"\n' +
3219
+ '2. Compare CPU freq: trace="current", sql="SELECT cpu, AVG(value) as avg_freq FROM counter JOIN counter_track ON counter.track_id=counter_track.id WHERE counter_track.name GLOB \'cpu*freq\' GROUP BY cpu"', {
3220
+ trace: zod_1.z.enum(['current', 'reference']).describe('Which trace to query: "current" = primary trace loaded in Perfetto, "reference" = comparison trace.'),
3221
+ sql: zod_1.z.string().describe('The SQL query to execute against the specified trace.'),
3222
+ summary: zod_1.z.boolean().optional().describe('When true, returns column statistics + sample rows instead of full results. Default: false.'),
3223
+ }, async ({ trace, sql, summary }) => {
3224
+ const planError = requirePlan('execute_sql_on');
3225
+ if (planError) {
3226
+ return { content: [{ type: 'text', text: planError }] };
3227
+ }
3228
+ const artifactSqlHint = artifactSqlMisuseHint(sql, outputLanguage);
3229
+ if (artifactSqlHint) {
3230
+ return {
3231
+ content: [{ type: 'text', text: JSON.stringify(artifactSqlHint) }],
3232
+ isError: true,
3233
+ };
3234
+ }
3235
+ const targetTraceId = trace === 'reference' ? referenceTraceId : traceId;
3236
+ const traceLabel = trace === 'reference'
3237
+ ? (0, outputLanguage_1.localize)(outputLanguage, '[参考 Trace]', '[reference trace]')
3238
+ : (0, outputLanguage_1.localize)(outputLanguage, '[当前 Trace]', '[current trace]');
3239
+ const producer = createEvidenceProducerContext('execute_sql_on', { trace, sql, summary }, trace === 'reference'
3240
+ ? (0, outputLanguage_1.localize)(outputLanguage, '执行参考 Trace SQL,验证对比差异。', 'Run SQL on the reference trace to verify comparison deltas.')
3241
+ : (0, outputLanguage_1.localize)(outputLanguage, '执行当前 Trace SQL,验证对比差异。', 'Run SQL on the current trace to verify comparison deltas.'), trace);
3242
+ try {
3243
+ const sqlStart = Date.now();
3244
+ const { result, finalSql, injected, traceProvenance, normalizedSql, sqlRewrites } = await runRawSqlWithIncludeInjection(targetTraceId, sql, trace);
3245
+ const processIdentityWarning = rawSqlProcessIdentityWarning(normalizedSql);
3246
+ const truncated = result.rows.length > 200;
3247
+ const rows = truncated ? result.rows.slice(0, 200) : result.rows;
3248
+ const success = !result.error;
3249
+ let emittedEvidence;
3250
+ if (success && summary && result.rows.length > 0) {
3251
+ const summaryResult = (0, sqlSummarizer_1.summarizeSqlResult)(result.columns, result.rows);
3252
+ const durationMs = Date.now() - sqlStart;
3253
+ if (emitUpdate) {
3254
+ emittedEvidence = emitSqlSummaryDataEnvelope(emitUpdate, summaryResult, finalSql, injected, traceProvenance, producer);
3255
+ }
3256
+ const text = JSON.stringify({
3257
+ success: true,
3258
+ trace: traceLabel,
3259
+ traceSide: trace,
3260
+ traceId: targetTraceId,
3261
+ traceProvenance,
3262
+ summary: summaryResult,
3263
+ totalRows: result.rows.length,
3264
+ durationMs,
3265
+ evidenceRefId: emittedEvidence?.evidenceRefId,
3266
+ sourceToolCallId: producer.sourceToolCallId,
3267
+ paramsHash: producer.paramsHash,
3268
+ planPhaseId: producer.planPhaseId,
3269
+ executableSql: finalSql,
3270
+ ...(sqlRewrites.length > 0 ? { sqlRewrites } : {}),
3271
+ stdlibInjectedModules: injected,
3272
+ ...(processIdentityWarning ? { processIdentityWarning } : {}),
3273
+ });
3274
+ return { content: [{ type: 'text', text: consumeWatchdogWarning(text + getReasoningNudge()) }] };
3275
+ }
3276
+ const durationMs = Date.now() - sqlStart;
3277
+ if (emitUpdate && success && result.columns.length > 0) {
3278
+ emittedEvidence = emitSqlDataEnvelope(emitUpdate, result.columns, rows, finalSql, injected, traceProvenance, producer);
3279
+ }
3280
+ else if (emitUpdate && !success) {
3281
+ emittedEvidence = emitSqlDiagnosticDataEnvelope(emitUpdate, result.error || (0, outputLanguage_1.localize)(outputLanguage, 'SQL 执行失败', 'SQL execution failed'), finalSql, injected, traceProvenance, producer);
3282
+ }
3283
+ const text = JSON.stringify({
3284
+ success,
3285
+ trace: traceLabel,
3286
+ traceSide: trace,
3287
+ traceId: targetTraceId,
3288
+ traceProvenance,
3289
+ columns: result.columns,
3290
+ rows,
3291
+ totalRows: result.rows.length,
3292
+ truncated,
3293
+ durationMs,
3294
+ evidenceRefId: emittedEvidence?.evidenceRefId,
3295
+ sourceToolCallId: producer.sourceToolCallId,
3296
+ paramsHash: producer.paramsHash,
3297
+ planPhaseId: producer.planPhaseId,
3298
+ executableSql: finalSql,
3299
+ ...(sqlRewrites.length > 0 ? { sqlRewrites } : {}),
3300
+ stdlibInjectedModules: injected,
3301
+ ...(processIdentityWarning ? { processIdentityWarning } : {}),
3302
+ error: result.error,
3303
+ });
3304
+ return { content: [{ type: 'text', text: consumeWatchdogWarning(success ? text + getReasoningNudge() : text) }] };
3305
+ }
3306
+ catch (e) {
3307
+ const traceProvenance = (0, traceProcessorConnectionModel_1.buildTraceProcessorQueryProvenance)({
3308
+ traceId: targetTraceId,
3309
+ traceSide: trace,
3310
+ });
3311
+ const emittedEvidence = emitUpdate ? emitSqlDiagnosticDataEnvelope(emitUpdate, e.message, sql, undefined, traceProvenance, producer, outputLanguage) : undefined;
3312
+ return {
3313
+ content: [{
3314
+ type: 'text',
3315
+ text: JSON.stringify({
3316
+ success: false,
3317
+ trace: traceLabel,
3318
+ traceSide: trace,
3319
+ traceId: targetTraceId,
3320
+ traceProvenance,
3321
+ evidenceRefId: emittedEvidence?.evidenceRefId,
3322
+ sourceToolCallId: producer.sourceToolCallId,
3323
+ paramsHash: producer.paramsHash,
3324
+ planPhaseId: producer.planPhaseId,
3325
+ error: e.message,
3326
+ }),
3327
+ }],
3328
+ };
3329
+ }
3330
+ }, { annotations: { readOnlyHint: true } }) : null;
3331
+ const compareSkill = referenceTraceId ? (0, claude_agent_sdk_1.tool)('compare_skill', 'Run the same skill on both current and reference traces in parallel, returning side-by-side results with schema alignment info.\n\n' +
3332
+ 'Use when: you want to compare the same analysis dimension across both traces (e.g., scrolling_analysis, cpu_analysis).\n' +
3333
+ 'Don\'t use when: you need different skills on each trace, or ad-hoc SQL queries (use execute_sql_on instead).\n\n' +
3334
+ 'Examples:\n' +
3335
+ '1. Compare scrolling: skillId="scrolling_analysis", params={process_name: "com.example.app"}\n' +
3336
+ '2. Compare CPU: skillId="cpu_analysis"', {
3337
+ skillId: zod_1.z.string().describe('Skill identifier to run on both traces'),
3338
+ params: zod_1.z.record(zod_1.z.string(), zod_1.z.any()).optional().describe('Parameters passed to both skill executions. Common: { process_name, start_ts, end_ts }'),
3339
+ }, async ({ skillId, params }) => {
3340
+ const planError = requirePlan('compare_skill');
3341
+ if (planError) {
3342
+ return { content: [{ type: 'text', text: planError }] };
3343
+ }
3344
+ try {
3345
+ const effectiveParams = normalizeSkillParams(params, packageName);
3346
+ // For reference trace: use its own package name if detected, otherwise
3347
+ // omit process_name filter entirely (safer than silently using current's package)
3348
+ const refParams = comparisonContext?.referencePackageName
3349
+ ? normalizeSkillParams(params, comparisonContext.referencePackageName)
3350
+ : normalizeSkillParams(params); // No default package — skill runs unfiltered
3351
+ const baseProducer = createEvidenceProducerContext('compare_skill', { skillId, params }, (0, outputLanguage_1.localize)(outputLanguage, `对比 Skill ${skillId},在当前和参考 Trace 上收集同构证据。`, `Compare Skill ${skillId} to collect aligned evidence on current and reference traces.`));
3352
+ emitUpdate?.({
3353
+ type: 'progress',
3354
+ content: {
3355
+ phase: 'analyzing',
3356
+ message: (0, outputLanguage_1.localize)(outputLanguage, `对比技能 ${skillId}:在两个 Trace 上并行执行...`, `Comparing skill ${skillId}: running on both traces in parallel...`),
3357
+ },
3358
+ timestamp: Date.now(),
3359
+ });
3360
+ const compareStart = Date.now();
3361
+ const currentTraceProvenance = (0, traceProcessorConnectionModel_1.buildTraceProcessorQueryProvenance)({
3362
+ traceId,
3363
+ traceSide: 'current',
3364
+ });
3365
+ const referenceTraceProvenance = (0, traceProcessorConnectionModel_1.buildTraceProcessorQueryProvenance)({
3366
+ traceId: referenceTraceId,
3367
+ traceSide: 'reference',
3368
+ });
3369
+ const [currentResult, refResult] = await Promise.all([
3370
+ skillExecutor.execute(skillId, traceId, effectiveParams),
3371
+ skillExecutor.execute(skillId, referenceTraceId, refParams),
3372
+ ]);
3373
+ const compareDuration = Date.now() - compareStart;
3374
+ // Schema alignment: check which steps are comparable
3375
+ const currentStepIds = new Set((currentResult.displayResults || []).map(r => r.stepId));
3376
+ const refStepIds = new Set((refResult.displayResults || []).map(r => r.stepId));
3377
+ const comparableSteps = [...currentStepIds].filter(id => refStepIds.has(id));
3378
+ const incompatibleSteps = [
3379
+ ...[...currentStepIds]
3380
+ .filter(id => !refStepIds.has(id))
3381
+ .map(id => `${id} ${(0, outputLanguage_1.localize)(outputLanguage, '(仅当前 Trace)', '(current trace only)')}`),
3382
+ ...[...refStepIds]
3383
+ .filter(id => !currentStepIds.has(id))
3384
+ .map(id => `${id} ${(0, outputLanguage_1.localize)(outputLanguage, '(仅参考 Trace)', '(reference trace only)')}`),
3385
+ ];
3386
+ // Emit data envelopes for both sides (labeled)
3387
+ if (emitUpdate && currentResult.displayResults?.length) {
3388
+ emitSkillDataEnvelopes(currentResult.displayResults, skillId, emitUpdate, currentTraceProvenance, {
3389
+ ...baseProducer,
3390
+ sourceToolCallId: `${baseProducer.sourceToolCallId}:current`,
3391
+ producerReason: (0, outputLanguage_1.localize)(outputLanguage, `当前 Trace 对比 Skill ${skillId} 结果。`, `Current trace result for comparison Skill ${skillId}.`),
3392
+ });
3393
+ }
3394
+ if (emitUpdate && refResult.displayResults?.length) {
3395
+ emitSkillDataEnvelopes(refResult.displayResults, skillId, emitUpdate, referenceTraceProvenance, {
3396
+ ...baseProducer,
3397
+ sourceToolCallId: `${baseProducer.sourceToolCallId}:reference`,
3398
+ producerReason: (0, outputLanguage_1.localize)(outputLanguage, `参考 Trace 对比 Skill ${skillId} 结果。`, `Reference trace result for comparison Skill ${skillId}.`),
3399
+ });
3400
+ }
3401
+ // Build compact comparison summary for Claude
3402
+ const buildStepSummary = (results) => results.map(r => ({
3403
+ stepId: r.stepId,
3404
+ title: r.title,
3405
+ rowCount: r.data?.rows?.length || 0,
3406
+ columns: r.data?.columns || [],
3407
+ }));
3408
+ const text = JSON.stringify({
3409
+ success: true,
3410
+ durationMs: compareDuration,
3411
+ current: {
3412
+ traceSide: 'current',
3413
+ traceId,
3414
+ traceProvenance: currentTraceProvenance,
3415
+ success: currentResult.success,
3416
+ stepCount: currentResult.displayResults?.length || 0,
3417
+ steps: buildStepSummary(currentResult.displayResults || []),
3418
+ diagnosticCount: currentResult.diagnostics?.length || 0,
3419
+ error: currentResult.error,
3420
+ },
3421
+ reference: {
3422
+ traceSide: 'reference',
3423
+ traceId: referenceTraceId,
3424
+ traceProvenance: referenceTraceProvenance,
3425
+ success: refResult.success,
3426
+ stepCount: refResult.displayResults?.length || 0,
3427
+ steps: buildStepSummary(refResult.displayResults || []),
3428
+ diagnosticCount: refResult.diagnostics?.length || 0,
3429
+ error: refResult.error,
3430
+ },
3431
+ alignment: {
3432
+ comparableSteps,
3433
+ incompatibleSteps: incompatibleSteps.length > 0 ? incompatibleSteps : undefined,
3434
+ },
3435
+ hint: (0, outputLanguage_1.localize)(outputLanguage, '使用 execute_sql_on 深钻具体差异指标,或使用 fetch_artifact 获取详细数据。', 'Use execute_sql_on to drill into specific delta metrics, or fetch_artifact for detailed data.'),
3436
+ });
3437
+ return { content: [{ type: 'text', text: consumeWatchdogWarning(text + getReasoningNudge()) }] };
3438
+ }
3439
+ catch (e) {
3440
+ return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: e.message }) }] };
3441
+ }
3442
+ }) : null;
3443
+ const getComparisonContext = (referenceTraceId && comparisonContext) ? (0, claude_agent_sdk_1.tool)('get_comparison_context', 'Get metadata comparison between the current trace and the reference trace. ' +
3444
+ 'Returns device info, focus app, architecture, and capability alignment for both traces.\n\n' +
3445
+ 'ALWAYS call this first in comparison mode to understand what you are comparing ' +
3446
+ 'and confirm the traces are comparable (same app, compatible capabilities).', {}, async () => {
3447
+ const ctx = comparisonContext;
3448
+ const text = JSON.stringify({
3449
+ success: true,
3450
+ current: {
3451
+ traceId,
3452
+ packageName: packageName || 'unknown',
3453
+ architecture: options.cachedArchitecture?.type || 'unknown',
3454
+ focusApps: options.cachedArchitecture ? undefined : 'detect with detect_architecture',
3455
+ },
3456
+ reference: {
3457
+ traceId: referenceTraceId,
3458
+ packageName: ctx.referencePackageName || 'unknown',
3459
+ architecture: ctx.referenceArchitecture?.type || 'unknown',
3460
+ },
3461
+ packageAlignment: packageName && ctx.referencePackageName
3462
+ ? (packageName === ctx.referencePackageName ? 'same' : 'different')
3463
+ : 'unknown',
3464
+ commonCapabilities: ctx.commonCapabilities,
3465
+ capabilityDiff: ctx.capabilityDiff,
3466
+ });
3467
+ return { content: [{ type: 'text', text }] };
3468
+ }, { annotations: { readOnlyHint: true } }) : null;
3469
+ // Plan 41 M0 (P2-G1 evolution): the canonical tool list lives in
3470
+ // `McpToolRegistry`. Each register call carries the §4.5 exposure
3471
+ // level so future hosts (stdio, A2A) can filter without
3472
+ // re-deciding policy. Registration order is preserved exactly to
3473
+ // keep SDK behavior identical to the pre-refactor toolEntries
3474
+ // array — trace regression validates that.
3475
+ const registry = new mcpToolRegistry_1.McpToolRegistry();
3476
+ if (options.lightweight) {
3477
+ // Lightweight mode: core data-access tools only — no planning,
3478
+ // hypothesis, notes, or advanced tools. Plan gate is automatically
3479
+ // disabled because analysisPlan is not passed in lightweight mode.
3480
+ // `invoke_skill` returns artifact references, so `fetch_artifact` must
3481
+ // stay available or lightweight models try to query artifact IDs as SQL.
3482
+ registry.registerSdk(executeSql, 'execute_sql', 'public');
3483
+ registry.registerSdk(invokeSkill, 'invoke_skill', 'public');
3484
+ registry.registerSdk(lookupSqlSchema, 'lookup_sql_schema', 'public');
3485
+ if (fetchArtifact)
3486
+ registry.registerSdk(fetchArtifact, 'fetch_artifact', 'public');
3487
+ }
3488
+ else {
3489
+ // Full mode: all always-on tools + conditional tools.
3490
+ registry.registerSdk(executeSql, 'execute_sql', 'public');
3491
+ registry.registerSdk(invokeSkill, 'invoke_skill', 'public');
3492
+ registry.registerSdk(listSkills, 'list_skills', 'public');
3493
+ registry.registerSdk(detectArchitecture, 'detect_architecture', 'public');
3494
+ registry.registerSdk(lookupSqlSchema, 'lookup_sql_schema', 'public');
3495
+ registry.registerSdk(queryPerfettoSource, 'query_perfetto_source', 'public');
3496
+ registry.registerSdk(listStdlibModules, 'list_stdlib_modules', 'public');
3497
+ registry.registerSdk(lookupKnowledge, 'lookup_knowledge', 'public');
3498
+ registry.registerSdk(lookupBlogKnowledge, 'lookup_blog_knowledge', 'public');
3499
+ registry.registerSdk(lookupAospSource, 'lookup_aosp_source', 'public');
3500
+ registry.registerSdk(lookupOemSdk, 'lookup_oem_sdk', 'public');
3501
+ registry.registerSdk(lookupBaseline, 'lookup_baseline', 'public');
3502
+ registry.registerSdk(compareBaselines, 'compare_baselines', 'public');
3503
+ registry.registerSdk(recallProjectMemory, 'recall_project_memory', 'public');
3504
+ registry.registerSdk(recallSimilarCase, 'recall_similar_case', 'public');
3505
+ if (writeAnalysisNote)
3506
+ registry.registerSdk(writeAnalysisNote, 'write_analysis_note', 'internal');
3507
+ if (fetchArtifact)
3508
+ registry.registerSdk(fetchArtifact, 'fetch_artifact', 'public');
3509
+ if (submitPlan)
3510
+ registry.registerSdk(submitPlan, 'submit_plan', 'internal');
3511
+ if (updatePlanPhase)
3512
+ registry.registerSdk(updatePlanPhase, 'update_plan_phase', 'internal');
3513
+ if (revisePlan)
3514
+ registry.registerSdk(revisePlan, 'revise_plan', 'internal');
3515
+ if (submitHypothesis)
3516
+ registry.registerSdk(submitHypothesis, 'submit_hypothesis', 'internal');
3517
+ if (resolveHypothesis)
3518
+ registry.registerSdk(resolveHypothesis, 'resolve_hypothesis', 'internal');
3519
+ if (flagUncertainty)
3520
+ registry.registerSdk(flagUncertainty, 'flag_uncertainty', 'internal');
3521
+ // recall_patterns stays 'internal' for one more commit. Plan 41 M1b
3522
+ // routes the recall path through openSupersedeStoreReadOnly so it no
3523
+ // longer mkdir's or migrates the supersede DB on first call. The
3524
+ // public-readonly exposure flip is gated on the M1b invariant test
3525
+ // soaking for one release cycle to catch any hidden writable code
3526
+ // path; that flip is the M1b commit 2 follow-up.
3527
+ registry.registerSdk(recallPatterns, 'recall_patterns', 'internal');
3528
+ // Comparison mode tools — only when referenceTraceId is provided.
3529
+ if (compareSkill)
3530
+ registry.registerSdk(compareSkill, 'compare_skill', 'internal');
3531
+ if (executeSqlOn)
3532
+ registry.registerSdk(executeSqlOn, 'execute_sql_on', 'internal');
3533
+ if (getComparisonContext)
3534
+ registry.registerSdk(getComparisonContext, 'get_comparison_context', 'internal');
3535
+ }
3536
+ return {
3537
+ server: registry.buildSdkServer(),
3538
+ allowedTools: registry.buildAllowedTools(),
3539
+ toolDefinitions: registry.list(),
3540
+ };
3541
+ }
3542
+ function evidenceHash(input) {
3543
+ const text = typeof input === 'string'
3544
+ ? input
3545
+ : JSON.stringify(input, (_key, value) => typeof value === 'bigint' ? value.toString() : value);
3546
+ return (0, crypto_1.createHash)('sha256').update(text || '').digest('hex').slice(0, 12);
3547
+ }
3548
+ function evidencePart(value, fallback = 'unknown') {
3549
+ const text = String(value ?? fallback)
3550
+ .trim()
3551
+ .replace(/[^a-zA-Z0-9_.-]+/g, '_')
3552
+ .replace(/^_+|_+$/g, '')
3553
+ .slice(0, 80);
3554
+ return text || fallback;
3555
+ }
3556
+ function evidenceTracePart(traceProvenance) {
3557
+ if (!traceProvenance)
3558
+ return 'trace_unknown';
3559
+ const side = evidencePart(traceProvenance.traceSide || 'current', 'current');
3560
+ const trace = evidenceHash(traceProvenance.traceId);
3561
+ return `${side}:${trace}`;
3562
+ }
3563
+ function stableSqlEvidenceRefId(sql, columns, rows, traceProvenance, producer, mode = 'table') {
3564
+ const queryHash = evidenceHash(sql || { columns, sampleRows: rows.slice(0, 5), rowCount: rows.length });
3565
+ const toolPart = evidencePart(producer?.paramsHash || 'tool', 'tool');
3566
+ return {
3567
+ evidenceRefId: `data:sql_${mode}:${evidenceTracePart(traceProvenance)}:${queryHash}:${toolPart}`,
3568
+ queryHash,
3569
+ };
3570
+ }
3571
+ function stableSkillEvidenceRefId(skillId, stepId, title, data, traceProvenance, producer) {
3572
+ const dataHash = evidenceHash({
3573
+ title,
3574
+ data,
3575
+ });
3576
+ const toolPart = evidencePart(producer?.paramsHash || 'tool', 'tool');
3577
+ return `data:skill:${evidencePart(skillId, 'skill')}:${evidencePart(stepId || title, 'step')}:${evidenceTracePart(traceProvenance)}:${dataHash}:${toolPart}`;
3578
+ }
3579
+ function sqlSummaryMarkdown(summary) {
3580
+ const stats = Array.isArray(summary.columnStats) ? summary.columnStats : [];
3581
+ const lines = [
3582
+ `Total rows: ${summary.totalRows}`,
3583
+ '',
3584
+ '| Column | Type | Min | Avg | P95 | Max | Nulls |',
3585
+ '| --- | --- | ---: | ---: | ---: | ---: | ---: |',
3586
+ ];
3587
+ for (const stat of stats.slice(0, 20)) {
3588
+ lines.push([
3589
+ stat.column,
3590
+ stat.type,
3591
+ stat.min ?? '',
3592
+ stat.avg ?? '',
3593
+ stat.p95 ?? '',
3594
+ stat.max ?? '',
3595
+ stat.nullCount,
3596
+ ].join(' | '));
3597
+ }
3598
+ return lines.join('\n');
3599
+ }
3600
+ function sqlSummaryMetrics(summary) {
3601
+ const metrics = [
3602
+ { label: 'total_rows', value: summary.totalRows, severity: 'info' },
3603
+ ];
3604
+ const stats = Array.isArray(summary.columnStats) ? summary.columnStats : [];
3605
+ for (const stat of stats.slice(0, 8)) {
3606
+ if (stat.type !== 'numeric')
3607
+ continue;
3608
+ if (stat.avg !== undefined)
3609
+ metrics.push({ label: `${stat.column}.avg`, value: stat.avg, severity: 'info' });
3610
+ if (stat.p95 !== undefined)
3611
+ metrics.push({ label: `${stat.column}.p95`, value: stat.p95, severity: 'info' });
3612
+ }
3613
+ return metrics;
3614
+ }
3615
+ function producerEnvelopeOptions(producer) {
3616
+ return {
3617
+ sourceToolCallId: producer?.sourceToolCallId,
3618
+ paramsHash: producer?.paramsHash,
3619
+ planPhaseId: producer?.planPhaseId,
3620
+ planPhaseTitle: producer?.planPhaseTitle,
3621
+ planPhaseGoal: producer?.planPhaseGoal,
3622
+ planPhaseAttribution: producer?.planPhaseAttribution,
3623
+ planPhaseWarning: producer?.planPhaseWarning,
3624
+ toolNarration: producer?.toolNarration,
3625
+ producerReason: producer?.producerReason,
3626
+ };
3627
+ }
3628
+ /** Emit a DataEnvelope for SQL query results. */
3629
+ function emitSqlDataEnvelope(emit, columns, rows, sql, stdlibInjectedModules, traceProvenance, producer) {
3630
+ const { evidenceRefId, queryHash } = stableSqlEvidenceRefId(sql, columns, rows, traceProvenance, producer);
3631
+ const envelope = (0, dataContract_1.createDataEnvelope)({ columns, rows }, {
3632
+ type: 'sql_result',
3633
+ source: 'execute_sql',
3634
+ title: `SQL Query (${rows.length} rows)`,
3635
+ layer: 'list',
3636
+ format: 'table',
3637
+ columns: columns.map((col) => ({
3638
+ name: col,
3639
+ type: inferSqlColumnType(col),
3640
+ })),
3641
+ evidenceRefId,
3642
+ traceSide: traceProvenance?.traceSide,
3643
+ traceId: traceProvenance?.traceId,
3644
+ queryHash,
3645
+ ...producerEnvelopeOptions(producer),
3646
+ intent: 'ad_hoc_sql_verification',
3647
+ });
3648
+ emit({
3649
+ type: 'data',
3650
+ content: [{
3651
+ ...envelope,
3652
+ ...(sql ? { sql } : {}),
3653
+ ...(stdlibInjectedModules?.length ? { stdlibInjectedModules } : {}),
3654
+ ...(traceProvenance ? {
3655
+ traceSide: traceProvenance.traceSide,
3656
+ traceId: traceProvenance.traceId,
3657
+ traceProvenance,
3658
+ } : {}),
3659
+ }],
3660
+ timestamp: Date.now(),
3661
+ });
3662
+ return { evidenceRefId, queryHash };
3663
+ }
3664
+ /** Emit a DataEnvelope for SQL summary-mode results. */
3665
+ function emitSqlSummaryDataEnvelope(emit, summary, sql, stdlibInjectedModules, traceProvenance, producer) {
3666
+ const { evidenceRefId, queryHash } = stableSqlEvidenceRefId(sql, summary.columns, summary.sampleRows, traceProvenance, producer, 'summary');
3667
+ const envelope = (0, dataContract_1.createDataEnvelope)({
3668
+ summary: {
3669
+ title: `SQL Summary (${summary.totalRows} rows)`,
3670
+ content: sqlSummaryMarkdown(summary),
3671
+ metrics: sqlSummaryMetrics(summary),
3672
+ },
3673
+ }, {
3674
+ type: 'sql_result',
3675
+ source: 'execute_sql',
3676
+ title: `SQL Summary (${summary.totalRows} rows)`,
3677
+ layer: 'overview',
3678
+ format: 'summary',
3679
+ evidenceRefId,
3680
+ traceSide: traceProvenance?.traceSide,
3681
+ traceId: traceProvenance?.traceId,
3682
+ queryHash,
3683
+ ...producerEnvelopeOptions(producer),
3684
+ intent: 'ad_hoc_sql_summary',
3685
+ });
3686
+ emit({
3687
+ type: 'data',
3688
+ content: [{
3689
+ ...envelope,
3690
+ ...(sql ? { sql } : {}),
3691
+ ...(stdlibInjectedModules?.length ? { stdlibInjectedModules } : {}),
3692
+ ...(traceProvenance ? {
3693
+ traceSide: traceProvenance.traceSide,
3694
+ traceId: traceProvenance.traceId,
3695
+ traceProvenance,
3696
+ } : {}),
3697
+ }],
3698
+ timestamp: Date.now(),
3699
+ });
3700
+ return { evidenceRefId, queryHash };
3701
+ }
3702
+ /** Emit a diagnostic DataEnvelope for failed SQL so missing tables remain explainable. */
3703
+ function emitSqlDiagnosticDataEnvelope(emit, error, sql, stdlibInjectedModules, traceProvenance, producer, outputLanguage = outputLanguage_1.DEFAULT_OUTPUT_LANGUAGE) {
3704
+ const { evidenceRefId, queryHash } = stableSqlEvidenceRefId(sql, [], [[error]], traceProvenance, producer, 'diagnostic');
3705
+ const envelope = (0, dataContract_1.createDataEnvelope)({
3706
+ text: [
3707
+ (0, outputLanguage_1.localize)(outputLanguage, 'SQL 执行未产出可用表格。', 'SQL execution did not produce a table.'),
3708
+ (0, outputLanguage_1.localize)(outputLanguage, '这是一条失败诊断,不是可引用的性能证据;需要修正 SQL 后重试。', 'This is a failure diagnostic, not citable performance evidence; fix the SQL and retry.'),
3709
+ `Error: ${error}`,
3710
+ sql ? `SQL: ${sql}` : '',
3711
+ ].filter(Boolean).join('\n'),
3712
+ }, {
3713
+ type: 'diagnostic',
3714
+ source: 'execute_sql',
3715
+ title: (0, outputLanguage_1.localize)(outputLanguage, 'SQL 执行诊断', 'SQL diagnostic'),
3716
+ layer: 'diagnosis',
3717
+ format: 'text',
3718
+ evidenceRefId,
3719
+ traceSide: traceProvenance?.traceSide,
3720
+ traceId: traceProvenance?.traceId,
3721
+ queryHash,
3722
+ ...producerEnvelopeOptions(producer),
3723
+ intent: 'ad_hoc_sql_diagnostic',
3724
+ });
3725
+ emit({
3726
+ type: 'data',
3727
+ content: [{
3728
+ ...envelope,
3729
+ ...(sql ? { sql } : {}),
3730
+ ...(stdlibInjectedModules?.length ? { stdlibInjectedModules } : {}),
3731
+ ...(traceProvenance ? {
3732
+ traceSide: traceProvenance.traceSide,
3733
+ traceId: traceProvenance.traceId,
3734
+ traceProvenance,
3735
+ } : {}),
3736
+ }],
3737
+ timestamp: Date.now(),
3738
+ });
3739
+ return { evidenceRefId, queryHash };
3740
+ }
3741
+ function inferSqlColumnType(col) {
3742
+ if (col.includes('ts') || col.includes('timestamp'))
3743
+ return 'timestamp';
3744
+ if (col.includes('dur'))
3745
+ return 'duration';
3746
+ if (col.includes('pct') || col.includes('percent'))
3747
+ return 'percentage';
3748
+ return 'string';
3749
+ }
3750
+ /**
3751
+ * Convert skill DisplayResults to DataEnvelopes and emit as SSE 'data' events.
3752
+ * This enables interactive tables (clickable timestamps, expandable rows) in the frontend.
3753
+ */
3754
+ function emitSkillDataEnvelopes(displayResults, skillId, emit, traceProvenance, producer) {
3755
+ const envelopes = displayResults
3756
+ .filter(dr => Array.isArray(dr.data?.rows))
3757
+ .map(dr => {
3758
+ const explicitColumns = dr.columnDefinitions;
3759
+ const envelope = (0, dataContract_1.displayResultToEnvelope)(dr, skillId, explicitColumns);
3760
+ const evidenceRefId = stableSkillEvidenceRefId(skillId, envelope.meta.stepId, envelope.display.title, envelope.data, traceProvenance, producer);
3761
+ const withEvidence = {
3762
+ ...envelope,
3763
+ meta: {
3764
+ ...envelope.meta,
3765
+ evidenceRefId,
3766
+ traceSide: traceProvenance?.traceSide,
3767
+ traceId: traceProvenance?.traceId,
3768
+ ...producerEnvelopeOptions(producer),
3769
+ intent: 'skill_structured_result',
3770
+ },
3771
+ };
3772
+ return traceProvenance
3773
+ ? {
3774
+ ...withEvidence,
3775
+ traceSide: traceProvenance.traceSide,
3776
+ traceId: traceProvenance.traceId,
3777
+ traceProvenance,
3778
+ }
3779
+ : withEvidence;
3780
+ });
3781
+ if (envelopes.length > 0) {
3782
+ emit({ type: 'data', content: envelopes, timestamp: Date.now() });
3783
+ }
3784
+ }
3785
+ //# sourceMappingURL=claudeMcpServer.js.map