@teevee98/synapse-hub 0.0.0-stage → 3.8.2

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 (369) hide show
  1. package/.agents/agents/api-engineer.md +67 -0
  2. package/.agents/agents/failure-analyst.md +75 -0
  3. package/.agents/agents/live-explorer.md +70 -0
  4. package/.agents/agents/orchestrator.md +104 -0
  5. package/.agents/agents/perf-engineer.md +74 -0
  6. package/.agents/agents/pom-crafter.md +112 -0
  7. package/.agents/agents/quality-gatekeeper.md +87 -0
  8. package/.agents/agents/test-designer.md +73 -0
  9. package/.agents/agents/test-runner.md +67 -0
  10. package/.agents/rules/author-integrity-guard.md +33 -0
  11. package/.agents/rules/communication-style.md +18 -0
  12. package/.agents/rules/context-engineering.md +37 -0
  13. package/.agents/rules/git-push-protocol.md +33 -0
  14. package/.agents/rules/graphify.md +14 -0
  15. package/.agents/rules/lessons-learned.md +25 -0
  16. package/.agents/rules/mandatory-playwright-live.md +25 -0
  17. package/.agents/rules/mobile_appium_rules.md +43 -0
  18. package/.agents/rules/performance_testing_rules.md +35 -0
  19. package/.agents/rules/skill-precedence.md +29 -0
  20. package/.agents/rules/systematic-debugging.md +36 -0
  21. package/.agents/skills/actor-qa-swarm/SKILL.md +77 -0
  22. package/.agents/skills/actor-qa-swarm/examples/broker_sharding_sample.json +12 -0
  23. package/.agents/skills/agent-orchestration-multi-agent-optimize/SKILL.md +88 -0
  24. package/.agents/skills/agent-orchestration-multi-agent-optimize/examples/swarm_workload_config.json +15 -0
  25. package/.agents/skills/agentless-qa-repair/SKILL.md +69 -0
  26. package/.agents/skills/agentless-qa-repair/examples/healing_report_sample.json +17 -0
  27. package/.agents/skills/agentless-qa-repair/examples/three_phase_repair_workflow.md +40 -0
  28. package/.agents/skills/antigravity-test-sentinel/SKILL.md +63 -0
  29. package/.agents/skills/antigravity-test-sentinel/examples/dod_gate_policy.json +11 -0
  30. package/.agents/skills/antigravity-test-sentinel/examples/sprint_dod_enforcement.md +47 -0
  31. package/.agents/skills/api-network-mocking-interception/SKILL.md +142 -0
  32. package/.agents/skills/api-network-mocking-interception/examples/network_route_stub.json +9 -0
  33. package/.agents/skills/api-spec-to-e2e-matrix/SKILL.md +80 -0
  34. package/.agents/skills/api-spec-to-e2e-matrix/examples/sample_openapi.json +19 -0
  35. package/.agents/skills/architecture-decision-records/SKILL.md +64 -0
  36. package/.agents/skills/architecture-decision-records/examples/0001-record-architecture-decisions.md +12 -0
  37. package/.agents/skills/auth-session-and-cookie-manager/SKILL.md +75 -0
  38. package/.agents/skills/auth-session-and-cookie-manager/examples/multi_role_auth_matrix.md +70 -0
  39. package/.agents/skills/auth-session-and-cookie-manager/examples/storage_state_sample.json +11 -0
  40. package/.agents/skills/backend-load-and-stress-patterns/SKILL.md +85 -0
  41. package/.agents/skills/backend-load-and-stress-patterns/examples/k6_load_test_sample.js +13 -0
  42. package/.agents/skills/backend-load-and-stress-patterns/references/k6_load_template.js +82 -0
  43. package/.agents/skills/bats-testing-patterns/SKILL.md +100 -0
  44. package/.agents/skills/bats-testing-patterns/examples/cli_runner_test.bats +6 -0
  45. package/.agents/skills/bats-testing-patterns/resources/implementation-playbook.md +614 -0
  46. package/.agents/skills/clean-pom-crafter/SKILL.md +110 -0
  47. package/.agents/skills/clean-pom-crafter/examples/standard_test_case.groovy +28 -0
  48. package/.agents/skills/clean-pom-crafter/references/pom_patterns.groovy +138 -0
  49. package/.agents/skills/code-refactoring-refactor-clean/SKILL.md +64 -0
  50. package/.agents/skills/code-refactoring-refactor-clean/examples/refactored_page_sample.groovy +9 -0
  51. package/.agents/skills/code-refactoring-refactor-clean/examples/refactored_playwright_pom.ts +52 -0
  52. package/.agents/skills/code-refactoring-refactor-clean/resources/implementation-playbook.md +881 -0
  53. package/.agents/skills/consumer-driven-contract-testing/SKILL.md +147 -0
  54. package/.agents/skills/consumer-driven-contract-testing/examples/order_service_pact.json +45 -0
  55. package/.agents/skills/db-state-verifier-and-seeder/SKILL.md +123 -0
  56. package/.agents/skills/db-state-verifier-and-seeder/examples/db_fixture_seed.json +12 -0
  57. package/.agents/skills/e2e-testing-patterns/SKILL.md +103 -0
  58. package/.agents/skills/e2e-testing-patterns/examples/playwright_sharded_config.ts +12 -0
  59. package/.agents/skills/e2e-testing-patterns/resources/implementation-playbook.md +522 -0
  60. package/.agents/skills/event-stream-qa-orchestrator/SKILL.md +79 -0
  61. package/.agents/skills/event-stream-qa-orchestrator/examples/timeline_sample.jsonl +2 -0
  62. package/.agents/skills/failure-autopsy-and-healing/SKILL.md +66 -0
  63. package/.agents/skills/failure-autopsy-and-healing/examples/closed_loop_healing_walkthrough.md +48 -0
  64. package/.agents/skills/failure-autopsy-and-healing/examples/sample_junit_failure.xml +8 -0
  65. package/.agents/skills/failure-autopsy-and-healing/references/healing_matrix.md +64 -0
  66. package/.agents/skills/failure-autopsy-and-healing/references/qa_investigation_protocol.md +56 -0
  67. package/.agents/skills/failure-autopsy-and-healing/scripts/triage_failures.sh +83 -0
  68. package/.agents/skills/file-and-report-validator/SKILL.md +90 -0
  69. package/.agents/skills/file-and-report-validator/examples/sample_export_schema.json +14 -0
  70. package/.agents/skills/flaky-test-sentinel-and-quarantine/SKILL.md +114 -0
  71. package/.agents/skills/flaky-test-sentinel-and-quarantine/examples/quarantine_registry.json +11 -0
  72. package/.agents/skills/gherkin-to-suite/SKILL.md +103 -0
  73. package/.agents/skills/gherkin-to-suite/examples/checkout.feature +39 -0
  74. package/.agents/skills/gherkin-to-suite/examples/suite_report_sample.json +334 -0
  75. package/.agents/skills/github-actions-templates/SKILL.md +77 -0
  76. package/.agents/skills/github-actions-templates/examples/matrix_test_pipeline.yml +8 -0
  77. package/.agents/skills/graphify-impact-analyzer/SKILL.md +76 -0
  78. package/.agents/skills/graphify-impact-analyzer/examples/dependency_blast_radius.json +8 -0
  79. package/.agents/skills/katalon-cli-runner/SKILL.md +76 -0
  80. package/.agents/skills/katalon-cli-runner/examples/headless_kre_exec.sh +3 -0
  81. package/.agents/skills/katalon-cli-runner/references/groovy-patterns.md +209 -0
  82. package/.agents/skills/katalon-cli-runner/references/katalon-api.md +155 -0
  83. package/.agents/skills/katalon-cli-runner/references/runner_commands.md +67 -0
  84. package/.agents/skills/lam-script-generator/SKILL.md +123 -0
  85. package/.agents/skills/lam-script-generator/examples/user_story_sample.md +8 -0
  86. package/.agents/skills/lean-code-ladder/SKILL.md +94 -0
  87. package/.agents/skills/lean-code-ladder/examples/ladder_walkthrough.md +37 -0
  88. package/.agents/skills/lean-impact-scoreboard/SKILL.md +48 -0
  89. package/.agents/skills/lean-impact-scoreboard/examples/sample_benchmark_gain.md +20 -0
  90. package/.agents/skills/lean-impact-scoreboard/examples/sample_scoreboard.md +15 -0
  91. package/.agents/skills/meta-prompt-crafter/SKILL.md +107 -0
  92. package/.agents/skills/meta-prompt-crafter/examples/qa_prompt_template.md +35 -0
  93. package/.agents/skills/mipro-prompt-compiler/SKILL.md +59 -0
  94. package/.agents/skills/mipro-prompt-compiler/examples/compiled_module_sample.json +22 -0
  95. package/.agents/skills/mipro-prompt-compiler/examples/dspy_assertion_optimizer_case.md +46 -0
  96. package/.agents/skills/mobile-appium-som/SKILL.md +88 -0
  97. package/.agents/skills/mobile-appium-som/examples/BaseScreen.java +88 -0
  98. package/.agents/skills/mobile-appium-som/examples/LoginScreen.java +46 -0
  99. package/.agents/skills/mobile-appium-som/examples/TC_MobileLogin.java +43 -0
  100. package/.agents/skills/persistent-planning-files/SKILL.md +108 -0
  101. package/.agents/skills/persistent-planning-files/examples/task_plan_example.md +56 -0
  102. package/.agents/skills/playwright-live-interaction/SKILL.md +131 -0
  103. package/.agents/skills/playwright-live-interaction/examples/live_probe_script.js +5 -0
  104. package/.agents/skills/playwright-live-interaction/references/advanced_superpowers.md +160 -0
  105. package/.agents/skills/playwright-live-interaction/references/compact_accessibility_snapshots.md +75 -0
  106. package/.agents/skills/playwright-live-interaction/references/recipes.md +388 -0
  107. package/.agents/skills/playwright-live-interaction/references/swarm_orchestration.md +134 -0
  108. package/.agents/skills/playwright-webapp-testing/SKILL.md +93 -0
  109. package/.agents/skills/playwright-webapp-testing/examples/server_lifecycle_playwright.py +63 -0
  110. package/.agents/skills/qa-aci-interface/SKILL.md +67 -0
  111. package/.agents/skills/qa-aci-interface/examples/surgical_code_window_walkthrough.md +40 -0
  112. package/.agents/skills/qa-aci-interface/examples/surgical_edit_sample.json +12 -0
  113. package/.agents/skills/qa-memory-os/SKILL.md +80 -0
  114. package/.agents/skills/qa-memory-os/examples/archival_memory_sample.json +21 -0
  115. package/.agents/skills/rbt-manual-testing/SKILL.md +137 -0
  116. package/.agents/skills/rbt-manual-testing/examples/checkout_rbt_manual_suite.md +25 -0
  117. package/.agents/skills/rbt-manual-testing/references/field_validation_checklist.md +29 -0
  118. package/.agents/skills/repo-quality-audit/SKILL.md +68 -0
  119. package/.agents/skills/repo-quality-audit/examples/sample_audit_walkthrough.md +15 -0
  120. package/.agents/skills/repo-quality-audit/examples/sample_repo_audit.md +33 -0
  121. package/.agents/skills/review-spec/SKILL.md +60 -0
  122. package/.agents/skills/review-spec/examples/pocock_grilling_decision_rubric.md +40 -0
  123. package/.agents/skills/review-spec/examples/sample_spec_review.md +33 -0
  124. package/.agents/skills/security-dast-sentinel/SKILL.md +119 -0
  125. package/.agents/skills/security-dast-sentinel/examples/dast_scan_config.json +10 -0
  126. package/.agents/skills/security-dast-sentinel/references/AI-AND-LLM.md +113 -0
  127. package/.agents/skills/security-dast-sentinel/references/ATTACK-CLASSES.md +89 -0
  128. package/.agents/skills/security-dast-sentinel/references/dast_recipes.ts +33 -0
  129. package/.agents/skills/self-healing-locator/SKILL.md +86 -0
  130. package/.agents/skills/self-healing-locator/examples/aom_diff_sample.json +16 -0
  131. package/.agents/skills/senior-code-review/SKILL.md +108 -0
  132. package/.agents/skills/senior-code-review/examples/sample_review_walkthrough.md +29 -0
  133. package/.agents/skills/skillspector-security-guard/SKILL.md +57 -0
  134. package/.agents/skills/skillspector-security-guard/examples/audit_threat_vectors_report.json +35 -0
  135. package/.agents/skills/skillspector-security-guard/examples/safe_mcp_config.json +12 -0
  136. package/.agents/skills/surgical-coding-principles/SKILL.md +89 -0
  137. package/.agents/skills/surgical-coding-principles/examples/surgical_vs_scope_creep.md +46 -0
  138. package/.agents/skills/synthetic-test-data-generator/SKILL.md +135 -0
  139. package/.agents/skills/synthetic-test-data-generator/examples/idempotent_data_recipe.json +9 -0
  140. package/.agents/skills/systematic-debugging/SKILL.md +100 -0
  141. package/.agents/skills/systematic-debugging/examples/four_phase_case.md +44 -0
  142. package/.agents/skills/technical-debt-harvester/SKILL.md +70 -0
  143. package/.agents/skills/technical-debt-harvester/examples/sample_debt_ledger.md +25 -0
  144. package/.agents/skills/technical-debt-harvester/examples/sample_ledger_output.md +20 -0
  145. package/.agents/skills/test-driven-development/SKILL.md +114 -0
  146. package/.agents/skills/test-driven-development/examples/red_green_refactor_qa.md +78 -0
  147. package/.agents/skills/token-and-context-optimizer/SKILL.md +70 -0
  148. package/.agents/skills/token-and-context-optimizer/examples/distilled_log_sample.txt +3 -0
  149. package/.agents/skills/token-and-context-optimizer/references/context_engineering_guide.md +49 -0
  150. package/.agents/skills/tot-exploratory-testing/SKILL.md +59 -0
  151. package/.agents/skills/tot-exploratory-testing/examples/payment_gateway_tot_tree.json +62 -0
  152. package/.agents/skills/tot-exploratory-testing/examples/tot_graph_sample.json +35 -0
  153. package/.agents/skills/verification-before-completion/SKILL.md +100 -0
  154. package/.agents/skills/verification-before-completion/examples/evidence_log_example.md +46 -0
  155. package/.agents/skills/visual-regression-sentinel/SKILL.md +82 -0
  156. package/.agents/skills/visual-regression-sentinel/examples/visual_mask_rules.json +9 -0
  157. package/.agents/skills/wcag-audit-patterns/SKILL.md +77 -0
  158. package/.agents/skills/wcag-audit-patterns/examples/wcag_compliance_checklist.json +10 -0
  159. package/.agents/skills/wcag-audit-patterns/resources/implementation-playbook.md +541 -0
  160. package/.agents/skills/web-agent-gym-benchmarking/SKILL.md +62 -0
  161. package/.agents/skills/web-agent-gym-benchmarking/examples/benchmark_report_sample.json +22 -0
  162. package/.agents/skills/web-agent-gym-benchmarking/examples/enterprise_tasks_suite.json +38 -0
  163. package/.agents/skills/web-vitals-and-performance-profiler/SKILL.md +65 -0
  164. package/.agents/skills/web-vitals-and-performance-profiler/examples/cwv_budget_policy.json +6 -0
  165. package/.agents/skills/web-vitals-and-performance-profiler/examples/playwright_cwv_profiler_fixture.ts +118 -0
  166. package/.agents/templates/completion_report.md +57 -0
  167. package/.agents/workflows/analyze_requirement_document.md +18 -0
  168. package/.agents/workflows/export_testcases_excel.md +32 -0
  169. package/.agents/workflows/generate_combinatorial_test_data.md +28 -0
  170. package/.agents/workflows/generate_cross_module_test_plan.md +37 -0
  171. package/.agents/workflows/generate_manual_testcases_rbt.md +56 -0
  172. package/.agents/workflows/generate_requirements_from_website.md +25 -0
  173. package/.agents/workflows/generate_testcases_from_requirements.md +21 -0
  174. package/.agents/workflows/graphify.md +10 -0
  175. package/.agents/workflows/test-impact.md +15 -0
  176. package/.agents/workflows/verify.md +34 -0
  177. package/.cursor/rules/agents.mdc +16 -0
  178. package/.cursor/rules/language.mdc +7 -0
  179. package/.cursor/rules/synapse-qa.mdc +24 -0
  180. package/.cursorrules +27 -0
  181. package/.dockerignore +53 -0
  182. package/.pre-commit-hooks.yaml +14 -0
  183. package/.windsurfrules +26 -0
  184. package/AGENTS.md +86 -0
  185. package/CLAUDE.md +54 -0
  186. package/Dockerfile +81 -0
  187. package/LICENSE +52 -0
  188. package/NOTICE +264 -0
  189. package/README.en.md +172 -0
  190. package/README.md +171 -2
  191. package/action.yml +51 -0
  192. package/agentskills.json +16 -0
  193. package/bin/agent-qa.js +138 -0
  194. package/docker-compose.yml +74 -0
  195. package/docs/ARCHITECTURE.en.md +197 -0
  196. package/docs/ARCHITECTURE.md +198 -0
  197. package/docs/CI_CD_INTEGRATION.en.md +170 -0
  198. package/docs/CI_CD_INTEGRATION.md +170 -0
  199. package/docs/CLI_REFERENCE.en.md +175 -0
  200. package/docs/CLI_REFERENCE.md +177 -0
  201. package/docs/CONTRIBUTING.en.md +49 -0
  202. package/docs/CONTRIBUTING.md +49 -0
  203. package/docs/PERFORMANCE_AUDIT_REPORT.md +784 -0
  204. package/docs/PLUGIN_DEVELOPMENT_GUIDE.md +127 -0
  205. package/docs/QUALITY_GATES.en.md +121 -0
  206. package/docs/QUALITY_GATES.md +121 -0
  207. package/docs/TOKEN_QUOTA_PLAYBOOK.md +41 -0
  208. package/docs/TOOL_CATALOG.md +129 -0
  209. package/docs/adopted-ecosystem-tools.md +96 -0
  210. package/docs/research/EXTERNAL_AGENT_SKILLS_SURVEY.md +1062 -0
  211. package/docs/research/agent_skill_training_analysis.md +1359 -0
  212. package/docs/schemas/synapse.config.schema.json +87 -0
  213. package/package.json +94 -4
  214. package/plugin.json +31 -0
  215. package/scripts/generate_skill_examples.py +244 -0
  216. package/scripts/install.ps1 +112 -0
  217. package/scripts/install_global_plugin.ps1 +94 -0
  218. package/scripts/install_global_plugin.sh +49 -0
  219. package/scripts/lint_skills.ps1 +57 -0
  220. package/scripts/package_dist.py +337 -0
  221. package/scripts/setup.sh +59 -0
  222. package/scripts/update_hub.ps1 +19 -0
  223. package/scripts/update_hub.sh +15 -0
  224. package/skills_manifest.json +854 -0
  225. package/synapse.config.json +32 -0
  226. package/templates/PROJECT_AI_GUIDE_TEMPLATE.md +111 -0
  227. package/templates/PROJECT_STATE_TEMPLATE.md +20 -0
  228. package/templates/ai_bridges/CLAUDE.md +54 -0
  229. package/templates/ai_bridges/copilot-instructions.md +20 -0
  230. package/templates/ai_bridges/cursor_synapse_qa.mdc +24 -0
  231. package/templates/ai_bridges/windsurfrules +26 -0
  232. package/templates/ci/github-actions-synapse.yml +95 -0
  233. package/templates/ci/gitlab-ci-synapse.yml +16 -0
  234. package/templates/ui/index.html +1069 -0
  235. package/templates/welcome.html.tmpl +2079 -0
  236. package/tools/.infer_baseline.json +30 -0
  237. package/tools/TOOLS_RUNBOOK.md +1553 -0
  238. package/tools/TOOL_CATALOG.json +1769 -0
  239. package/tools/__init__.py +43 -0
  240. package/tools/_openapi_parser.py +158 -0
  241. package/tools/agent_canary.py +525 -0
  242. package/tools/agentless_patcher.py +417 -0
  243. package/tools/analyze_project.py +258 -0
  244. package/tools/api_drift_sentinel.py +208 -0
  245. package/tools/api_fuzzer.py +762 -0
  246. package/tools/author_integrity.py +184 -0
  247. package/tools/auto_heal.py +271 -0
  248. package/tools/auto_heal_reflexion.py +532 -0
  249. package/tools/autogen_qa_broker.py +844 -0
  250. package/tools/benchmark_swarm_context.py +394 -0
  251. package/tools/browser_helpers.js +746 -0
  252. package/tools/browsergym_eval.py +236 -0
  253. package/tools/bug_reporter.py +252 -0
  254. package/tools/bump_version.py +423 -0
  255. package/tools/cache_resolver.py +1214 -0
  256. package/tools/check_env.py +426 -0
  257. package/tools/check_version_sync.py +256 -0
  258. package/tools/ci_healing_hook.py +126 -0
  259. package/tools/cli.py +1598 -0
  260. package/tools/config_decoupler.py +253 -0
  261. package/tools/contract_validator.py +141 -0
  262. package/tools/core/__init__.py +70 -0
  263. package/tools/core/adapters.py +431 -0
  264. package/tools/core/circuit_breaker.py +263 -0
  265. package/tools/core/cli_runtime.py +66 -0
  266. package/tools/core/file_lock.py +159 -0
  267. package/tools/core/i18n.py +394 -0
  268. package/tools/core/memory_bus.py +905 -0
  269. package/tools/core/process_supervisor.py +332 -0
  270. package/tools/core/telemetry.py +329 -0
  271. package/tools/count_tokens.py +1267 -0
  272. package/tools/create_mock_docx.py +104 -0
  273. package/tools/dashboard_generator.py +2419 -0
  274. package/tools/db_sandbox.py +675 -0
  275. package/tools/debt_harvester.py +237 -0
  276. package/tools/distill_log.py +161 -0
  277. package/tools/dspy_qa_signatures.py +356 -0
  278. package/tools/e2e_flow_prober.py +132 -0
  279. package/tools/export_postman_collection.py +945 -0
  280. package/tools/flaky_detector.py +389 -0
  281. package/tools/fsm_enforcer.py +450 -0
  282. package/tools/fsm_middleware.py +401 -0
  283. package/tools/fuzz_payloads.py +197 -0
  284. package/tools/generate_allure_report.py +88 -0
  285. package/tools/generate_api_matrix.py +193 -0
  286. package/tools/generate_jmx_plan.py +1322 -0
  287. package/tools/generate_sbom.py +252 -0
  288. package/tools/generate_tc_from_story.py +203 -0
  289. package/tools/generate_test_reports.py +133 -0
  290. package/tools/generate_tool_catalog.py +482 -0
  291. package/tools/gherkin_suite.py +758 -0
  292. package/tools/git_pre_commit_guard.py +298 -0
  293. package/tools/goldfish_review.py +366 -0
  294. package/tools/heal/__init__.py +28 -0
  295. package/tools/heal_pr_automator.py +220 -0
  296. package/tools/heuristic_locator_matcher.py +351 -0
  297. package/tools/hub_publisher.py +623 -0
  298. package/tools/humanize_linter.py +438 -0
  299. package/tools/infer_linter.py +977 -0
  300. package/tools/init_config.py +307 -0
  301. package/tools/interview_story.py +116 -0
  302. package/tools/jira_sync.py +566 -0
  303. package/tools/jtl_analyzer.py +474 -0
  304. package/tools/lint/__init__.py +30 -0
  305. package/tools/lint_ai_docs.py +374 -0
  306. package/tools/lookup_tc.py +165 -0
  307. package/tools/lookup_xpath.py +167 -0
  308. package/tools/matrix_sharder.py +148 -0
  309. package/tools/mcp/__init__.py +18 -0
  310. package/tools/mcp_docx_server.ps1 +13 -0
  311. package/tools/mcp_docx_server.py +851 -0
  312. package/tools/mcp_excel_server.ps1 +13 -0
  313. package/tools/mcp_excel_server.py +441 -0
  314. package/tools/mcp_server.py +724 -0
  315. package/tools/md_to_xlsx.py +327 -0
  316. package/tools/micro_mutator.py +887 -0
  317. package/tools/mipro_assertion_tuner.py +210 -0
  318. package/tools/network_mock_shield.py +311 -0
  319. package/tools/newman_analyzer.py +384 -0
  320. package/tools/omni_emitter.py +579 -0
  321. package/tools/omni_parser.py +450 -0
  322. package/tools/omni_transpiler.py +168 -0
  323. package/tools/openxml_guard.py +438 -0
  324. package/tools/output_formatter.py +182 -0
  325. package/tools/package_release.py +325 -0
  326. package/tools/perf/__init__.py +24 -0
  327. package/tools/pinpoint_failure.py +190 -0
  328. package/tools/project_state.py +171 -0
  329. package/tools/qa_event_stream.py +358 -0
  330. package/tools/repo_map.py +346 -0
  331. package/tools/report/__init__.py +32 -0
  332. package/tools/reversible_sandbox.py +344 -0
  333. package/tools/safety_firewall.py +437 -0
  334. package/tools/security_coverage_ledger.py +538 -0
  335. package/tools/security_scanner.py +229 -0
  336. package/tools/senior_code_review.py +393 -0
  337. package/tools/setup_project.py +770 -0
  338. package/tools/skill_collision_guard.py +304 -0
  339. package/tools/skill_profiles.py +217 -0
  340. package/tools/skill_vault.py +481 -0
  341. package/tools/skillspector.py +1278 -0
  342. package/tools/smart_visual_masker.py +132 -0
  343. package/tools/spec_drift_sentinel.py +438 -0
  344. package/tools/swe_qa_aci.py +369 -0
  345. package/tools/synapse_observer.py +485 -0
  346. package/tools/synapse_qa_bench.py +190 -0
  347. package/tools/sync_agent_rules.py +274 -0
  348. package/tools/telemetry_correlator.py +397 -0
  349. package/tools/template_excel_exporter.py +514 -0
  350. package/tools/templates/jmeter-distributed/README.md +54 -0
  351. package/tools/templates/jmeter-distributed/docker-compose.yml +83 -0
  352. package/tools/test_impact.py +419 -0
  353. package/tools/test_memory_os.py +462 -0
  354. package/tools/textgrad_mutation_optimizer.py +237 -0
  355. package/tools/tms_sync_bridge.py +834 -0
  356. package/tools/tot_exploratory_tester.py +239 -0
  357. package/tools/trace_data_flow.py +240 -0
  358. package/tools/traffic_session_converter.py +256 -0
  359. package/tools/trend_analytics.py +314 -0
  360. package/tools/ui_server.py +401 -0
  361. package/tools/universal_ir.py +488 -0
  362. package/tools/update_sentinel.py +383 -0
  363. package/tools/validate_groovy_scripts.py +173 -0
  364. package/tools/verify_all.py +1259 -0
  365. package/tools/visual_diff_canvas.py +143 -0
  366. package/tools/visual_som_helper.py +550 -0
  367. package/tools/watch_mode.py +308 -0
  368. package/tools/wcag_audit.py +239 -0
  369. package/tools/welcome_page.py +290 -0
