@teevee98/synapse-hub 0.0.0-stage → 3.8.3

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 +171 -0
  190. package/README.md +170 -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 +198 -0
  196. package/docs/ARCHITECTURE.md +199 -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 +174 -0
  200. package/docs/CLI_REFERENCE.md +176 -0
  201. package/docs/CONTRIBUTING.en.md +49 -0
  202. package/docs/CONTRIBUTING.md +49 -0
  203. package/docs/PERFORMANCE_AUDIT_REPORT.md +783 -0
  204. package/docs/PLUGIN_DEVELOPMENT_GUIDE.md +127 -0
  205. package/docs/QUALITY_GATES.en.md +118 -0
  206. package/docs/QUALITY_GATES.md +118 -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 +1358 -0
  212. package/docs/schemas/synapse.config.schema.json +86 -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 +31 -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 +2074 -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 +262 -0
  244. package/tools/api_drift_sentinel.py +208 -0
  245. package/tools/api_fuzzer.py +762 -0
  246. package/tools/author_integrity.py +190 -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 +2403 -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 +306 -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 +725 -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 +1271 -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,905 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 Thế Vị (@TeeVee98). All rights reserved.
2
+ # SPDX-License-Identifier: MIT
3
+ # Project: Synapse-Hub (https://github.com/TeeVee98/Synapse-Hub)
4
+
5
+ """
6
+ tools/core/memory_bus.py — Unified QA Memory Bus Architecture
7
+ --------------------------------------------------------------
8
+ Provides a centralized, SQLite WAL-mode persistent memory bus (.synapse/memory.db)
9
+ unifying 5 critical QA operating partitions:
10
+ 1. blocks: Core environment, authentication, and session memory blocks.
11
+ 2. actor_mailbox: Asynchronous actor-to-actor message queues for swarm agents.
12
+ 3. skill_vault: Persistent store of verified Page Classes and interaction skills.
13
+ 4. healing_cache: Closed-loop error signatures, root causes, and verified code patches.
14
+ 5. event_stream: Deterministic, immutable hash-chained execution timeline with checkpoints.
15
+
16
+ Features:
17
+ - SQLite WAL (Write-Ahead Logging) mode for concurrent read/write throughput.
18
+ - Full ACID transaction support with atomic commits and automatic rollback on test abort.
19
+ - Named savepoints for nested transaction isolation.
20
+ - Automatic cryptographic SHA-256 event chaining for stream tamper evidence.
21
+ """
22
+
23
+ import os
24
+ import random
25
+ import json
26
+ import uuid
27
+ import sqlite3
28
+ import hashlib
29
+ import threading
30
+ from datetime import datetime, timezone
31
+ from contextlib import contextmanager
32
+ from typing import Dict, Any, List, Optional, Tuple, Generator
33
+
34
+ GENESIS_HASH = "0" * 64
35
+
36
+
37
+ def _now_iso() -> str:
38
+ return datetime.now(timezone.utc).isoformat()
39
+
40
+
41
+ def _json_dumps(data: Any) -> str:
42
+ return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
43
+
44
+
45
+ def _json_loads(text: str) -> Any:
46
+ try:
47
+ return json.loads(text)
48
+ except Exception:
49
+ return text
50
+
51
+
52
+ class UnifiedMemoryBus:
53
+ """
54
+ Centralized persistent memory bus coordinating multi-agent state across
55
+ blocks, actor_mailbox, skill_vault, healing_cache, and event_stream.
56
+ """
57
+
58
+ def __init__(self, db_path: Optional[str] = None):
59
+ if db_path is None:
60
+ repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
61
+ synapse_dir = os.path.join(repo_root, ".synapse")
62
+ os.makedirs(synapse_dir, exist_ok=True)
63
+ self.db_path = os.path.join(synapse_dir, "memory.db")
64
+ else:
65
+ if db_path != ":memory:":
66
+ parent = os.path.dirname(os.path.abspath(db_path))
67
+ if parent:
68
+ os.makedirs(parent, exist_ok=True)
69
+ self.db_path = db_path
70
+
71
+ self._lock = threading.RLock()
72
+ self._conn = sqlite3.connect(
73
+ self.db_path,
74
+ check_same_thread=False,
75
+ timeout=10.0,
76
+ isolation_level=None # Explicit autocommit mode, transactions handled manually
77
+ )
78
+ self._conn.row_factory = sqlite3.Row
79
+ self._in_transaction = False
80
+ self._savepoint_depth = 0
81
+ self._init_pragmas_and_schema()
82
+
83
+ def _init_pragmas_and_schema(self):
84
+ with self._lock:
85
+ cur = self._conn.cursor()
86
+ if self.db_path != ":memory:":
87
+ cur.execute("PRAGMA journal_mode = WAL;")
88
+ cur.execute("PRAGMA synchronous = NORMAL;")
89
+ cur.execute("PRAGMA foreign_keys = ON;")
90
+ cur.execute("PRAGMA busy_timeout = 5000;")
91
+
92
+ # 1. Blocks Partition
93
+ cur.execute("""
94
+ CREATE TABLE IF NOT EXISTS memory_blocks (
95
+ block_id TEXT PRIMARY KEY,
96
+ scope TEXT NOT NULL DEFAULT 'global',
97
+ label TEXT NOT NULL,
98
+ content TEXT NOT NULL,
99
+ tags TEXT DEFAULT '',
100
+ created_at TEXT NOT NULL,
101
+ updated_at TEXT NOT NULL,
102
+ UNIQUE(scope, label)
103
+ );
104
+ """)
105
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_blocks_scope ON memory_blocks(scope);")
106
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_blocks_label ON memory_blocks(label);")
107
+
108
+ # 2. Actor Mailbox Partition
109
+ cur.execute("""
110
+ CREATE TABLE IF NOT EXISTS actor_mailbox (
111
+ message_id TEXT PRIMARY KEY,
112
+ session_id TEXT,
113
+ sender TEXT NOT NULL,
114
+ recipient TEXT NOT NULL,
115
+ stage TEXT NOT NULL,
116
+ payload TEXT NOT NULL,
117
+ status TEXT NOT NULL DEFAULT 'PENDING',
118
+ created_at TEXT NOT NULL,
119
+ read_at TEXT
120
+ );
121
+ """)
122
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_mailbox_recipient ON actor_mailbox(recipient, status);")
123
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_mailbox_stage ON actor_mailbox(stage);")
124
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_mailbox_session ON actor_mailbox(session_id);")
125
+ try:
126
+ cur.execute("ALTER TABLE actor_mailbox ADD COLUMN session_id TEXT;")
127
+ except sqlite3.OperationalError as _err:
128
+ _ = _err
129
+
130
+ # 3. Skill Vault Partition
131
+ cur.execute("""
132
+ CREATE TABLE IF NOT EXISTS skill_vault (
133
+ skill_id TEXT PRIMARY KEY,
134
+ name TEXT NOT NULL,
135
+ framework TEXT NOT NULL,
136
+ content TEXT NOT NULL,
137
+ signature TEXT DEFAULT '',
138
+ metadata TEXT DEFAULT '{}',
139
+ verified INTEGER NOT NULL DEFAULT 1,
140
+ created_at TEXT NOT NULL,
141
+ updated_at TEXT NOT NULL,
142
+ UNIQUE(name, framework)
143
+ );
144
+ """)
145
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_skill_name ON skill_vault(name);")
146
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_skill_framework ON skill_vault(framework);")
147
+
148
+ # 4. Healing Cache Partition
149
+ cur.execute("""
150
+ CREATE TABLE IF NOT EXISTS healing_cache (
151
+ cache_id TEXT PRIMARY KEY,
152
+ error_signature TEXT NOT NULL UNIQUE,
153
+ failed_code TEXT NOT NULL,
154
+ patch_code TEXT NOT NULL,
155
+ rca_verdict TEXT DEFAULT '',
156
+ verified INTEGER NOT NULL DEFAULT 0,
157
+ hit_count INTEGER NOT NULL DEFAULT 1,
158
+ created_at TEXT NOT NULL,
159
+ updated_at TEXT NOT NULL
160
+ );
161
+ """)
162
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_healing_sig ON healing_cache(error_signature);")
163
+
164
+ # 5. Event Stream Partition
165
+ cur.execute("""
166
+ CREATE TABLE IF NOT EXISTS event_stream (
167
+ event_id TEXT PRIMARY KEY,
168
+ session_id TEXT NOT NULL,
169
+ sequence INTEGER NOT NULL,
170
+ event_type TEXT NOT NULL,
171
+ actor TEXT NOT NULL,
172
+ stage TEXT NOT NULL,
173
+ payload TEXT NOT NULL,
174
+ prev_hash TEXT NOT NULL,
175
+ event_hash TEXT NOT NULL,
176
+ checkpoint_name TEXT,
177
+ timestamp TEXT NOT NULL,
178
+ UNIQUE(session_id, sequence)
179
+ );
180
+ """)
181
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_event_session ON event_stream(session_id, sequence);")
182
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_event_checkpoint ON event_stream(session_id, checkpoint_name);")
183
+ cur.close()
184
+
185
+ # ---------------------------------------------------------------------------
186
+ # Transaction Management & Abort Rollback
187
+ # ---------------------------------------------------------------------------
188
+
189
+ def begin(self):
190
+ """Begins an explicit database transaction."""
191
+ with self._lock:
192
+ if not self._in_transaction:
193
+ self._conn.execute("BEGIN IMMEDIATE;")
194
+ self._in_transaction = True
195
+
196
+ def commit(self):
197
+ """Commits active database transaction."""
198
+ with self._lock:
199
+ if self._in_transaction:
200
+ self._conn.execute("COMMIT;")
201
+ self._in_transaction = False
202
+
203
+ def rollback(self):
204
+ """Rolls back active database transaction."""
205
+ with self._lock:
206
+ if self._in_transaction:
207
+ self._conn.execute("ROLLBACK;")
208
+ self._in_transaction = False
209
+
210
+ @contextmanager
211
+ def transaction(self) -> Generator["UnifiedMemoryBus", None, None]:
212
+ """
213
+ Transactional context manager. Automatically commits on successful exit
214
+ or rolls back on exception.
215
+ """
216
+ with self._lock:
217
+ if not self._in_transaction:
218
+ self.begin()
219
+ try:
220
+ yield self
221
+ self.commit()
222
+ except Exception:
223
+ self.rollback()
224
+ raise
225
+ else:
226
+ # Nested transaction implemented via savepoint
227
+ sp_name = f"sp_{uuid.uuid4().hex[:8]}"
228
+ self._conn.execute(f"SAVEPOINT {sp_name};")
229
+ try:
230
+ yield self
231
+ self._conn.execute(f"RELEASE SAVEPOINT {sp_name};")
232
+ except Exception:
233
+ self._conn.execute(f"ROLLBACK TO SAVEPOINT {sp_name};")
234
+ raise
235
+
236
+ @contextmanager
237
+ def savepoint(self, name: Optional[str] = None) -> Generator[str, None, None]:
238
+ """Named savepoint context manager for partial rollback boundaries."""
239
+ with self._lock:
240
+ sp_name = name or f"sp_{uuid.uuid4().hex[:8]}"
241
+ self._conn.execute(f"SAVEPOINT {sp_name};")
242
+ try:
243
+ yield sp_name
244
+ self._conn.execute(f"RELEASE SAVEPOINT {sp_name};")
245
+ except Exception:
246
+ self._conn.execute(f"ROLLBACK TO SAVEPOINT {sp_name};")
247
+ raise
248
+
249
+ def abort_test(self, session_id: Optional[str] = None, reason: str = "Test aborted"):
250
+ """
251
+ Synchronous test abort handler. Rolls back active uncommitted transactions,
252
+ cancels pending mailbox messages, and records an abort event if session_id is provided.
253
+ """
254
+ with self._lock:
255
+ if self._in_transaction:
256
+ self.rollback()
257
+
258
+ if session_id:
259
+ # Mark pending messages for this session's agents as ABORTED
260
+ self._conn.execute(
261
+ "UPDATE actor_mailbox SET status = 'ABORTED' WHERE status = 'PENDING' AND (session_id = ? OR session_id IS NULL OR session_id = '');",
262
+ (session_id,)
263
+ )
264
+ self.record_event(
265
+ session_id=session_id,
266
+ event_type="TEST_ABORTED",
267
+ actor="system",
268
+ stage="ABORT_HANDLER",
269
+ payload={"reason": reason, "aborted_at": _now_iso()}
270
+ )
271
+ else:
272
+ self._conn.execute(
273
+ "UPDATE actor_mailbox SET status = 'ABORTED' WHERE status = 'PENDING';"
274
+ )
275
+
276
+ # ---------------------------------------------------------------------------
277
+ # Partition 1: Memory Blocks API
278
+ # ---------------------------------------------------------------------------
279
+
280
+ def set_block(self, label: str, content: Any, scope: str = "global", tags: str = "") -> Dict[str, Any]:
281
+ """Creates or updates a memory block under a specific scope."""
282
+ with self._lock:
283
+ now = _now_iso()
284
+ content_str = _json_dumps(content) if not isinstance(content, str) else content
285
+ block_id = f"blk_{uuid.uuid4().hex[:12]}"
286
+ cur = self._conn.cursor()
287
+ cur.execute("""
288
+ INSERT INTO memory_blocks (block_id, scope, label, content, tags, created_at, updated_at)
289
+ VALUES (?, ?, ?, ?, ?, ?, ?)
290
+ ON CONFLICT(scope, label) DO UPDATE SET
291
+ content = excluded.content,
292
+ tags = excluded.tags,
293
+ updated_at = excluded.updated_at;
294
+ """, (block_id, scope, label, content_str, tags, now, now))
295
+ cur.close()
296
+ return {
297
+ "scope": scope,
298
+ "label": label,
299
+ "content": content,
300
+ "tags": tags,
301
+ "updated_at": now
302
+ }
303
+
304
+ def get_block(self, label: str, scope: str = "global") -> Optional[Dict[str, Any]]:
305
+ """Retrieves a memory block by label and scope."""
306
+ with self._lock:
307
+ cur = self._conn.cursor()
308
+ cur.execute(
309
+ "SELECT * FROM memory_blocks WHERE scope = ? AND label = ? LIMIT 1;",
310
+ (scope, label)
311
+ )
312
+ row = cur.fetchone()
313
+ cur.close()
314
+ if not row:
315
+ return None
316
+ return {
317
+ "block_id": row["block_id"],
318
+ "scope": row["scope"],
319
+ "label": row["label"],
320
+ "content": _json_loads(row["content"]),
321
+ "tags": row["tags"],
322
+ "created_at": row["created_at"],
323
+ "updated_at": row["updated_at"]
324
+ }
325
+
326
+ def delete_block(self, label: str, scope: str = "global") -> bool:
327
+ """Deletes a memory block by label and scope."""
328
+ with self._lock:
329
+ cur = self._conn.cursor()
330
+ cur.execute("DELETE FROM memory_blocks WHERE scope = ? AND label = ?;", (scope, label))
331
+ deleted = cur.rowcount > 0
332
+ cur.close()
333
+ return deleted
334
+
335
+ def list_blocks(self, scope: Optional[str] = None) -> List[Dict[str, Any]]:
336
+ """Lists all memory blocks, optionally filtered by scope."""
337
+ with self._lock:
338
+ cur = self._conn.cursor()
339
+ if scope:
340
+ cur.execute("SELECT * FROM memory_blocks WHERE scope = ? ORDER BY label ASC;", (scope,))
341
+ else:
342
+ cur.execute("SELECT * FROM memory_blocks ORDER BY scope ASC, label ASC;")
343
+ rows = cur.fetchall()
344
+ cur.close()
345
+ return [
346
+ {
347
+ "block_id": r["block_id"],
348
+ "scope": r["scope"],
349
+ "label": r["label"],
350
+ "content": _json_loads(r["content"]),
351
+ "tags": r["tags"],
352
+ "created_at": r["created_at"],
353
+ "updated_at": r["updated_at"]
354
+ }
355
+ for r in rows
356
+ ]
357
+
358
+ # ---------------------------------------------------------------------------
359
+ # Partition 2: Actor Mailbox API
360
+ # ---------------------------------------------------------------------------
361
+
362
+ def send_message(
363
+ self,
364
+ sender: str,
365
+ recipient: str,
366
+ stage: str,
367
+ payload: Any,
368
+ session_id: Optional[str] = None
369
+ ) -> str:
370
+ """Queues an asynchronous message from sender to recipient actor."""
371
+ with self._lock:
372
+ msg_id = f"msg_{uuid.uuid4().hex[:12]}"
373
+ now = _now_iso()
374
+ payload_str = _json_dumps(payload) if not isinstance(payload, str) else payload
375
+ cur = self._conn.cursor()
376
+ cur.execute("""
377
+ INSERT INTO actor_mailbox (message_id, session_id, sender, recipient, stage, payload, status, created_at)
378
+ VALUES (?, ?, ?, ?, ?, ?, 'PENDING', ?);
379
+ """, (msg_id, session_id, sender, recipient, stage, payload_str, now))
380
+ cur.close()
381
+ return msg_id
382
+
383
+ def receive_messages(
384
+ self,
385
+ recipient: str,
386
+ stage: Optional[str] = None,
387
+ status: str = "PENDING",
388
+ mark_read: bool = True,
389
+ session_id: Optional[str] = None
390
+ ) -> List[Dict[str, Any]]:
391
+ """Retrieves and optionally marks messages as PROCESSED for recipient."""
392
+ with self._lock:
393
+ cur = self._conn.cursor()
394
+ query = "SELECT * FROM actor_mailbox WHERE recipient = ? AND status = ?"
395
+ params: List[Any] = [recipient, status]
396
+ if stage:
397
+ query += " AND stage = ?"
398
+ params.append(stage)
399
+ if session_id:
400
+ query += " AND (session_id = ? OR session_id IS NULL)"
401
+ params.append(session_id)
402
+ query += " ORDER BY created_at ASC;"
403
+
404
+ cur.execute(query, params)
405
+ rows = cur.fetchall()
406
+
407
+ messages = []
408
+ msg_ids = []
409
+ for r in rows:
410
+ msg_ids.append(r["message_id"])
411
+ messages.append({
412
+ "message_id": r["message_id"],
413
+ "session_id": r["session_id"] if "session_id" in r.keys() else None,
414
+ "sender": r["sender"],
415
+ "recipient": r["recipient"],
416
+ "stage": r["stage"],
417
+ "payload": _json_loads(r["payload"]),
418
+ "status": r["status"],
419
+ "created_at": r["created_at"],
420
+ "read_at": r["read_at"]
421
+ })
422
+
423
+ if mark_read and msg_ids:
424
+ now = _now_iso()
425
+ placeholders = ",".join("?" for _ in msg_ids)
426
+ cur.execute(
427
+ f"UPDATE actor_mailbox SET status = 'PROCESSED', read_at = ? WHERE message_id IN ({placeholders});",
428
+ [now] + msg_ids
429
+ )
430
+ cur.close()
431
+ return messages
432
+
433
+ def peek_messages(
434
+ self,
435
+ recipient: str,
436
+ stage: Optional[str] = None,
437
+ session_id: Optional[str] = None
438
+ ) -> List[Dict[str, Any]]:
439
+ """Inspects pending messages without changing status."""
440
+ return self.receive_messages(
441
+ recipient=recipient, stage=stage, status="PENDING", mark_read=False, session_id=session_id
442
+ )
443
+
444
+ def mark_message_status(self, message_id: str, status: str) -> bool:
445
+ """Updates the status of an actor mailbox message."""
446
+ with self._lock:
447
+ cur = self._conn.cursor()
448
+ cur.execute(
449
+ "UPDATE actor_mailbox SET status = ?, read_at = ? WHERE message_id = ?;",
450
+ (status, _now_iso(), message_id)
451
+ )
452
+ updated = cur.rowcount > 0
453
+ cur.close()
454
+ return updated
455
+
456
+ # ---------------------------------------------------------------------------
457
+ # Partition 3: Skill Vault API
458
+ # ---------------------------------------------------------------------------
459
+
460
+ def store_skill(
461
+ self,
462
+ name: str,
463
+ framework: str,
464
+ content: str,
465
+ signature: str = "",
466
+ metadata: Optional[Dict[str, Any]] = None,
467
+ verified: bool = True
468
+ ) -> str:
469
+ """Persists or updates an interaction skill or Page Class snippet."""
470
+ with self._lock:
471
+ skill_id = f"sk_{uuid.uuid4().hex[:12]}"
472
+ now = _now_iso()
473
+ meta_str = _json_dumps(metadata or {})
474
+ ver_int = 1 if verified else 0
475
+ cur = self._conn.cursor()
476
+ cur.execute("""
477
+ INSERT INTO skill_vault (skill_id, name, framework, content, signature, metadata, verified, created_at, updated_at)
478
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
479
+ ON CONFLICT(name, framework) DO UPDATE SET
480
+ content = excluded.content,
481
+ signature = excluded.signature,
482
+ metadata = excluded.metadata,
483
+ verified = excluded.verified,
484
+ updated_at = excluded.updated_at;
485
+ """, (skill_id, name, framework, content, signature, meta_str, ver_int, now, now))
486
+ cur.close()
487
+ return skill_id
488
+
489
+ def get_skill(self, name: str, framework: str) -> Optional[Dict[str, Any]]:
490
+ """Retrieves a skill by name and framework."""
491
+ with self._lock:
492
+ cur = self._conn.cursor()
493
+ cur.execute(
494
+ "SELECT * FROM skill_vault WHERE name = ? AND framework = ? LIMIT 1;",
495
+ (name, framework)
496
+ )
497
+ row = cur.fetchone()
498
+ cur.close()
499
+ if not row:
500
+ return None
501
+ return {
502
+ "skill_id": row["skill_id"],
503
+ "name": row["name"],
504
+ "framework": row["framework"],
505
+ "content": row["content"],
506
+ "signature": row["signature"],
507
+ "metadata": _json_loads(row["metadata"]),
508
+ "verified": bool(row["verified"]),
509
+ "created_at": row["created_at"],
510
+ "updated_at": row["updated_at"]
511
+ }
512
+
513
+ def find_skills(
514
+ self,
515
+ query: str = "",
516
+ framework: Optional[str] = None,
517
+ verified_only: bool = True
518
+ ) -> List[Dict[str, Any]]:
519
+ """Searches skills by substring in name/signature, optionally filtered."""
520
+ with self._lock:
521
+ cur = self._conn.cursor()
522
+ sql = "SELECT * FROM skill_vault WHERE 1=1"
523
+ params: List[Any] = []
524
+ if verified_only:
525
+ sql += " AND verified = 1"
526
+ if framework:
527
+ sql += " AND framework = ?"
528
+ params.append(framework)
529
+ if query:
530
+ sql += " AND (name LIKE ? OR signature LIKE ? OR content LIKE ?)"
531
+ pattern = f"%{query}%"
532
+ params.extend([pattern, pattern, pattern])
533
+ sql += " ORDER BY name ASC;"
534
+
535
+ cur.execute(sql, params)
536
+ rows = cur.fetchall()
537
+ cur.close()
538
+ return [
539
+ {
540
+ "skill_id": r["skill_id"],
541
+ "name": r["name"],
542
+ "framework": r["framework"],
543
+ "content": r["content"],
544
+ "signature": r["signature"],
545
+ "metadata": _json_loads(r["metadata"]),
546
+ "verified": bool(r["verified"]),
547
+ "created_at": r["created_at"],
548
+ "updated_at": r["updated_at"]
549
+ }
550
+ for r in rows
551
+ ]
552
+
553
+ def delete_skill(self, skill_id: str) -> bool:
554
+ """Deletes a skill by its skill_id."""
555
+ with self._lock:
556
+ cur = self._conn.cursor()
557
+ cur.execute("DELETE FROM skill_vault WHERE skill_id = ?;", (skill_id,))
558
+ deleted = cur.rowcount > 0
559
+ cur.close()
560
+ return deleted
561
+
562
+ # ---------------------------------------------------------------------------
563
+ # Partition 4: Healing Cache API
564
+ # ---------------------------------------------------------------------------
565
+
566
+ def record_healing(
567
+ self,
568
+ error_signature: str,
569
+ failed_code: str,
570
+ patch_code: str,
571
+ rca_verdict: str = "",
572
+ verified: bool = False
573
+ ) -> str:
574
+ """Records a healing patch or increments hit count if signature exists."""
575
+ with self._lock:
576
+ now = _now_iso()
577
+ cache_id = f"heal_{uuid.uuid4().hex[:12]}"
578
+ ver_int = 1 if verified else 0
579
+ cur = self._conn.cursor()
580
+ cur.execute("""
581
+ INSERT INTO healing_cache (cache_id, error_signature, failed_code, patch_code, rca_verdict, verified, hit_count, created_at, updated_at)
582
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)
583
+ ON CONFLICT(error_signature) DO UPDATE SET
584
+ failed_code = excluded.failed_code,
585
+ patch_code = excluded.patch_code,
586
+ rca_verdict = excluded.rca_verdict,
587
+ verified = MAX(healing_cache.verified, excluded.verified),
588
+ hit_count = healing_cache.hit_count + 1,
589
+ updated_at = excluded.updated_at;
590
+ """, (cache_id, error_signature, failed_code, patch_code, rca_verdict, ver_int, now, now))
591
+ cur.close()
592
+ return cache_id
593
+
594
+ def lookup_healing(self, error_signature: str, verified_only: bool = False) -> Optional[Dict[str, Any]]:
595
+ """Looks up a cached healing patch by error signature."""
596
+ with self._lock:
597
+ cur = self._conn.cursor()
598
+ sql = "SELECT * FROM healing_cache WHERE error_signature = ?"
599
+ params: List[Any] = [error_signature]
600
+ if verified_only:
601
+ sql += " AND verified = 1"
602
+ sql += " LIMIT 1;"
603
+
604
+ cur.execute(sql, params)
605
+ row = cur.fetchone()
606
+ cur.close()
607
+ if not row:
608
+ return None
609
+ return {
610
+ "cache_id": row["cache_id"],
611
+ "error_signature": row["error_signature"],
612
+ "failed_code": row["failed_code"],
613
+ "patch_code": row["patch_code"],
614
+ "rca_verdict": row["rca_verdict"],
615
+ "verified": bool(row["verified"]),
616
+ "hit_count": row["hit_count"],
617
+ "created_at": row["created_at"],
618
+ "updated_at": row["updated_at"]
619
+ }
620
+
621
+ def verify_healing(self, cache_id: str, verified: bool = True) -> bool:
622
+ """Marks a healing record as verified or unverified."""
623
+ with self._lock:
624
+ cur = self._conn.cursor()
625
+ ver_int = 1 if verified else 0
626
+ cur.execute(
627
+ "UPDATE healing_cache SET verified = ?, updated_at = ? WHERE cache_id = ?;",
628
+ (ver_int, _now_iso(), cache_id)
629
+ )
630
+ updated = cur.rowcount > 0
631
+ cur.close()
632
+ return updated
633
+
634
+ # ---------------------------------------------------------------------------
635
+ # Partition 5: Event Stream API (Hash-Chained & Checkpoint Rollbacks)
636
+ # ---------------------------------------------------------------------------
637
+
638
+ def record_event(
639
+ self,
640
+ session_id: str,
641
+ event_type: str,
642
+ actor: str,
643
+ stage: str,
644
+ payload: Any,
645
+ checkpoint_name: Optional[str] = None,
646
+ max_retries: int = 15
647
+ ) -> Dict[str, Any]:
648
+ """
649
+ Appends a new event to the session's hash-chained timeline.
650
+ Features concurrency retry with BEGIN IMMEDIATE to serialize multi-process writes.
651
+ """
652
+ with self._lock:
653
+ payload_str = _json_dumps(payload) if not isinstance(payload, str) else payload
654
+
655
+ # If already inside an explicit caller transaction, execute directly within that transaction
656
+ if self._in_transaction:
657
+ cur = self._conn.cursor()
658
+ cur.execute(
659
+ "SELECT sequence, event_hash FROM event_stream WHERE session_id = ? ORDER BY sequence DESC LIMIT 1;",
660
+ (session_id,)
661
+ )
662
+ last_row = cur.fetchone()
663
+ seq = (last_row["sequence"] + 1) if last_row else 1
664
+ prev_hash = last_row["event_hash"] if last_row else GENESIS_HASH
665
+
666
+ event_id = f"evt_{uuid.uuid4().hex[:12]}"
667
+ now = _now_iso()
668
+ hash_input = f"{session_id}:{seq}:{event_type}:{actor}:{stage}:{payload_str}:{prev_hash}:{now}"
669
+ event_hash = hashlib.sha256(hash_input.encode("utf-8")).hexdigest()
670
+
671
+ cur.execute("""
672
+ INSERT INTO event_stream (
673
+ event_id, session_id, sequence, event_type, actor, stage, payload,
674
+ prev_hash, event_hash, checkpoint_name, timestamp
675
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
676
+ """, (event_id, session_id, seq, event_type, actor, stage, payload_str, prev_hash, event_hash, checkpoint_name, now))
677
+ cur.close()
678
+
679
+ return {
680
+ "event_id": event_id,
681
+ "session_id": session_id,
682
+ "sequence": seq,
683
+ "event_type": event_type,
684
+ "actor": actor,
685
+ "stage": stage,
686
+ "payload": payload,
687
+ "prev_hash": prev_hash,
688
+ "event_hash": event_hash,
689
+ "checkpoint_name": checkpoint_name,
690
+ "timestamp": now
691
+ }
692
+
693
+ # Otherwise, use isolated immediate transaction with retry loop for concurrent safety
694
+ for attempt in range(max_retries):
695
+ try:
696
+ self._conn.execute("BEGIN IMMEDIATE;")
697
+ cur = self._conn.cursor()
698
+ cur.execute(
699
+ "SELECT sequence, event_hash FROM event_stream WHERE session_id = ? ORDER BY sequence DESC LIMIT 1;",
700
+ (session_id,)
701
+ )
702
+ last_row = cur.fetchone()
703
+ seq = (last_row["sequence"] + 1) if last_row else 1
704
+ prev_hash = last_row["event_hash"] if last_row else GENESIS_HASH
705
+
706
+ event_id = f"evt_{uuid.uuid4().hex[:12]}"
707
+ now = _now_iso()
708
+ hash_input = f"{session_id}:{seq}:{event_type}:{actor}:{stage}:{payload_str}:{prev_hash}:{now}"
709
+ event_hash = hashlib.sha256(hash_input.encode("utf-8")).hexdigest()
710
+
711
+ cur.execute("""
712
+ INSERT INTO event_stream (
713
+ event_id, session_id, sequence, event_type, actor, stage, payload,
714
+ prev_hash, event_hash, checkpoint_name, timestamp
715
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
716
+ """, (event_id, session_id, seq, event_type, actor, stage, payload_str, prev_hash, event_hash, checkpoint_name, now))
717
+ self._conn.execute("COMMIT;")
718
+ cur.close()
719
+
720
+ return {
721
+ "event_id": event_id,
722
+ "session_id": session_id,
723
+ "sequence": seq,
724
+ "event_type": event_type,
725
+ "actor": actor,
726
+ "stage": stage,
727
+ "payload": payload,
728
+ "prev_hash": prev_hash,
729
+ "event_hash": event_hash,
730
+ "checkpoint_name": checkpoint_name,
731
+ "timestamp": now
732
+ }
733
+ except (sqlite3.IntegrityError, sqlite3.OperationalError):
734
+ try:
735
+ self._conn.execute("ROLLBACK;")
736
+ except Exception as _rb_err:
737
+ _ = _rb_err
738
+ if attempt == max_retries - 1:
739
+ raise
740
+ # Non-blocking backoff jitter on SQLite contention
741
+ threading.Event().wait(random.uniform(0.005, 0.02 * (attempt + 1)))
742
+
743
+ def get_events(self, session_id: str, since_sequence: int = 0) -> List[Dict[str, Any]]:
744
+ """Retrieves timeline events for a session."""
745
+ with self._lock:
746
+ cur = self._conn.cursor()
747
+ cur.execute(
748
+ "SELECT * FROM event_stream WHERE session_id = ? AND sequence >= ? ORDER BY sequence ASC;",
749
+ (session_id, since_sequence)
750
+ )
751
+ rows = cur.fetchall()
752
+ cur.close()
753
+ return [
754
+ {
755
+ "event_id": r["event_id"],
756
+ "session_id": r["session_id"],
757
+ "sequence": r["sequence"],
758
+ "event_type": r["event_type"],
759
+ "actor": r["actor"],
760
+ "stage": r["stage"],
761
+ "payload": _json_loads(r["payload"]),
762
+ "prev_hash": r["prev_hash"],
763
+ "event_hash": r["event_hash"],
764
+ "checkpoint_name": r["checkpoint_name"],
765
+ "timestamp": r["timestamp"]
766
+ }
767
+ for r in rows
768
+ ]
769
+
770
+ def verify_stream_integrity(self, session_id: str) -> Tuple[bool, Optional[str]]:
771
+ """
772
+ Cryptographically verifies SHA-256 hash chaining across session event stream.
773
+ Directly checks raw payload as persisted in DB to prevent serialization drift.
774
+ Returns (is_valid, error_description).
775
+ """
776
+ with self._lock:
777
+ cur = self._conn.cursor()
778
+ cur.execute(
779
+ "SELECT sequence, event_type, actor, stage, payload, prev_hash, event_hash, timestamp "
780
+ "FROM event_stream WHERE session_id = ? ORDER BY sequence ASC;",
781
+ (session_id,)
782
+ )
783
+ rows = cur.fetchall()
784
+ cur.close()
785
+
786
+ if not rows:
787
+ return True, None
788
+
789
+ expected_prev = GENESIS_HASH
790
+ for r in rows:
791
+ seq = r["sequence"]
792
+ if r["prev_hash"] != expected_prev:
793
+ return False, f"Broken hash chain at sequence {seq}: expected prev_hash {expected_prev[:12]}..., got {r['prev_hash'][:12]}..."
794
+
795
+ # Recalculate hash on exact persisted payload string
796
+ payload_str = r["payload"]
797
+ hash_input = f"{session_id}:{seq}:{r['event_type']}:{r['actor']}:{r['stage']}:{payload_str}:{r['prev_hash']}:{r['timestamp']}"
798
+ expected_hash = hashlib.sha256(hash_input.encode("utf-8")).hexdigest()
799
+
800
+ if r["event_hash"] != expected_hash:
801
+ return False, f"Tampered event payload at sequence {seq}: hash mismatch."
802
+
803
+ expected_prev = r["event_hash"]
804
+
805
+ return True, None
806
+
807
+ def create_checkpoint(self, session_id: str, actor: str, stage: str, checkpoint_name: str) -> Dict[str, Any]:
808
+ """Creates a named checkpoint event in the session timeline."""
809
+ return self.record_event(
810
+ session_id=session_id,
811
+ event_type="CHECKPOINT",
812
+ actor=actor,
813
+ stage=stage,
814
+ payload={"checkpoint": checkpoint_name},
815
+ checkpoint_name=checkpoint_name
816
+ )
817
+
818
+ def rollback_to_checkpoint(self, session_id: str, checkpoint_name: str) -> Dict[str, Any]:
819
+ """
820
+ Rolls back the event stream to the state of the named checkpoint.
821
+ Removes succeeding events and appends a ROLLBACK_EXECUTED audit event.
822
+ """
823
+ with self._lock:
824
+ cur = self._conn.cursor()
825
+ cur.execute(
826
+ "SELECT sequence FROM event_stream WHERE session_id = ? AND checkpoint_name = ? ORDER BY sequence DESC LIMIT 1;",
827
+ (session_id, checkpoint_name)
828
+ )
829
+ row = cur.fetchone()
830
+ if not row:
831
+ cur.close()
832
+ raise ValueError(f"Checkpoint '{checkpoint_name}' not found for session '{session_id}'.")
833
+
834
+ cp_seq = row["sequence"]
835
+ # Delete events after this checkpoint sequence
836
+ cur.execute(
837
+ "DELETE FROM event_stream WHERE session_id = ? AND sequence > ?;",
838
+ (session_id, cp_seq)
839
+ )
840
+ cur.close()
841
+
842
+ # Record rollback event
843
+ return self.record_event(
844
+ session_id=session_id,
845
+ event_type="ROLLBACK_EXECUTED",
846
+ actor="system",
847
+ stage="ROLLBACK_CONTROLLER",
848
+ payload={"target_checkpoint": checkpoint_name, "reverted_to_sequence": cp_seq}
849
+ )
850
+
851
+ # ---------------------------------------------------------------------------
852
+ # Diagnostics & Lifecycle
853
+ # ---------------------------------------------------------------------------
854
+
855
+ def get_stats(self) -> Dict[str, int]:
856
+ """Returns row counts across all 5 partitions."""
857
+ with self._lock:
858
+ cur = self._conn.cursor()
859
+ stats = {}
860
+ for table in ("memory_blocks", "actor_mailbox", "skill_vault", "healing_cache", "event_stream"):
861
+ cur.execute(f"SELECT COUNT(*) AS cnt FROM {table};")
862
+ stats[table] = cur.fetchone()["cnt"]
863
+ cur.close()
864
+ return stats
865
+
866
+ def clear_all(self):
867
+ """Clears all records across all partitions (test teardown helper)."""
868
+ with self._lock:
869
+ cur = self._conn.cursor()
870
+ cur.execute("DELETE FROM memory_blocks;")
871
+ cur.execute("DELETE FROM actor_mailbox;")
872
+ cur.execute("DELETE FROM skill_vault;")
873
+ cur.execute("DELETE FROM healing_cache;")
874
+ cur.execute("DELETE FROM event_stream;")
875
+ cur.close()
876
+
877
+ def close(self):
878
+ """Closes the underlying SQLite connection."""
879
+ with self._lock:
880
+ try:
881
+ self._conn.close()
882
+ except Exception as err:
883
+ _ = err
884
+
885
+ def __enter__(self) -> "UnifiedMemoryBus":
886
+ return self
887
+
888
+ def __exit__(self, exc_type, exc_val, exc_tb):
889
+ self.close()
890
+
891
+
892
+ # Singleton / factory helper
893
+ _GLOBAL_BUS: Optional[UnifiedMemoryBus] = None
894
+ _BUS_LOCK = threading.Lock()
895
+
896
+
897
+ def get_memory_bus(db_path: Optional[str] = None) -> UnifiedMemoryBus:
898
+ """Returns singleton UnifiedMemoryBus instance or creates new if path specified."""
899
+ global _GLOBAL_BUS
900
+ if db_path is not None:
901
+ return UnifiedMemoryBus(db_path=db_path)
902
+ with _BUS_LOCK:
903
+ if _GLOBAL_BUS is None:
904
+ _GLOBAL_BUS = UnifiedMemoryBus()
905
+ return _GLOBAL_BUS