@@ -0,0 +1,1214 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Universal Local Semantic Memory Cache & Self-Healing Resolver
4
+ -------------------------------------------------------------
5
+ Provides 100% Offline, Zero-Token diagnostic resolution for known test failures.
6
+ Saves solutions directly into an SQLite database (tools/memory_cache.db).
7
+ When identical failures occur, returns pre-tested patches with 0 LLM Tokens.
8
+
9
+ Features:
10
+ 1. Positive Memory Cache (healing_cache): Pre-tested, verified code patches.
11
+ 2. Negative Memory Cache (failed_fixes): Blacklist tracking incorrect patches,
12
+ preventing AI Agents from falling into Blind Retry Loops.
13
+ """
14
+
15
+ import sys
16
+ import os
17
+ import sqlite3
18
+ import json
19
+ import argparse
20
+ import re
21
+ import math
22
+ import time
23
+ import functools
24
+ from collections import Counter
25
+ from datetime import datetime
26
+
27
+ # Enforce UTF-8 stdout encoding for Windows console compatibility
28
+ if hasattr(sys.stdout, 'reconfigure'):
29
+ try:
30
+ sys.stdout.reconfigure(encoding='utf-8')
31
+ sys.stderr.reconfigure(encoding='utf-8')
32
+ except Exception:
33
+ pass
34
+
35
+ def _find_project_root():
36
+ """Traverses up from CWD or script directory to find the target project root."""
37
+ curr = os.path.abspath(os.getcwd())
38
+ while True:
39
+ if any(os.path.exists(os.path.join(curr, m)) for m in ("package.json", "PROJECT_AI_GUIDE.md", ".git", "pyproject.toml")):
40
+ return curr
41
+ parent = os.path.dirname(curr)
42
+ if parent == curr:
43
+ break
44
+ curr = parent
45
+ return os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
46
+
47
+
48
+ GLOBAL_DIR = os.path.expanduser("~/.agent_memory")
49
+ GLOBAL_DB = os.path.join(GLOBAL_DIR, "global_cache.db")
50
+ LOCAL_DIR = os.path.join(_find_project_root(), ".synapse")
51
+ LOCAL_DB = os.path.join(LOCAL_DIR, "cache.db")
52
+
53
+
54
+ def resolve_db_path(use_local=False):
55
+ """
56
+ Returns the SQLite database path.
57
+ Defaults to project-local store (.synapse/cache.db) to prevent cross-project NDA/IP leakage.
58
+ Global memory (~/.agent_memory/global_cache.db) is only used when SYNAPSE_GLOBAL_CACHE=1
59
+ or when explicit use_local=False is called with SYNAPSE_GLOBAL_CACHE enabled.
60
+ Zero filesystem mutation on module import: directories are lazy-created upon connection.
61
+ """
62
+ if os.environ.get("SYNAPSE_CACHE_DB"):
63
+ return os.environ.get("SYNAPSE_CACHE_DB")
64
+ if os.environ.get("SYNAPSE_GLOBAL_CACHE", "").lower() in ("1", "true", "yes") and not use_local:
65
+ return GLOBAL_DB
66
+ return LOCAL_DB
67
+
68
+
69
+ DB_FILE = resolve_db_path()
70
+
71
+ SECRET_PATTERNS = [
72
+ (re.compile(r'(?i)(api[_-]?key|secret|token|password|auth|passwd|credential)[\s:=]+["\']?([a-zA-Z0-9_\-\.]{8,})["\']?'), r'\1="[REDACTED]"'),
73
+ (re.compile(r'-----BEGIN[ A-Z_-]+PRIVATE KEY-----[\s\S]+?-----END[ A-Z_-]+PRIVATE KEY-----'), '[REDACTED_PRIVATE_KEY]'),
74
+ (re.compile(r'https?://([^:]+):([^@]+)@'), r'https://\1:[REDACTED]@'),
75
+ (re.compile(r'Bearer\s+[a-zA-Z0-9_\-\.]{15,}'), 'Bearer [REDACTED_TOKEN]'),
76
+ ]
77
+
78
+
79
+ def sanitize_text(text):
80
+ """Redacts passwords, API tokens, and private keys before persisting to SQLite memory."""
81
+ if not text or not isinstance(text, str):
82
+ return text or ""
83
+ sanitized = text
84
+ for pattern, repl in SECRET_PATTERNS:
85
+ sanitized = pattern.sub(repl, sanitized)
86
+ return sanitized
87
+
88
+
89
+ def djb2_hash(s: str) -> str:
90
+ """Computes a 32-bit unsigned DJB2 hash formatted as an 8-char hex string."""
91
+ h = 5381
92
+ for byte in s.encode('utf-8', errors='ignore'):
93
+ h = (((h << 5) + h) + byte) & 0xFFFFFFFF
94
+ return f"{h:08x}"
95
+
96
+
97
+ def compute_error_fingerprint(error_type: str, error_msg: str, stack_anchor: str = "") -> str:
98
+ """
99
+ Computes a deterministic, normalized fingerprint hash for an error.
100
+ Strips volatile elements (timestamps, hex addresses, line numbers) so semantically
101
+ identical errors across test runs produce the identical fingerprint.
102
+ """
103
+ norm_type = (error_type or "").strip().lower()
104
+ msg = error_msg or ""
105
+ # Strip hex memory addresses
106
+ msg = re.sub(r'0x[0-9a-fA-F]+', '0xADDR', msg)
107
+ # Strip ISO/standard timestamps
108
+ msg = re.sub(r'\b\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?\b', 'TIMESTAMP', msg)
109
+ # Strip variable line numbers in filenames like "file.py:123"
110
+ msg = re.sub(r':\d+\b', ':LINE', msg)
111
+ # Collapse whitespace
112
+ msg = re.sub(r'\s+', ' ', msg).strip()[:200]
113
+
114
+ anchor = (stack_anchor or "").strip().lower()
115
+ if anchor:
116
+ anchor = re.sub(r':\d+\b', ':LINE', anchor)
117
+ raw = f"{norm_type}:{msg}@{anchor}"
118
+ else:
119
+ raw = f"{norm_type}:{msg}"
120
+ return f"fp_{djb2_hash(raw)}"
121
+
122
+
123
+ def group_errors_by_fingerprint(error_list: list, repeat_threshold: int = 3) -> dict:
124
+ """
125
+ Groups error events by fingerprint and detects repeated errors (exceeding repeat_threshold).
126
+ """
127
+ grouped = {}
128
+ for item in error_list:
129
+ err_type = item.get("error_type") or item.get("type") or "UnknownError"
130
+ err_msg = item.get("error_message") or item.get("message") or item.get("symptom") or ""
131
+ anchor = item.get("stack_anchor") or item.get("file") or ""
132
+ fp = compute_error_fingerprint(err_type, err_msg, anchor)
133
+ if fp not in grouped:
134
+ grouped[fp] = {
135
+ "fingerprint": fp,
136
+ "count": 0,
137
+ "is_repeated": False,
138
+ "error_type": err_type,
139
+ "sample_message": err_msg,
140
+ "items": []
141
+ }
142
+ grouped[fp]["count"] += 1
143
+ if grouped[fp]["count"] >= repeat_threshold:
144
+ grouped[fp]["is_repeated"] = True
145
+ grouped[fp]["items"].append(item)
146
+ return grouped
147
+
148
+
149
+ SEED_SOLUTIONS = [
150
+ {
151
+ "error_signature": "ElementClickInterceptedException",
152
+ "module_name": "GLOBAL",
153
+ "symptom": "Modal backdrop or PrimeNG overlay (.p-component-overlay) blocks button click.",
154
+ "root_cause": "Angular PrimeNG animation fade-out latency.",
155
+ "groovy_patch": "waitForElementNotVisible(By.cssSelector(\".p-component-overlay, .modal-backdrop\"), 5);\nfindElement(by).click();"
156
+ },
157
+ {
158
+ "error_signature": "Save_Button_Disabled",
159
+ "module_name": "GLOBAL",
160
+ "symptom": "Save button [ Submit ] remains dimmed/disabled.",
161
+ "root_cause": "Angular Reactive Form missing synthetic input/change event or required field empty.",
162
+ "groovy_patch": "WebElement el = findElement(By.cssSelector(\"input[formcontrolname='code']\"));\njsSetInput(el, uniqueCode);"
163
+ },
164
+ {
165
+ "error_signature": "StaleElementReferenceException",
166
+ "module_name": "GLOBAL",
167
+ "symptom": "Element is not attached to the DOM.",
168
+ "root_cause": "Angular re-rendered DOM node after async API response.",
169
+ "groovy_patch": "for (int i = 0; i < 3; i++) {\n try {\n waitForElementVisible(by, 5);\n findElement(by).click();\n break;\n } catch (StaleElementReferenceException e) {\n waitForPageLoaded(5);\n }\n}"
170
+ },
171
+ {
172
+ "error_signature": "Duplicate_Code_Error",
173
+ "module_name": "GLOBAL",
174
+ "symptom": "Toast alert: 'Code already exists' or 'Data already exists'.",
175
+ "root_cause": "Hardcoded or non-unique test identifier collided with existing record.",
176
+ "groovy_patch": "String code = BasePage.uniqueCode(\"AUTO_\");"
177
+ },
178
+ {
179
+ "error_signature": "PrimeNG_Dropdown_Empty",
180
+ "module_name": "GLOBAL",
181
+ "symptom": "Dropdown item not clicked or panel not visible.",
182
+ "root_cause": "Overlay panel (.p-dropdown-panel) has not rendered when click dispatched.",
183
+ "groovy_patch": "waitForElementVisible(By.cssSelector(\".p-dropdown-panel\"), 5);\nfindElement(By.xpath(\"//li[contains(., '\" + text + \"')]\")).click();"
184
+ },
185
+ {
186
+ "error_signature": "BlockUI_TimeoutException",
187
+ "module_name": "GLOBAL",
188
+ "symptom": "Timeout waiting for table or form interaction.",
189
+ "root_cause": "PrimeNG loading mask (.p-blockui, .p-progress-spinner) still active.",
190
+ "groovy_patch": "waitForElementNotVisible(By.cssSelector(\".p-blockui, .p-progress-spinner\"), 10);"
191
+ }
192
+ ]
193
+
194
+ SEED_LESSONS_LEARNED = [
195
+ {
196
+ "page_context": "Checkout / Payment",
197
+ "error_signature": "ElementClickInterceptedException",
198
+ "root_cause": "Debounce 300ms hoáēˇc PrimeNG overlay (.p-component-overlay) đang máģ dáē§n.",
199
+ "failed_attempt": "findElement(By.id('confirm-btn')).click();",
200
+ "successful_fix": "waitForElementNotVisible('.p-component-overlay', 5); jsClick(btn);",
201
+ "lesson_summary": "TáēĄi Checkout/Payment, button Confirm báģ‹ debounce hoáēˇc overlay animation; không click tráģąc tiáēŋp mà pháēŖi đáģŖi overlay biáēŋn máēĨt hoáēˇc dÚng clickJS/clickSafe."
202
+ },
203
+ {
204
+ "page_context": "Auth / Reactive Forms",
205
+ "error_signature": "Save_Button_Disabled / FormInvalid",
206
+ "root_cause": "Angular Reactive Form không nháē­n native DOM value do thiáēŋu Zone.js synthetic input event.",
207
+ "failed_attempt": "input.sendKeys(uniqueCode); submitBtn.click();",
208
+ "successful_fix": "jsSetInput(input, uniqueCode); qa.audit();",
209
+ "lesson_summary": "TáēĄi cÃĄc form Angular/React, sendKeys chay không trigger validity; báē¯t buáģ™c dispatch synthetic input/change event hoáēˇc dÚng qa.audit."
210
+ },
211
+ {
212
+ "page_context": "Data Mining / Async Table",
213
+ "error_signature": "StaleElementReferenceException",
214
+ "root_cause": "BáēŖng dáģ¯ liáģ‡u re-render DOM node sau khi nháē­n API response báēĨt đáģ“ng báģ™.",
215
+ "failed_attempt": "tableRows.get(0).click();",
216
+ "successful_fix": "waitForElementNotVisible('.p-blockui, .p-progress-spinner', 10); retryClick(row);",
217
+ "lesson_summary": "TáēĄi báēŖng dáģ¯ liáģ‡u async, tuyáģ‡t đáģ‘i không click row ngay láē­p táģŠc; pháēŖi đáģŖi BlockUI/Spinner biáēŋn máēĨt hoàn toàn đáģƒ trÃĄnh Stale Element."
218
+ }
219
+ ]
220
+
221
+ SEED_FAILED_FIXES = [
222
+ {
223
+ "error_signature": "StaleElementReferenceException",
224
+ "attempted_patch": "Thread.sleep(3000); findElement(by).click();",
225
+ "failure_reason": "Causes pipeline flakiness; fails whenever network lag or server response exceeds static sleep duration.",
226
+ "agent_role": "pom-crafter"
227
+ },
228
+ {
229
+ "error_signature": "ElementClickInterceptedException",
230
+ "attempted_patch": "new Actions(driver).moveToElement(el).click().perform();",
231
+ "failure_reason": "Still blocked by modal backdrop because backdrop element sits physically above target element in z-index.",
232
+ "agent_role": "failure-analyst"
233
+ },
234
+ {
235
+ "error_signature": "Save_Button_Disabled",
236
+ "attempted_patch": "el.sendKeys(uniqueCode);",
237
+ "failure_reason": "Standard Selenium sendKeys does not fire Angular Zone.js synthetic input/change events, leaving formControl invalid.",
238
+ "agent_role": "pom-crafter"
239
+ }
240
+ ]
241
+
242
+
243
+ def retry_on_locked(max_retries=5, initial_delay=0.05, backoff=2.0):
244
+ """Decorator to retry SQLite operations if database is locked or busy."""
245
+ def decorator(func):
246
+ @functools.wraps(func)
247
+ def wrapper(*args, **kwargs):
248
+ delay = initial_delay
249
+ last_err = None
250
+ for attempt in range(max_retries):
251
+ try:
252
+ return func(*args, **kwargs)
253
+ except sqlite3.OperationalError as e:
254
+ last_err = e
255
+ err_msg = str(e).lower()
256
+ if "locked" in err_msg or "busy" in err_msg:
257
+ time.sleep(delay)
258
+ delay *= backoff
259
+ else:
260
+ raise
261
+ if last_err:
262
+ raise last_err
263
+ return wrapper
264
+ return decorator
265
+
266
+
267
+ class ManagedConnection(sqlite3.Connection):
268
+ """Resilient SQLite connection that automatically commits/rollbacks and closes on context exit."""
269
+ def __exit__(self, exc_type, exc_val, exc_tb):
270
+ try:
271
+ super().__exit__(exc_type, exc_val, exc_tb)
272
+ finally:
273
+ self.close()
274
+
275
+
276
+ def get_db(db_path=None, timeout=30.0):
277
+ """Returns a resilient SQLite connection configured with WAL mode, busy timeout, and auto-close."""
278
+ target = db_path or resolve_db_path()
279
+ parent_dir = os.path.dirname(os.path.abspath(target))
280
+ if parent_dir and not os.path.exists(parent_dir):
281
+ os.makedirs(parent_dir, exist_ok=True)
282
+ conn = sqlite3.connect(target, timeout=timeout, factory=ManagedConnection)
283
+ conn.row_factory = sqlite3.Row
284
+ try:
285
+ conn.execute("PRAGMA journal_mode=WAL;")
286
+ conn.execute("PRAGMA synchronous=NORMAL;")
287
+ conn.execute("PRAGMA busy_timeout=30000;")
288
+ except sqlite3.Error as e:
289
+ sys.stderr.write(f"Notice: SQLite PRAGMA configuration skipped: {e}\n")
290
+ return conn
291
+
292
+
293
+ @retry_on_locked()
294
+ def init_db(seed=True, target_db=None):
295
+ current_db = target_db or DB_FILE
296
+ with get_db(current_db) as conn:
297
+ cursor = conn.cursor()
298
+ # 1. Positive Memory Table (Verified Working Patches)
299
+ cursor.execute("""
300
+ CREATE TABLE IF NOT EXISTS healing_cache (
301
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
302
+ error_signature TEXT NOT NULL,
303
+ module_name TEXT DEFAULT 'GLOBAL',
304
+ symptom TEXT,
305
+ root_cause TEXT,
306
+ code_patch TEXT DEFAULT '',
307
+ groovy_patch TEXT NOT NULL,
308
+ hit_count INTEGER DEFAULT 0,
309
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
310
+ UNIQUE(error_signature, module_name)
311
+ )
312
+ """)
313
+ try:
314
+ cursor.execute("ALTER TABLE healing_cache ADD COLUMN code_patch TEXT DEFAULT ''")
315
+ except sqlite3.OperationalError:
316
+ _ = True
317
+
318
+ # 2. Negative Memory Table (Blacklist of Failed Fix Attempts)
319
+ cursor.execute("""
320
+ CREATE TABLE IF NOT EXISTS failed_fixes (
321
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
322
+ error_signature TEXT NOT NULL,
323
+ attempted_patch TEXT NOT NULL,
324
+ failure_reason TEXT NOT NULL,
325
+ agent_role TEXT DEFAULT 'pom-crafter',
326
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
327
+ )
328
+ """)
329
+
330
+ # 3. Episodic Reflexion Table (Historical Lessons Learned)
331
+ cursor.execute("""
332
+ CREATE TABLE IF NOT EXISTS lessons_learned (
333
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
334
+ page_context TEXT DEFAULT 'GLOBAL',
335
+ error_signature TEXT NOT NULL,
336
+ root_cause TEXT,
337
+ failed_attempt TEXT,
338
+ successful_fix TEXT,
339
+ lesson_summary TEXT NOT NULL,
340
+ hit_count INTEGER DEFAULT 0,
341
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
342
+ )
343
+ """)
344
+
345
+ # 4. Flaky Test Historical Telemetry & Quarantine Matrix
346
+ cursor.execute("""
347
+ CREATE TABLE IF NOT EXISTS test_telemetry (
348
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
349
+ test_id TEXT NOT NULL,
350
+ run_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
351
+ status TEXT NOT NULL,
352
+ is_retry INTEGER DEFAULT 0,
353
+ duration_ms REAL DEFAULT 0.0,
354
+ error_signature TEXT DEFAULT '',
355
+ context TEXT DEFAULT ''
356
+ )
357
+ """)
358
+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_telemetry_test_id ON test_telemetry (test_id)")
359
+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_telemetry_timestamp ON test_telemetry (run_timestamp)")
360
+ conn.commit()
361
+
362
+ # Migrate existing solutions from local DB if initializing global DB for the first time
363
+ if current_db == GLOBAL_DB and os.path.exists(LOCAL_DB):
364
+ try:
365
+ with get_db(LOCAL_DB) as local_conn:
366
+ rows = local_conn.execute("SELECT * FROM healing_cache").fetchall()
367
+ for r in rows:
368
+ cursor.execute("""
369
+ INSERT OR IGNORE INTO healing_cache
370
+ (error_signature, module_name, symptom, root_cause, groovy_patch, hit_count)
371
+ VALUES (?, ?, ?, ?, ?, ?)
372
+ """, (r["error_signature"], r["module_name"], r["symptom"], r["root_cause"], r["groovy_patch"], r["hit_count"]))
373
+ conn.commit()
374
+ except (sqlite3.Error, OSError) as e:
375
+ sys.stderr.write(f"Notice: Local cache migration skipped: {e}\n")
376
+
377
+ if seed:
378
+ for s in SEED_SOLUTIONS:
379
+ cursor.execute("""
380
+ INSERT OR IGNORE INTO healing_cache
381
+ (error_signature, module_name, symptom, root_cause, groovy_patch)
382
+ VALUES (?, ?, ?, ?, ?)
383
+ """, (s["error_signature"], s["module_name"], s["symptom"], s["root_cause"], s["groovy_patch"]))
384
+
385
+ for f in SEED_FAILED_FIXES:
386
+ cursor.execute("""
387
+ SELECT COUNT(*) as cnt FROM failed_fixes
388
+ WHERE error_signature = ? AND attempted_patch = ?
389
+ """, (f["error_signature"], f["attempted_patch"]))
390
+ if cursor.fetchone()["cnt"] == 0:
391
+ cursor.execute("""
392
+ INSERT INTO failed_fixes (error_signature, attempted_patch, failure_reason, agent_role)
393
+ VALUES (?, ?, ?, ?)
394
+ """, (f["error_signature"], f["attempted_patch"], f["failure_reason"], f["agent_role"]))
395
+
396
+ for les in SEED_LESSONS_LEARNED:
397
+ cursor.execute("""
398
+ SELECT COUNT(*) as cnt FROM lessons_learned
399
+ WHERE error_signature = ? AND page_context = ?
400
+ """, (les["error_signature"], les["page_context"]))
401
+ if cursor.fetchone()["cnt"] == 0:
402
+ cursor.execute("""
403
+ INSERT INTO lessons_learned
404
+ (page_context, error_signature, root_cause, failed_attempt, successful_fix, lesson_summary)
405
+ VALUES (?, ?, ?, ?, ?, ?)
406
+ """, (les["page_context"], les["error_signature"], les["root_cause"], les["failed_attempt"], les["successful_fix"], les["lesson_summary"]))
407
+ conn.commit()
408
+
409
+
410
+ # Stop-words list filtering generic stacktrace, code runtime & English grammar noise
411
+ STOP_WORDS = {
412
+ # English stop words
413
+ "a", "about", "above", "after", "again", "against", "all", "am", "an", "and",
414
+ "any", "are", "aren't", "as", "at", "be", "because", "been", "before", "being",
415
+ "below", "between", "both", "but", "by", "can", "cannot", "could", "couldn't",
416
+ "did", "didn't", "do", "does", "doesn't", "doing", "don't", "down", "during",
417
+ "each", "few", "for", "from", "further", "had", "hadn't", "has", "hasn't",
418
+ "have", "haven't", "having", "he", "her", "here", "hers", "herself", "him",
419
+ "himself", "his", "how", "i", "if", "in", "into", "is", "isn't", "it", "it's",
420
+ "its", "itself", "let's", "me", "more", "most", "mustn't", "my", "myself",
421
+ "no", "nor", "not", "of", "off", "on", "once", "only", "or", "other", "ought",
422
+ "our", "ours", "ourselves", "out", "over", "own", "same", "shan't", "she",
423
+ "should", "shouldn't", "so", "some", "such", "than", "that", "that's", "the",
424
+ "their", "theirs", "them", "themselves", "then", "there", "there's", "these",
425
+ "they", "they'd", "they'll", "they're", "they've", "this", "those", "through",
426
+ "to", "too", "under", "until", "up", "very", "was", "wasn't", "we", "we'd",
427
+ "we'll", "we're", "we've", "were", "weren't", "what", "what's", "when", "where",
428
+ "which", "while", "who", "whom", "why", "with", "won't", "would", "wouldn't",
429
+ "you", "you'd", "you'll", "you're", "you've", "your", "yours", "yourself",
430
+
431
+ # Java / Groovy / Selenium / Katalon Stacktrace & Runtime Boilerplate Noise
432
+ "org", "com", "net", "io", "java", "lang", "util", "reflect", "sun", "native",
433
+ "impl", "accessor", "unknown", "source", "line", "method", "thread", "run",
434
+ "call", "invoke", "invoker", "kms", "katalon", "core", "webui", "keyword",
435
+ "builtin", "driver", "webdriver", "remote", "http", "internal", "client",
436
+ "server", "session", "step", "tc", "test", "tests", "case", "suite", "runner",
437
+ "element", "elements", "locator", "find", "finding", "found", "selenium",
438
+ "openqa", "chrome", "firefox", "edge", "safari", "webkit",
439
+
440
+ # Generic Error Noise (present in almost all failure traces)
441
+ "exception", "error", "failed", "failure", "caused", "cause", "trace",
442
+ "stacktrace", "message", "warning", "info", "debug", "null", "object"
443
+ }
444
+
445
+
446
+ def tokenize(text):
447
+ """
448
+ Extracts tokens with CamelCase decomposition and Stop-words stripping.
449
+ Preserves specific domain identifiers while eliminating generic stacktrace noise.
450
+ """
451
+ if not text:
452
+ return []
453
+ words = re.findall(r'[a-zA-Z0-9_\-]+', text)
454
+ tokens = []
455
+ for w in words:
456
+ w_lower = w.lower().strip("-_")
457
+ # Filter Katalon / Framework built-in keyword class noise (e.g. ClickKeyword, SetTextKeyword)
458
+ if w_lower.endswith("keyword"):
459
+ continue
460
+ if len(w_lower) >= 2 and w_lower not in STOP_WORDS:
461
+ tokens.append(w_lower)
462
+ # Split CamelCase: "ElementClickIntercepted" -> "click", "intercepted"
463
+ camel_parts = re.findall(r'[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|\d|\W|$)|\d+', w)
464
+ if len(camel_parts) > 1:
465
+ for cp in camel_parts:
466
+ cp_lower = cp.lower().strip("-_")
467
+ if len(cp_lower) >= 2 and cp_lower not in STOP_WORDS and not cp_lower.endswith("keyword"):
468
+ tokens.append(cp_lower)
469
+ return tokens
470
+
471
+
472
+ def compute_tfidf_similarities(query, documents):
473
+ """
474
+ Computes TF-IDF weighted cosine similarity between a query and a candidate document corpus.
475
+ Applies inverse document frequency to dampen frequent boilerplate words and amplify
476
+ rare diagnostic markers (e.g. 'stale', 'intercepted', 'ng-invalid').
477
+ """
478
+ query_tokens = tokenize(query)
479
+ if not query_tokens or not documents:
480
+ return [0.0] * len(documents)
481
+
482
+ doc_tokens_list = [tokenize(doc) for doc in documents]
483
+ all_docs = [query_tokens] + doc_tokens_list
484
+ total_docs = len(all_docs)
485
+
486
+ # Document Frequency across the combined corpus
487
+ df = Counter()
488
+ for doc in all_docs:
489
+ for token in set(doc):
490
+ df[token] += 1
491
+
492
+ # Smoothed IDF: ln(1 + N / (1 + df)) + 1
493
+ idf = {t: math.log(1.0 + total_docs / (1.0 + freq)) + 1.0 for t, freq in df.items()}
494
+
495
+ def get_tfidf_vec(tokens):
496
+ tf = Counter(tokens)
497
+ vec = {}
498
+ for t, count in tf.items():
499
+ vec[t] = (1.0 + math.log(count)) * idf.get(t, 1.0)
500
+ return vec
501
+
502
+ def norm(vec):
503
+ return math.sqrt(sum(val ** 2 for val in vec.values()))
504
+
505
+ query_vec = get_tfidf_vec(query_tokens)
506
+ query_norm = norm(query_vec)
507
+ if not query_norm:
508
+ return [0.0] * len(documents)
509
+
510
+ scores = []
511
+ for doc_tokens in doc_tokens_list:
512
+ if not doc_tokens:
513
+ scores.append(0.0)
514
+ continue
515
+ doc_vec = get_tfidf_vec(doc_tokens)
516
+ doc_norm = norm(doc_vec)
517
+ if not doc_norm:
518
+ scores.append(0.0)
519
+ continue
520
+ dot = sum(query_vec[t] * doc_vec[t] for t in set(query_vec.keys()) & set(doc_vec.keys()))
521
+ scores.append(float(dot) / (query_norm * doc_norm))
522
+
523
+ return scores
524
+
525
+
526
+ def compute_cosine_similarity(text1, text2):
527
+ """
528
+ Computes tokenized Cosine Similarity between two texts with stop-words filtration.
529
+ """
530
+ tokens1 = tokenize(text1)
531
+ tokens2 = tokenize(text2)
532
+ if not tokens1 or not tokens2:
533
+ return 0.0
534
+ vec1 = Counter(tokens1)
535
+ vec2 = Counter(tokens2)
536
+ intersection = set(vec1.keys()) & set(vec2.keys())
537
+ if not intersection:
538
+ return 0.0
539
+ numerator = sum([vec1[x] * vec2[x] for x in intersection])
540
+ sum1 = sum([val**2 for val in vec1.values()])
541
+ sum2 = sum([val**2 for val in vec2.values()])
542
+ denominator = math.sqrt(sum1) * math.sqrt(sum2)
543
+ if not denominator:
544
+ return 0.0
545
+ return float(numerator) / denominator
546
+
547
+
548
+ def get_failed_fixes(error_signature):
549
+ """Retrieves all previously recorded failed fix attempts for this error signature."""
550
+ init_db(seed=True)
551
+ with get_db() as conn:
552
+ cursor = conn.cursor()
553
+ cursor.execute("""
554
+ SELECT * FROM failed_fixes
555
+ WHERE error_signature = ? OR error_signature LIKE ?
556
+ ORDER BY created_at DESC
557
+ """, (error_signature, f"%{error_signature}%"))
558
+ return [dict(r) for r in cursor.fetchall()]
559
+
560
+
561
+ @retry_on_locked()
562
+ def record_failed_fix(error_signature, attempted_patch, failure_reason, agent_role="pom-crafter"):
563
+ """Records a failed bug fix attempt into negative memory so AI agents will never repeat it."""
564
+ error_signature = sanitize_text(error_signature)
565
+ attempted_patch = sanitize_text(attempted_patch)
566
+ failure_reason = sanitize_text(failure_reason)
567
+ init_db(seed=True)
568
+ with get_db() as conn:
569
+ cursor = conn.cursor()
570
+ cursor.execute("""
571
+ INSERT INTO failed_fixes (error_signature, attempted_patch, failure_reason, agent_role)
572
+ VALUES (?, ?, ?, ?)
573
+ """, (error_signature, attempted_patch, failure_reason, agent_role))
574
+ conn.commit()
575
+ return True
576
+
577
+
578
+ def query_solution(error_signature, module_name="GLOBAL", threshold=0.35):
579
+ """
580
+ Two-Way Query:
581
+ 1. Returns verified working patch from positive memory.
582
+ 2. Attaches blacklist of previously failed fixes from negative memory.
583
+ """
584
+ init_db(seed=True)
585
+ with get_db() as conn:
586
+ cursor = conn.cursor()
587
+ # 1. Exact match with module
588
+ cursor.execute("""
589
+ SELECT * FROM healing_cache
590
+ WHERE error_signature = ? AND module_name = ?
591
+ """, (error_signature, module_name))
592
+ row = cursor.fetchone()
593
+ match_type = "EXACT_MODULE"
594
+
595
+ # 2. Fallback to GLOBAL match
596
+ if not row:
597
+ cursor.execute("""
598
+ SELECT * FROM healing_cache
599
+ WHERE error_signature = ? AND module_name = 'GLOBAL'
600
+ """, (error_signature,))
601
+ row = cursor.fetchone()
602
+ match_type = "GLOBAL_MATCH"
603
+
604
+ # 3. Fuzzy search on symptom/error
605
+ if not row:
606
+ cursor.execute("""
607
+ SELECT * FROM healing_cache
608
+ WHERE error_signature LIKE ? OR symptom LIKE ?
609
+ """, (f"%{error_signature}%", f"%{error_signature}%"))
610
+ row = cursor.fetchone()
611
+ match_type = "FUZZY_SQL"
612
+
613
+ # 4. Offline Semantic Vector TF-IDF Cosine Similarity
614
+ confidence = 1.0
615
+ if not row:
616
+ cursor.execute("SELECT * FROM healing_cache")
617
+ all_rows = cursor.fetchall()
618
+ if all_rows:
619
+ candidates_corpus = [
620
+ f"{c['error_signature']} {c['symptom']} {c['root_cause']}"
621
+ for c in all_rows
622
+ ]
623
+ scores = compute_tfidf_similarities(error_signature, candidates_corpus)
624
+ best_idx = -1
625
+ best_score = 0.0
626
+ for idx, score in enumerate(scores):
627
+ if score > best_score:
628
+ best_score = score
629
+ best_idx = idx
630
+
631
+ if best_idx >= 0 and best_score >= threshold:
632
+ row = all_rows[best_idx]
633
+ match_type = f"SEMANTIC_TFIDF ({best_score*100:.1f}%)"
634
+ confidence = best_score
635
+
636
+ # Query negative memory for this error
637
+ failed_fixes = get_failed_fixes(error_signature)
638
+
639
+ if row:
640
+ cursor.execute("""
641
+ UPDATE healing_cache
642
+ SET hit_count = hit_count + 1
643
+ WHERE id = ?
644
+ """, (row["id"],))
645
+ conn.commit()
646
+ result = dict(row)
647
+ patch = result.get("code_patch") or result.get("groovy_patch")
648
+ result["code_patch"] = patch
649
+ result["groovy_patch"] = patch
650
+ result["match_type"] = match_type
651
+ result["confidence"] = confidence
652
+ result["failed_fixes"] = failed_fixes
653
+ return result
654
+ elif failed_fixes:
655
+ # No solution yet, but we have failed fixes recorded!
656
+ return {
657
+ "error_signature": error_signature,
658
+ "module_name": module_name,
659
+ "symptom": "Unknown solution",
660
+ "root_cause": "Unknown",
661
+ "code_patch": None,
662
+ "groovy_patch": None,
663
+ "match_type": "NEGATIVE_MEMORY_ONLY",
664
+ "confidence": 0.0,
665
+ "failed_fixes": failed_fixes
666
+ }
667
+ return None
668
+
669
+
670
+ @retry_on_locked()
671
+ def learn_solution(error_signature, module_name, symptom, root_cause, groovy_patch, code_patch=None):
672
+ """Saves a verified solution into positive memory."""
673
+ patch = sanitize_text(code_patch or groovy_patch)
674
+ error_signature = sanitize_text(error_signature)
675
+ symptom = sanitize_text(symptom)
676
+ root_cause = sanitize_text(root_cause)
677
+ init_db(seed=True)
678
+ with get_db() as conn:
679
+ cursor = conn.cursor()
680
+ cursor.execute("""
681
+ INSERT INTO healing_cache (error_signature, module_name, symptom, root_cause, groovy_patch, code_patch)
682
+ VALUES (?, ?, ?, ?, ?, ?)
683
+ ON CONFLICT(error_signature, module_name) DO UPDATE SET
684
+ symptom = excluded.symptom,
685
+ root_cause = excluded.root_cause,
686
+ groovy_patch = excluded.groovy_patch,
687
+ code_patch = excluded.code_patch
688
+ """, (error_signature, module_name or "GLOBAL", symptom, root_cause, patch, patch))
689
+ conn.commit()
690
+ return True
691
+
692
+
693
+ @retry_on_locked()
694
+ def sync_db():
695
+ """Bidirectional synchronization between Global Central Memory and Local Project Cache."""
696
+ global DB_FILE
697
+ # Initialize schemas for both Global and Local stores prior to sync
698
+ DB_FILE = resolve_db_path(use_local=False)
699
+ init_db(seed=True, target_db=GLOBAL_DB)
700
+ DB_FILE = resolve_db_path(use_local=True)
701
+ init_db(seed=False, target_db=LOCAL_DB)
702
+
703
+ with get_db(GLOBAL_DB) as g_conn, get_db(LOCAL_DB) as l_conn:
704
+ # 1. Sync positive cache
705
+ g_rows = g_conn.execute("SELECT * FROM healing_cache").fetchall()
706
+ for r in g_rows:
707
+ l_conn.execute("""
708
+ INSERT INTO healing_cache (error_signature, module_name, symptom, root_cause, groovy_patch, hit_count)
709
+ VALUES (?, ?, ?, ?, ?, ?)
710
+ ON CONFLICT(error_signature, module_name) DO UPDATE SET
711
+ symptom = excluded.symptom,
712
+ root_cause = excluded.root_cause,
713
+ groovy_patch = excluded.groovy_patch
714
+ """, (r["error_signature"], r["module_name"], r["symptom"], r["root_cause"], r["groovy_patch"], r["hit_count"]))
715
+ l_conn.commit()
716
+
717
+ l_rows = l_conn.execute("SELECT * FROM healing_cache").fetchall()
718
+ for r in l_rows:
719
+ g_conn.execute("""
720
+ INSERT INTO healing_cache (error_signature, module_name, symptom, root_cause, groovy_patch, hit_count)
721
+ VALUES (?, ?, ?, ?, ?, ?)
722
+ ON CONFLICT(error_signature, module_name) DO UPDATE SET
723
+ symptom = excluded.symptom,
724
+ root_cause = excluded.root_cause,
725
+ groovy_patch = excluded.groovy_patch
726
+ """, (r["error_signature"], r["module_name"], r["symptom"], r["root_cause"], r["groovy_patch"], r["hit_count"]))
727
+ g_conn.commit()
728
+
729
+ # 2. Sync negative failed fixes
730
+ g_failed = g_conn.execute("SELECT * FROM failed_fixes").fetchall()
731
+ for f in g_failed:
732
+ l_conn.execute("""
733
+ INSERT OR IGNORE INTO failed_fixes (error_signature, attempted_patch, failure_reason, agent_role)
734
+ VALUES (?, ?, ?, ?)
735
+ """, (f["error_signature"], f["attempted_patch"], f["failure_reason"], f["agent_role"]))
736
+ l_conn.commit()
737
+
738
+ # 3. Sync lessons learned
739
+ g_lessons = g_conn.execute("SELECT * FROM lessons_learned").fetchall()
740
+ for r in g_lessons:
741
+ l_conn.execute("""
742
+ INSERT OR IGNORE INTO lessons_learned
743
+ (page_context, error_signature, root_cause, failed_attempt, successful_fix, lesson_summary, hit_count)
744
+ VALUES (?, ?, ?, ?, ?, ?, ?)
745
+ """, (r["page_context"], r["error_signature"], r["root_cause"], r["failed_attempt"], r["successful_fix"], r["lesson_summary"], r["hit_count"]))
746
+ l_conn.commit()
747
+
748
+ return len(g_rows)
749
+
750
+
751
+ @retry_on_locked()
752
+ def record_lesson(page_context, error_signature, root_cause, failed_attempt, successful_fix, lesson_summary):
753
+ """
754
+ Episodic Reflexion Memory:
755
+ Records a concise lesson learned (maximum 2 lines) into SQLite for cross-session reflection after secret sanitization.
756
+ """
757
+ init_db(seed=True)
758
+ page_context = sanitize_text(page_context or "GLOBAL")
759
+ error_signature = sanitize_text(error_signature)
760
+ root_cause = sanitize_text(root_cause)
761
+ failed_attempt = sanitize_text(failed_attempt)
762
+ successful_fix = sanitize_text(successful_fix)
763
+ lesson_summary = sanitize_text(lesson_summary.strip())
764
+ with get_db() as conn:
765
+ cursor = conn.cursor()
766
+ cursor.execute("""
767
+ INSERT INTO lessons_learned
768
+ (page_context, error_signature, root_cause, failed_attempt, successful_fix, lesson_summary)
769
+ VALUES (?, ?, ?, ?, ?, ?)
770
+ """, (page_context, error_signature, root_cause, failed_attempt, successful_fix, lesson_summary))
771
+ conn.commit()
772
+ return True
773
+
774
+
775
+ def query_lessons(context_or_keyword, limit=2):
776
+ """
777
+ Episodic Reflexion Memory Query:
778
+ Retrieves the top N (default: 2) most relevant historical lessons learned for a given page, flow, or error.
779
+ Returns: List[Dict[str, Any]]
780
+ """
781
+ init_db(seed=True)
782
+ if not context_or_keyword:
783
+ context_or_keyword = "GLOBAL"
784
+
785
+ with get_db() as conn:
786
+ cursor = conn.cursor()
787
+ rows = cursor.execute("SELECT * FROM lessons_learned").fetchall()
788
+ if not rows:
789
+ return []
790
+
791
+ scored = []
792
+ q_lower = context_or_keyword.lower()
793
+ for r in rows:
794
+ combined = f"{r['page_context']} {r['error_signature']} {r['lesson_summary']} {r['root_cause'] or ''}"
795
+ sim_score = compute_cosine_similarity(context_or_keyword, combined)
796
+
797
+ # Boost score for explicit matches in page_context or error_signature
798
+ if r["page_context"] and r["page_context"].lower() in q_lower:
799
+ sim_score += 0.40
800
+ if r["error_signature"] and r["error_signature"].lower() in q_lower:
801
+ sim_score += 0.35
802
+
803
+ scored.append((sim_score, dict(r)))
804
+
805
+ scored.sort(key=lambda x: x[0], reverse=True)
806
+ top_results = [item[1] for item in scored[:limit]]
807
+
808
+ for item in top_results:
809
+ cursor.execute("UPDATE lessons_learned SET hit_count = hit_count + 1 WHERE id = ?", (item["id"],))
810
+ conn.commit()
811
+
812
+ return top_results
813
+
814
+
815
+ @retry_on_locked()
816
+ def record_test_telemetry(test_id, status, is_retry=0, duration_ms=0.0, error_signature="", context="", target_db=None):
817
+ """
818
+ Records an individual test execution into persistent SQLite telemetry.
819
+ Used for computing 30-day historical flakiness index and auto-quarantine decisions.
820
+ """
821
+ error_signature = sanitize_text(error_signature)
822
+ context = sanitize_text(context)
823
+ init_db(seed=True, target_db=target_db)
824
+ current_db = target_db or DB_FILE
825
+ with get_db(current_db) as conn:
826
+ cursor = conn.cursor()
827
+ cursor.execute("""
828
+ INSERT INTO test_telemetry (test_id, status, is_retry, duration_ms, error_signature, context)
829
+ VALUES (?, ?, ?, ?, ?, ?)
830
+ """, (test_id, status.upper(), int(is_retry), float(duration_ms), error_signature, context))
831
+ conn.commit()
832
+ return True
833
+
834
+
835
+ def get_flaky_telemetry(days=30, min_runs=2, threshold=0.15, target_db=None):
836
+ """
837
+ Queries historical test telemetry and calculates the Flaky Ratio across the given window.
838
+ Flaky Ratio = (retry_pass_count + fail_then_pass_transitions) / total_runs.
839
+ """
840
+ init_db(seed=True, target_db=target_db)
841
+ current_db = target_db or DB_FILE
842
+ with get_db(current_db) as conn:
843
+ cursor = conn.cursor()
844
+ cursor.execute("""
845
+ SELECT
846
+ test_id,
847
+ COUNT(*) as total_runs,
848
+ SUM(CASE WHEN status = 'PASS' THEN 1 ELSE 0 END) as pass_count,
849
+ SUM(CASE WHEN status = 'FAIL' THEN 1 ELSE 0 END) as fail_count,
850
+ SUM(CASE WHEN status = 'PASS' AND is_retry = 1 THEN 1 ELSE 0 END) as retry_pass_count,
851
+ AVG(duration_ms) as avg_duration_ms
852
+ FROM test_telemetry
853
+ WHERE run_timestamp >= datetime('now', '-' || ? || ' days')
854
+ GROUP BY test_id
855
+ HAVING total_runs >= ?
856
+ """, (days, min_runs))
857
+ rows = cursor.fetchall()
858
+ candidates = []
859
+ for r in rows:
860
+ total = r["total_runs"]
861
+ retry_passes = r["retry_pass_count"] or 0
862
+ fails = r["fail_count"] or 0
863
+ passes = r["pass_count"] or 0
864
+ # If test both passes and fails across runs, or passes on retry
865
+ flaky_events = retry_passes + (1 if fails > 0 and passes > 0 else 0)
866
+ flaky_ratio = round(min(1.0, flaky_events / max(1, total)), 3)
867
+ quarantine = flaky_ratio >= threshold and passes > 0
868
+
869
+ candidates.append({
870
+ "test_id": r["test_id"],
871
+ "total_runs": total,
872
+ "pass_count": passes,
873
+ "fail_count": fails,
874
+ "retry_pass_count": retry_passes,
875
+ "flaky_ratio": flaky_ratio,
876
+ "avg_duration_ms": round(r["avg_duration_ms"] or 0.0, 1),
877
+ "quarantine_recommended": quarantine
878
+ })
879
+ candidates.sort(key=lambda x: x["flaky_ratio"], reverse=True)
880
+ return candidates
881
+
882
+
883
+ def get_stats():
884
+ init_db(seed=True)
885
+ with get_db() as conn:
886
+ cursor = conn.cursor()
887
+ cursor.execute("SELECT COUNT(*) as total_solutions, SUM(hit_count) as total_hits FROM healing_cache")
888
+ row = cursor.fetchone()
889
+ total_sol = row["total_solutions"] or 0
890
+ total_hits = row["total_hits"] or 0
891
+ saved_tokens = total_hits * 2000
892
+
893
+ cursor.execute("SELECT COUNT(*) as total_failed FROM failed_fixes")
894
+ total_failed = cursor.fetchone()["total_failed"] or 0
895
+
896
+ cursor.execute("SELECT COUNT(*) as total_lessons FROM lessons_learned")
897
+ total_lessons = cursor.fetchone()["total_lessons"] or 0
898
+
899
+ cursor.execute("SELECT COUNT(*) as total_telemetry FROM test_telemetry")
900
+ total_telemetry = cursor.fetchone()["total_telemetry"] or 0
901
+
902
+ cursor.execute("SELECT error_signature, module_name, hit_count FROM healing_cache ORDER BY hit_count DESC")
903
+ top_solutions = [dict(r) for r in cursor.fetchall()]
904
+
905
+ return {
906
+ "total_solutions": total_sol,
907
+ "total_hits": total_hits,
908
+ "total_failed_fixes": total_failed,
909
+ "total_lessons_learned": total_lessons,
910
+ "total_telemetry_records": total_telemetry,
911
+ "estimated_tokens_saved": saved_tokens,
912
+ "solutions": top_solutions
913
+ }
914
+
915
+
916
+ @retry_on_locked()
917
+ def purge_cache(keep_seeds=True, target_db=None):
918
+ """Clears SQLite memory cache, preserving default seed solutions if keep_seeds=True."""
919
+ target = target_db or DB_FILE
920
+ init_db(seed=False, target_db=target)
921
+ with get_db(target) as conn:
922
+ cursor = conn.cursor()
923
+ cursor.execute("DELETE FROM failed_fixes")
924
+ cursor.execute("DELETE FROM lessons_learned")
925
+ cursor.execute("DELETE FROM test_telemetry")
926
+ if keep_seeds:
927
+ cursor.execute("DELETE FROM healing_cache WHERE module_name != 'GLOBAL'")
928
+ else:
929
+ cursor.execute("DELETE FROM healing_cache")
930
+ conn.commit()
931
+ if keep_seeds:
932
+ init_db(seed=True, target_db=target)
933
+ return True
934
+
935
+
936
+ def export_cache(target_db=None):
937
+ """Exports all positive solutions, negative failed fixes, and lessons learned to a structured dictionary."""
938
+ target = target_db or DB_FILE
939
+ init_db(seed=True, target_db=target)
940
+ with get_db(target) as conn:
941
+ healing = [dict(r) for r in conn.execute("SELECT * FROM healing_cache").fetchall()]
942
+ failed = [dict(r) for r in conn.execute("SELECT * FROM failed_fixes").fetchall()]
943
+ lessons = [dict(r) for r in conn.execute("SELECT * FROM lessons_learned").fetchall()]
944
+ telemetry = [dict(r) for r in conn.execute("SELECT * FROM test_telemetry").fetchall()]
945
+ return {
946
+ "exported_at": datetime.now().isoformat(),
947
+ "database": target,
948
+ "healing_cache": healing,
949
+ "failed_fixes": failed,
950
+ "lessons_learned": lessons,
951
+ "test_telemetry": telemetry,
952
+ }
953
+
954
+
955
+ def main():
956
+ global DB_FILE
957
+ parser = argparse.ArgumentParser(description="Enterprise Central Agent Memory & Self-Healing Resolver")
958
+ parser.add_argument("--local", action="store_true", help="Force local project memory_cache.db instead of Global Central Memory")
959
+ subparsers = parser.add_subparsers(dest="command")
960
+
961
+ # Query command
962
+ query_parser = subparsers.add_parser("query", help="Query solution & anti-patches for an error (Zero Token)")
963
+ query_parser.add_argument("--error", required=True, help="Error signature or keyword")
964
+ query_parser.add_argument("--module", default="GLOBAL", help="Module or Page Class name")
965
+
966
+ # Learn command (Positive Memory)
967
+ learn_parser = subparsers.add_parser("learn", help="Save verified solution into positive memory")
968
+ learn_parser.add_argument("--error", required=True, help="Error signature")
969
+ learn_parser.add_argument("--module", default="GLOBAL", help="Module or Page Class name")
970
+ learn_parser.add_argument("--symptom", required=True, help="Symptom description")
971
+ learn_parser.add_argument("--cause", required=True, help="Root cause")
972
+ learn_parser.add_argument("--patch", required=True, help="Working patch code")
973
+
974
+ # Record-Failed command (Negative Memory)
975
+ failed_parser = subparsers.add_parser("record-failed", help="Record a failed fix attempt into negative memory blacklist")
976
+ failed_parser.add_argument("--error", required=True, help="Error signature being diagnosed")
977
+ failed_parser.add_argument("--patch", required=True, help="The failed patch code or attempted action")
978
+ failed_parser.add_argument("--reason", required=True, help="Why this fix failed or regression caused")
979
+ failed_parser.add_argument("--role", default="pom-crafter", help="Agent role that attempted the fix")
980
+
981
+ # Record-Lesson command (Episodic Reflexion Memory)
982
+ lesson_record_parser = subparsers.add_parser("record-lesson", help="Record a 2-line lesson learned into episodic memory")
983
+ lesson_record_parser.add_argument("--context", default="GLOBAL", help="Page name or workflow context (e.g., 'Checkout', 'Login')")
984
+ lesson_record_parser.add_argument("--error", required=True, help="Error signature or breaking symptom")
985
+ lesson_record_parser.add_argument("--cause", default="", help="Root cause explanation")
986
+ lesson_record_parser.add_argument("--failed", default="", help="Failed attempt or anti-pattern")
987
+ lesson_record_parser.add_argument("--fix", default="", help="Successful fix pattern")
988
+ lesson_record_parser.add_argument("--lesson", required=True, help="Short lesson summary (maximum 2 lines)")
989
+
990
+ # Get-Lessons command (Episodic Reflexion Memory Query)
991
+ lesson_get_parser = subparsers.add_parser("get-lessons", help="Retrieve top 2 historical lessons learned for context")
992
+ lesson_get_parser.add_argument("--context", required=True, help="Page, flow, or error keyword to match")
993
+ lesson_get_parser.add_argument("--limit", type=int, default=2, help="Number of lessons to retrieve (default: 2)")
994
+
995
+ # Record-Telemetry command (Historical Telemetry)
996
+ telem_record_parser = subparsers.add_parser("record-telemetry", help="Record individual test run outcome into telemetry")
997
+ telem_record_parser.add_argument("--test-id", required=True, help="Test case identifier or class#method")
998
+ telem_record_parser.add_argument("--status", required=True, choices=["PASS", "FAIL"], help="Execution status")
999
+ telem_record_parser.add_argument("--retry", type=int, default=0, help="Whether this run was an automated retry (1 or 0)")
1000
+ telem_record_parser.add_argument("--duration", type=float, default=0.0, help="Run duration in ms")
1001
+ telem_record_parser.add_argument("--error", default="", help="Error signature if failed")
1002
+ telem_record_parser.add_argument("--context", default="", help="Environment or workflow context")
1003
+
1004
+ # Get-Flaky command (Historical Flakiness Query)
1005
+ flaky_get_parser = subparsers.add_parser("get-flaky", help="Query historical flaky test candidates from telemetry")
1006
+ flaky_get_parser.add_argument("--days", type=int, default=30, help="Lookback window in days (default: 30)")
1007
+ flaky_get_parser.add_argument("--min-runs", type=int, default=2, help="Minimum runs required (default: 2)")
1008
+ flaky_get_parser.add_argument("--threshold", type=float, default=0.15, help="Flaky ratio threshold for quarantine (default: 0.15)")
1009
+
1010
+ # Stats command
1011
+ subparsers.add_parser("stats", help="View memory cache statistics (Positive & Negative)")
1012
+
1013
+ # Fingerprint command (Deterministic Error Signature Hashing)
1014
+ fp_parser = subparsers.add_parser("fingerprint", help="Generate deterministic DJB2 error fingerprint")
1015
+ fp_parser.add_argument("--type", default="UnknownError", help="Error type/class (e.g. AssertionError)")
1016
+ fp_parser.add_argument("--msg", required=True, help="Error message / symptom")
1017
+ fp_parser.add_argument("--stack", default="", help="Optional stack anchor or file:function")
1018
+
1019
+ # Detect-Repeated command (Group errors and flag repeated errors)
1020
+ rep_parser = subparsers.add_parser("detect-repeated", help="Group errors by fingerprint and flag repeated occurrences")
1021
+ rep_parser.add_argument("--file", required=True, help="Path to JSON file containing list of error objects")
1022
+ rep_parser.add_argument("--threshold", type=int, default=3, help="Repeat threshold (default: 3)")
1023
+
1024
+ # Sync command
1025
+ subparsers.add_parser("sync", help="Synchronize Global Central Memory with Local Project Cache")
1026
+
1027
+ # Purge command
1028
+ purge_parser = subparsers.add_parser("purge", help="Clear SQLite memory cache")
1029
+ purge_parser.add_argument("--all", action="store_true", help="Clear all entries including default seed solutions")
1030
+
1031
+ # Export command
1032
+ export_parser = subparsers.add_parser("export", help="Export memory cache and lessons to JSON")
1033
+ export_parser.add_argument("-o", "--output", help="Output file path (default: stdout)")
1034
+
1035
+ # Init command
1036
+ subparsers.add_parser("init", help="Initialize and seed database")
1037
+
1038
+ args = parser.parse_args()
1039
+ if args.local:
1040
+ DB_FILE = resolve_db_path(use_local=True)
1041
+ else:
1042
+ DB_FILE = resolve_db_path(use_local=False)
1043
+
1044
+ if args.command == "query":
1045
+ sol = query_solution(args.error, args.module)
1046
+ if sol:
1047
+ print("==================================================")
1048
+ if sol.get("groovy_patch"):
1049
+ print("✅ [CACHE HIT - 0 TOKENS] Found pre-tested solution!")
1050
+ print(f"Database Scope : {'LOCAL' if args.local else 'GLOBAL CENTRAL (~/.agent_memory)'}")
1051
+ print(f"Match Strategy : {sol.get('match_type', 'EXACT')}")
1052
+ print(f"Error Signature : {sol['error_signature']}")
1053
+ print(f"Module Scope : {sol['module_name']}")
1054
+ print(f"Root Cause : {sol['root_cause']}")
1055
+ print(f"Hit Count : {sol.get('hit_count', 0)}")
1056
+ print("--------------------------------------------------")
1057
+ print("💡 Recommended Healing Patch:")
1058
+ print(sol["groovy_patch"])
1059
+ else:
1060
+ print(f"âš ī¸ [NO VERIFIED SOLUTION YET] for error: '{args.error}'")
1061
+
1062
+ failed_fixes = sol.get("failed_fixes", [])
1063
+ if failed_fixes:
1064
+ print("--------------------------------------------------")
1065
+ print(f"đŸšĢ FORBIDDEN ANTI-PATCHES ({len(failed_fixes)} previously failed - DO NOT REPEAT):")
1066
+ for idx, ff in enumerate(failed_fixes, 1):
1067
+ print(f" {idx}. [FAILED ATTEMPT by {ff.get('agent_role', 'agent')}]:")
1068
+ print(f" Patch : {ff.get('attempted_patch')}")
1069
+ print(f" Reason: {ff.get('failure_reason')}")
1070
+ print("==================================================")
1071
+ else:
1072
+ print(f"❌ [CACHE MISS] No cached solution found for: '{args.error}'. Triggering LLM reasoning.")
1073
+ sys.exit(1)
1074
+
1075
+ elif args.command == "learn":
1076
+ ok = learn_solution(args.error, args.module, args.symptom, args.cause, args.patch)
1077
+ if ok:
1078
+ print(f"✅ [POSITIVE MEMORY LEARNED] Solution for '{args.error}' ({args.module}) cached successfully.")
1079
+
1080
+ elif args.command == "record-failed":
1081
+ ok = record_failed_fix(args.error, args.patch, args.reason, args.role)
1082
+ if ok:
1083
+ print(f"đŸšĢ [NEGATIVE MEMORY RECORDED] Failed fix attempt for '{args.error}' added to blacklist.")
1084
+ print(f" Agent Role : {args.role}")
1085
+ print(f" Reason : {args.reason}")
1086
+
1087
+ elif args.command == "record-lesson":
1088
+ ok = record_lesson(args.context, args.error, args.cause, args.failed, args.fix, args.lesson)
1089
+ if ok:
1090
+ print(f"🧠 [EPISODIC REFLEXION RECORDED] Lesson for context '{args.context}' cached successfully.")
1091
+ print(f" Error Signature : {args.error}")
1092
+ print(f" Lesson (2 lines): {args.lesson.strip()}")
1093
+
1094
+ elif args.command == "get-lessons":
1095
+ lessons = query_lessons(args.context, limit=args.limit)
1096
+ print("==================================================")
1097
+ print(f"🧠 [EPISODIC REFLEXION MEMORY] Top {len(lessons)} Lessons for: '{args.context}'")
1098
+ print("==================================================")
1099
+ if not lessons:
1100
+ print(" (Zero relevant lessons in cache yet. Proceeding with clean reasoning.)")
1101
+ else:
1102
+ for idx, les in enumerate(lessons, 1):
1103
+ print(f"📌 [Lesson {idx}] Context: {les['page_context']} | Trigger: {les['error_signature']}")
1104
+ print(f" 💡 Rule: {les['lesson_summary']}")
1105
+ if les.get("failed_attempt") or les.get("successful_fix"):
1106
+ print(f" âš ī¸ Anti-Pattern: {les.get('failed_attempt') or 'N/A'}")
1107
+ print(f" ✅ Proven Fix : {les.get('successful_fix') or 'N/A'}")
1108
+ print("==================================================")
1109
+
1110
+ elif args.command == "record-telemetry":
1111
+ ok = record_test_telemetry(
1112
+ args.test_id,
1113
+ args.status,
1114
+ is_retry=args.retry,
1115
+ duration_ms=args.duration,
1116
+ error_signature=args.error,
1117
+ context=args.context
1118
+ )
1119
+ if ok:
1120
+ print(f"📊 [TELEMETRY RECORDED] {args.test_id} -> {args.status} (Retry={args.retry}, {args.duration}ms)")
1121
+
1122
+ elif args.command == "get-flaky":
1123
+ flaky_list = get_flaky_telemetry(days=args.days, min_runs=args.min_runs, threshold=args.threshold)
1124
+ print("==================================================")
1125
+ print(f"📈 [HISTORICAL FLAKINESS TELEMETRY ({args.days} Days)]")
1126
+ print("==================================================")
1127
+ if not flaky_list:
1128
+ print(" (Zero flaky tests detected above threshold. Suite is stable.)")
1129
+ else:
1130
+ for item in flaky_list:
1131
+ status_icon = "🚨 [QUARANTINE]" if item["quarantine_recommended"] else "â„šī¸ [OBSERVE]"
1132
+ print(f"{status_icon} {item['test_id']}")
1133
+ print(f" Runs: {item['total_runs']} | Passes: {item['pass_count']} | Fails: {item['fail_count']} | Retry Passes: {item['retry_pass_count']}")
1134
+ print(f" Flaky Ratio: {item['flaky_ratio']*100:.1f}% | Avg Duration: {item['avg_duration_ms']}ms")
1135
+ print("==================================================")
1136
+
1137
+ elif args.command == "stats":
1138
+ stats = get_stats()
1139
+ print("==================================================")
1140
+ print(f"📊 AGENT MEMORY CACHE STATISTICS ({'LOCAL' if args.local else 'GLOBAL CENTRAL'})")
1141
+ print(f"Database Path : {DB_FILE}")
1142
+ print(f"Verified Solutions (✅) : {stats['total_solutions']}")
1143
+ print(f"Failed Fixes Blacklist (đŸšĢ): {stats['total_failed_fixes']}")
1144
+ print(f"Lessons Learned (🧠) : {stats.get('total_lessons_learned', 0)}")
1145
+ print(f"Total Cache Hits : {stats['total_hits']}")
1146
+ print(f"Estimated Tokens Saved : ~{stats['estimated_tokens_saved']:,} tokens")
1147
+ print("--------------------------------------------------")
1148
+ print("Top Solutions by Hit Count:")
1149
+ for s in stats["solutions"]:
1150
+ print(f" - [{s['hit_count']} hits] {s['error_signature']} ({s['module_name']})")
1151
+ print("==================================================")
1152
+
1153
+ elif args.command == "sync":
1154
+ count = sync_db()
1155
+ print(f"✅ [MEMORY SYNC] Bidirectional sync completed ({count} solutions synchronized between Global & Local).")
1156
+
1157
+ elif args.command == "purge":
1158
+ all_entries = getattr(args, "all", False)
1159
+ purge_cache(keep_seeds=not all_entries)
1160
+ scope_str = "All memory entries cleared (including default seeds)" if all_entries else "User entries cleared (seed solutions preserved)"
1161
+ print(f"✅ [MEMORY PURGE] SQLite cache purged: {scope_str} at {DB_FILE}")
1162
+
1163
+ elif args.command == "export":
1164
+ data = export_cache()
1165
+ if getattr(args, "output", None):
1166
+ with open(args.output, "w", encoding="utf-8") as f:
1167
+ json.dump(data, f, indent=2)
1168
+ print(f"✅ [MEMORY EXPORT] Exported memory cache to: {args.output}")
1169
+ else:
1170
+ print(json.dumps(data, indent=2))
1171
+
1172
+ elif args.command == "fingerprint":
1173
+ fp = compute_error_fingerprint(args.type, args.msg, args.stack)
1174
+ print(f"🔑 Error Fingerprint: {fp}")
1175
+ print(f" Normalized Type : {args.type.strip().lower()}")
1176
+ print(f" Raw Message : {args.msg[:120]}")
1177
+ if args.stack:
1178
+ print(f" Stack Anchor : {args.stack}")
1179
+
1180
+ elif args.command == "detect-repeated":
1181
+ if not os.path.exists(args.file):
1182
+ print(f"❌ Error file not found: {args.file}")
1183
+ sys.exit(1)
1184
+ with open(args.file, "r", encoding="utf-8", errors="replace") as f:
1185
+ error_data = json.load(f)
1186
+ if isinstance(error_data, dict) and "errors" in error_data:
1187
+ error_data = error_data["errors"]
1188
+ elif not isinstance(error_data, list):
1189
+ error_data = [error_data]
1190
+ grouped = group_errors_by_fingerprint(error_data, repeat_threshold=args.threshold)
1191
+ print("==================================================")
1192
+ print(f"🔍 [ERROR FINGERPRINT GROUPING] Processed {len(error_data)} errors -> {len(grouped)} unique groups")
1193
+ print("==================================================")
1194
+ repeated_count = 0
1195
+ for fp, group in grouped.items():
1196
+ status_tag = f"🚨 [REPEATED ERROR >= {args.threshold}x]" if group["is_repeated"] else "â„šī¸ [OBSERVE]"
1197
+ if group["is_repeated"]:
1198
+ repeated_count += 1
1199
+ print(f"{status_tag} {fp} ({group['count']}x)")
1200
+ print(f" Type: {group['error_type']} | Sample: {group['sample_message'][:100]}")
1201
+ print("==================================================")
1202
+ if repeated_count > 0:
1203
+ print(f"âš ī¸ Alert: {repeated_count} error fingerprints exceeded repeat threshold ({args.threshold}x).")
1204
+ sys.exit(2)
1205
+ else:
1206
+ print("✅ Zero repeated errors exceeded threshold.")
1207
+
1208
+ elif args.command == "init" or args.command is None:
1209
+ init_db(seed=True)
1210
+ print(f"✅ Central Agent Memory initialized at: {DB_FILE}")
1211
+
1212
+
1213
+ if __name__ == "__main__":
1214
+ main()