@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,834 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 Thįŗæ Vị (@TeeVee998). All rights reserved.
3
+ # SPDX-License-Identifier: MIT
4
+ # Project: Synapse-Hub (https://github.com/TeeVee998/Synapse-Hub)
5
+
6
+ """
7
+ Enterprise ALM & TMS Sync Bridge (Jira / Xray / Zephyr / TestRail)
8
+ ------------------------------------------------------------------
9
+ Bi-directional synchronization bridge connecting autonomous QA agents with
10
+ Enterprise Test Management Systems:
11
+ 1. Pull Mode (Inward):
12
+ - Pulls User Stories, Acceptance Criteria (Given-When-Then / Gherkin),
13
+ and Test Cases directly from Jira Issues, Xray, or TestRail v2.
14
+ - Formats them into standardized prompt contexts for Clean POM test generation.
15
+ 2. Push Mode (Outward Defect Reporter):
16
+ - Automatically creates detailed Bug Tickets on Jira/Xray or flags defects in TestRail.
17
+ - Attaches failure stack traces, repro steps, links to Screenshots/FAILED_*.png,
18
+ video recordings, console error logs, and environment metadata.
19
+ 3. Execution Run Sync:
20
+ - Reports bulk test execution outcomes (PASS / FAIL / BLOCKED, execution time)
21
+ back to Jira Xray (/api/v2/import/execution) or TestRail v2 (/api/v2/add_result_for_case).
22
+ 4. Enterprise Security & Authentication:
23
+ - Supports OAuth2 Bearer Tokens (JWT, Personal Access Tokens) alongside Basic Auth.
24
+ 5. Offline / Mock & Dry-Run Support:
25
+ - Fully functional offline simulation for CI pipelines and test suites without
26
+ requiring live enterprise credentials.
27
+ """
28
+
29
+ import os
30
+ import sys
31
+ import json
32
+ import base64
33
+ import argparse
34
+ import urllib.request
35
+ import urllib.error
36
+ from datetime import datetime
37
+ from typing import Dict, Any, List, Optional
38
+
39
+ # Enforce UTF-8 stdout encoding for Windows console compatibility
40
+ if hasattr(sys.stdout, 'reconfigure'):
41
+ try:
42
+ sys.stdout.reconfigure(encoding='utf-8')
43
+ sys.stderr.reconfigure(encoding='utf-8')
44
+ except Exception:
45
+ pass
46
+
47
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
48
+ QA_HUB_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))
49
+
50
+
51
+ def text_to_adf(text: str) -> Dict[str, Any]:
52
+ """Converts a raw string into Atlassian Document Format (ADF) JSON for Jira Cloud API v3."""
53
+ paragraphs = []
54
+ for block in (text or "").split("\n\n"):
55
+ block = block.strip()
56
+ if not block:
57
+ continue
58
+ paragraphs.append({
59
+ "type": "paragraph",
60
+ "content": [{"type": "text", "text": block}]
61
+ })
62
+ if not paragraphs:
63
+ paragraphs = [{"type": "paragraph", "content": [{"type": "text", "text": "No content provided."}]}]
64
+ return {
65
+ "type": "doc",
66
+ "version": 1,
67
+ "content": paragraphs
68
+ }
69
+
70
+
71
+ def adf_to_text(adf_data: Any) -> str:
72
+ """Extracts plain text recursively from Atlassian Document Format (ADF) JSON."""
73
+ if not isinstance(adf_data, dict):
74
+ return str(adf_data) if adf_data is not None else ""
75
+ text_parts: List[str] = []
76
+
77
+ def _extract(node: Any):
78
+ if isinstance(node, dict):
79
+ node_type = node.get("type")
80
+ if node_type == "text" and "text" in node:
81
+ text_parts.append(node["text"])
82
+ elif node_type == "hardBreak":
83
+ text_parts.append("\n")
84
+ for child in node.get("content", []):
85
+ _extract(child)
86
+ if node_type in ("paragraph", "heading", "listItem", "codeBlock"):
87
+ text_parts.append("\n")
88
+ elif isinstance(node, list):
89
+ for item in node:
90
+ _extract(item)
91
+
92
+ _extract(adf_data)
93
+ return "".join(text_parts).strip()
94
+
95
+
96
+ def build_jira_v3_adf_description(
97
+ test_case_id: str,
98
+ error_message: str,
99
+ reproduction_steps: List[str],
100
+ stack_trace: str = "",
101
+ ) -> Dict[str, Any]:
102
+ """
103
+ Constructs compliant Atlassian Document Format (ADF) JSON for Jira Cloud REST API v3 (/rest/api/3/issue).
104
+ Prevents HTTP 400 Bad Request: 'Operation value must be an Atlassian Document (ADF)'.
105
+ Guarantees all text nodes are non-empty strings (ADF schema requirement: minLength 1).
106
+ """
107
+ tc_clean = (test_case_id or "").strip() or "UNKNOWN_TEST"
108
+ err_clean = (error_message or "").strip() or "Unknown error"
109
+
110
+ raw_steps = reproduction_steps if reproduction_steps is not None else []
111
+ clean_steps = [s.strip() for s in raw_steps if isinstance(s, str) and s.strip()]
112
+ if not clean_steps:
113
+ clean_steps = ["Execute automated test scenario."]
114
+
115
+ content: List[Dict[str, Any]] = [
116
+ {
117
+ "type": "paragraph",
118
+ "content": [
119
+ {"type": "text", "text": "Failing Test Case: ", "marks": [{"type": "strong"}]},
120
+ {"type": "text", "text": tc_clean},
121
+ ],
122
+ },
123
+ {
124
+ "type": "paragraph",
125
+ "content": [
126
+ {"type": "text", "text": "Error Message:", "marks": [{"type": "strong"}]},
127
+ ],
128
+ },
129
+ {
130
+ "type": "codeBlock",
131
+ "attrs": {"language": "text"},
132
+ "content": [{"type": "text", "text": err_clean}],
133
+ },
134
+ {
135
+ "type": "paragraph",
136
+ "content": [
137
+ {"type": "text", "text": "Reproduction Steps:", "marks": [{"type": "strong"}]},
138
+ ],
139
+ },
140
+ {
141
+ "type": "orderedList",
142
+ "content": [
143
+ {
144
+ "type": "listItem",
145
+ "content": [
146
+ {"type": "paragraph", "content": [{"type": "text", "text": step}]}
147
+ ],
148
+ }
149
+ for step in clean_steps
150
+ ],
151
+ },
152
+ ]
153
+
154
+ st_clean = (stack_trace or "").strip()
155
+ if st_clean:
156
+ content.extend([
157
+ {
158
+ "type": "paragraph",
159
+ "content": [
160
+ {"type": "text", "text": "Stack Trace:", "marks": [{"type": "strong"}]},
161
+ ],
162
+ },
163
+ {
164
+ "type": "codeBlock",
165
+ "attrs": {"language": "text"},
166
+ "content": [{"type": "text", "text": st_clean}],
167
+ },
168
+ ])
169
+
170
+ return {
171
+ "type": "doc",
172
+ "version": 1,
173
+ "content": content,
174
+ }
175
+
176
+
177
+ class TMSBridge:
178
+ """Enterprise Test Management System Adapter."""
179
+
180
+ def __init__(
181
+ self,
182
+ provider: str = "jira",
183
+ base_url: str = "",
184
+ api_token: str = "",
185
+ user_email: str = "",
186
+ auth_type: str = "auto",
187
+ ):
188
+ self.provider = provider.lower().strip()
189
+ resolved_url = (
190
+ base_url
191
+ or os.getenv("JIRA_URL")
192
+ or os.getenv("TESTRAIL_URL")
193
+ or os.getenv("XRAY_BASE_URL")
194
+ or os.getenv("TMS_BASE_URL")
195
+ or ""
196
+ )
197
+ resolved_token = (
198
+ api_token
199
+ or os.getenv("JIRA_API_TOKEN")
200
+ or os.getenv("TESTRAIL_API_KEY")
201
+ or os.getenv("TESTRAIL_API_TOKEN")
202
+ or os.getenv("XRAY_API_TOKEN")
203
+ or os.getenv("TMS_API_TOKEN")
204
+ or ""
205
+ )
206
+ resolved_email = (
207
+ user_email
208
+ or os.getenv("JIRA_USER_EMAIL")
209
+ or os.getenv("TESTRAIL_USER_EMAIL")
210
+ or os.getenv("TMS_USER_EMAIL")
211
+ or ""
212
+ )
213
+ resolved_auth_type = auth_type if auth_type != "auto" else (os.getenv("TMS_AUTH_TYPE") or "auto")
214
+
215
+ # Use mock simulation if URL is omitted, mock is specified, or token is absent
216
+ if not resolved_url or "mock" in resolved_url or not resolved_token:
217
+ self.base_url = "https://mock-alm.enterprise.local"
218
+ self.api_token = "mock_token_12345"
219
+ self.user_email = resolved_email or "qa-agent@enterprise.local"
220
+ self.auth_type = "basic"
221
+ self.is_mock = True
222
+ else:
223
+ self.base_url = resolved_url.rstrip("/")
224
+ self.api_token = resolved_token
225
+ self.user_email = resolved_email
226
+ self.is_mock = False
227
+
228
+ if resolved_auth_type != "auto":
229
+ self.auth_type = resolved_auth_type.lower()
230
+ elif resolved_token.startswith("Bearer ") or len(resolved_token) > 100 or not resolved_email:
231
+ self.auth_type = "bearer"
232
+ else:
233
+ self.auth_type = "basic"
234
+
235
+ def get_auth_headers(self) -> Dict[str, str]:
236
+ """Generates HTTP authorization headers supporting Bearer Token, OAuth2, and Basic Auth."""
237
+ headers = {"Accept": "application/json"}
238
+ if self.auth_type in ("bearer", "oauth2") or self.api_token.startswith("Bearer "):
239
+ tok = self.api_token[7:].strip() if self.api_token.startswith("Bearer ") else self.api_token.strip()
240
+ headers["Authorization"] = f"Bearer {tok}"
241
+ else:
242
+ auth_str = f"{self.user_email}:{self.api_token}".encode("utf-8")
243
+ headers["Authorization"] = f"Basic {base64.b64encode(auth_str).decode('utf-8')}"
244
+ return headers
245
+
246
+ def _testrail_url(self, path: str) -> str:
247
+ """Normalizes TestRail API v2 endpoint URL preventing duplicated path fragments."""
248
+ base = self.base_url.rstrip("/")
249
+ if "/index.php" in base:
250
+ base = base.split("/index.php")[0]
251
+ elif base.endswith("/api/v2"):
252
+ base = base[:-7]
253
+ clean_path = path.lstrip("/")
254
+ return f"{base}/index.php?/api/v2/{clean_path}"
255
+
256
+ def _xray_url(self, path: str) -> str:
257
+ """Normalizes Xray endpoint URL supporting Cloud and DC/Server."""
258
+ base = self.base_url.rstrip("/")
259
+ is_cloud = "cloud" in base or "getxray.app" in base
260
+ clean_path = path.lstrip("/")
261
+ if is_cloud:
262
+ if base.endswith("/api/v2"):
263
+ base = base[:-7]
264
+ return f"{base}/api/v2/{clean_path}"
265
+ else:
266
+ if base.endswith("/rest/raven/1.0"):
267
+ base = base[:-15]
268
+ return f"{base}/rest/raven/1.0/{clean_path}"
269
+
270
+ def _execute_request(
271
+ self,
272
+ url: str,
273
+ method: str = "GET",
274
+ data: Optional[Dict[str, Any]] = None,
275
+ headers: Optional[Dict[str, str]] = None,
276
+ timeout: float = 15.0,
277
+ ) -> Dict[str, Any]:
278
+ """Executes an authenticated JSON HTTP request with strict error handling."""
279
+ req_headers = self.get_auth_headers()
280
+ if headers:
281
+ req_headers.update(headers)
282
+
283
+ body_bytes = None
284
+ if data is not None:
285
+ body_bytes = json.dumps(data).encode("utf-8")
286
+ req_headers["Content-Type"] = "application/json"
287
+
288
+ req = urllib.request.Request(url, data=body_bytes, headers=req_headers, method=method)
289
+ try:
290
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310
291
+ resp_content = resp.read().decode("utf-8")
292
+ if not resp_content.strip():
293
+ return {"status_code": resp.status, "message": "OK (empty body)"}
294
+ try:
295
+ return json.loads(resp_content)
296
+ except json.JSONDecodeError:
297
+ return {"status_code": resp.status, "raw": resp_content}
298
+ except urllib.error.HTTPError as exc:
299
+ err_body = ""
300
+ try:
301
+ err_body = exc.read().decode("utf-8")
302
+ except Exception as read_err:
303
+ err_body = f"<unreadable error body: {read_err}>"
304
+ err_msg = f"HTTP Error {exc.code}: {exc.reason}"
305
+ if err_body:
306
+ err_msg += f" - Response: {err_body}"
307
+ raise RuntimeError(err_msg) from exc
308
+
309
+ # -------------------------------------------------------------------------
310
+ # 1. PULL MODE: Extract User Story & Acceptance Criteria
311
+ # -------------------------------------------------------------------------
312
+ def pull_story_acceptance_criteria(self, issue_key: str) -> Dict[str, Any]:
313
+ """
314
+ Pulls User Story details, acceptance criteria, and technical specifications
315
+ by Issue Key (e.g. 'PROJ-1042' or TestRail case 'C1042').
316
+ """
317
+ issue_key_clean = issue_key.strip().upper()
318
+
319
+ if self.is_mock:
320
+ return {
321
+ "issue_key": issue_key_clean,
322
+ "summary": f"Automated Invoice Reconciliation for {issue_key_clean}",
323
+ "issue_type": "Story",
324
+ "status": "Ready for QA",
325
+ "assignee": self.user_email,
326
+ "description": "As an Enterprise Accountant, I want to reconcile invoices matching ERP records to ensure financial accuracy.",
327
+ "acceptance_criteria": [
328
+ "Given the accountant is logged in with FINANCE_ROLE",
329
+ "When navigating to '/billing/invoices' and filtering by date '2026-10-01'",
330
+ "Then invoice table displays matching records with status 'MATCHED'",
331
+ "And total amount reconciles with zero discrepancy"
332
+ ],
333
+ "gherkin_feature": (
334
+ f"Feature: Invoice Reconciliation ({issue_key_clean})\n"
335
+ f" Scenario: Successful matching of monthly invoices\n"
336
+ f" Given user is authenticated with 'FINANCE_ROLE'\n"
337
+ f" When filtering invoices by '2026-10-01'\n"
338
+ f" Then status badge displays 'MATCHED'\n"
339
+ ),
340
+ "labels": ["Billing", "Automated-E2E", "Finance"],
341
+ "source": f"Mock ALM Adapter ({self.provider})"
342
+ }
343
+
344
+ # TestRail v2 Pull Integration
345
+ if self.provider == "testrail":
346
+ clean_case_id = issue_key_clean.lstrip("C")
347
+ try:
348
+ case_int = int(clean_case_id)
349
+ data = self.testrail_get_case(case_int)
350
+ summary = data.get("title", f"TestRail Case C{case_int}")
351
+ desc_str = data.get("custom_preconds", "") or data.get("custom_steps", "") or ""
352
+ ac_lines = [step.strip() for step in str(desc_str).splitlines() if step.strip()]
353
+ return {
354
+ "issue_key": f"C{case_int}",
355
+ "summary": summary,
356
+ "issue_type": "TestCase",
357
+ "status": "Active",
358
+ "assignee": self.user_email,
359
+ "description": str(desc_str),
360
+ "acceptance_criteria": ac_lines,
361
+ "labels": ["TestRail", f"Section-{data.get('section_id')}"],
362
+ "source": f"Live TestRail API ({self.base_url})"
363
+ }
364
+ except Exception as e:
365
+ return {
366
+ "error": f"Failed to pull TestRail case {issue_key_clean}: {str(e)}",
367
+ "issue_key": issue_key_clean,
368
+ "source": "Live TestRail API (Error Fallback)"
369
+ }
370
+
371
+ # Live Jira / Xray REST API Integration
372
+ try:
373
+ endpoint = f"{self.base_url}/rest/api/3/issue/{issue_key_clean}"
374
+ data = self._execute_request(endpoint, method="GET")
375
+
376
+ fields = data.get("fields", {})
377
+ desc_raw = fields.get("description", "")
378
+ summary = fields.get("summary", "")
379
+
380
+ # Convert ADF dict if Jira Cloud API v3 returned document
381
+ desc_str = adf_to_text(desc_raw) if isinstance(desc_raw, dict) else (desc_raw if isinstance(desc_raw, str) else str(desc_raw))
382
+
383
+ # Extract Acceptance Criteria if present in text
384
+ ac_lines = []
385
+ for line in desc_str.splitlines():
386
+ if any(line.strip().startswith(kw) for kw in ("Given", "When", "Then", "And", "*", "-")):
387
+ ac_lines.append(line.strip())
388
+
389
+ return {
390
+ "issue_key": issue_key_clean,
391
+ "summary": summary,
392
+ "issue_type": fields.get("issuetype", {}).get("name", "Story"),
393
+ "status": fields.get("status", {}).get("name", "Open"),
394
+ "assignee": fields.get("assignee", {}).get("displayName", "Unassigned"),
395
+ "description": desc_str,
396
+ "acceptance_criteria": ac_lines,
397
+ "labels": fields.get("labels", []),
398
+ "source": f"Live {self.provider.upper()} API ({self.base_url})"
399
+ }
400
+ except Exception as e:
401
+ return {
402
+ "error": f"Failed to pull story {issue_key_clean}: {str(e)}",
403
+ "issue_key": issue_key_clean,
404
+ "source": f"Live {self.provider.upper()} API (Error Fallback)"
405
+ }
406
+
407
+ # -------------------------------------------------------------------------
408
+ # 2. PUSH MODE: Automated Bug Ticket Creation on Test Failure
409
+ # -------------------------------------------------------------------------
410
+ def report_defect(
411
+ self,
412
+ project_key: str,
413
+ test_case_id: str,
414
+ summary: str,
415
+ error_message: str,
416
+ stack_trace: str = "",
417
+ screenshot_path: str = "",
418
+ reproduction_steps: Optional[List[str]] = None,
419
+ severity: str = "High"
420
+ ) -> Dict[str, Any]:
421
+ """
422
+ Creates an actionable Bug Ticket in Jira/Xray or flags failure in TestRail.
423
+ """
424
+ proj_clean = project_key.strip().upper()
425
+ bug_key = f"{proj_clean}-BUG-{int(datetime.now().timestamp()) % 10000}"
426
+
427
+ repro = reproduction_steps or [
428
+ "1. Launch headless browser session via Playwright Live.",
429
+ "2. Navigate to target application flow under test.",
430
+ f"3. Execute test action sequence for '{test_case_id}'.",
431
+ f"4. Observe failure: {error_message}"
432
+ ]
433
+
434
+ ticket_payload = {
435
+ "ticket_key": bug_key,
436
+ "project": proj_clean,
437
+ "issue_type": "Bug",
438
+ "summary": f"[AUT-DEFECT] {test_case_id}: {summary}",
439
+ "severity": severity,
440
+ "test_case_id": test_case_id,
441
+ "error_message": error_message,
442
+ "reproduction_steps": repro,
443
+ "stack_trace": stack_trace,
444
+ "screenshot_attachment": screenshot_path,
445
+ "environment": {
446
+ "runner": "Playwright / Headless",
447
+ "os": sys.platform,
448
+ "timestamp": datetime.now().isoformat()
449
+ },
450
+ "status": "Created",
451
+ "mode": "MOCK_SIMULATION" if self.is_mock else f"LIVE_{self.provider.upper()}"
452
+ }
453
+
454
+ if self.is_mock:
455
+ return ticket_payload
456
+
457
+ # TestRail Defect Reporting via /api/v2/add_result_for_case
458
+ if self.provider == "testrail":
459
+ clean_case_id = "".join([c for c in test_case_id if c.isdigit()])
460
+ if clean_case_id:
461
+ try:
462
+ case_int = int(clean_case_id)
463
+ comment = f"Automated Failure: {summary}\nError: {error_message}\nStack Trace:\n{stack_trace}"
464
+ run_id = int(os.getenv("TESTRAIL_RUN_ID", "1"))
465
+ res = self.testrail_add_result_for_case(
466
+ run_id=run_id,
467
+ case_id=case_int,
468
+ status_id=5, # 5 = Failed in TestRail
469
+ comment=comment,
470
+ )
471
+ ticket_payload["ticket_key"] = f"TR-RESULT-{res.get('id', case_int)}"
472
+ ticket_payload["status"] = "Submitted"
473
+ return ticket_payload
474
+ except Exception as e:
475
+ ticket_payload["live_error"] = str(e)
476
+ ticket_payload["status"] = "Drafted (Offline Fallback)"
477
+ return ticket_payload
478
+ else:
479
+ ticket_payload["live_error"] = f"TestRail requires a numeric Case ID (e.g. C123), but '{test_case_id}' contains no digits."
480
+ ticket_payload["status"] = "Drafted (Offline Fallback)"
481
+ return ticket_payload
482
+
483
+ # Live Jira & Xray Bug Creation
484
+ try:
485
+ endpoint = f"{self.base_url}/rest/api/3/issue"
486
+ adf_desc = build_jira_v3_adf_description(
487
+ test_case_id=test_case_id,
488
+ error_message=error_message,
489
+ reproduction_steps=repro,
490
+ stack_trace=stack_trace,
491
+ )
492
+ body = {
493
+ "fields": {
494
+ "project": {"key": proj_clean},
495
+ "summary": ticket_payload["summary"],
496
+ "issuetype": {"name": "Bug"},
497
+ "description": adf_desc,
498
+ "labels": ["Automated-Failure", "AI-Reported", "Playwright"]
499
+ }
500
+ }
501
+
502
+ res_data = self._execute_request(endpoint, method="POST", data=body)
503
+ ticket_payload["ticket_key"] = res_data.get("key", bug_key)
504
+ ticket_payload["status"] = "Submitted"
505
+ except Exception as e:
506
+ ticket_payload["live_error"] = str(e)
507
+ ticket_payload["status"] = "Drafted (Offline Fallback)"
508
+
509
+ return ticket_payload
510
+
511
+ # -------------------------------------------------------------------------
512
+ # 3. TESTRAIL v2 REST ADAPTERS
513
+ # -------------------------------------------------------------------------
514
+ def testrail_get_tests(self, run_id: int) -> List[Dict[str, Any]]:
515
+ """
516
+ Retrieves tests for a TestRail test run via GET /api/v2/get_tests/{run_id}.
517
+ """
518
+ if self.is_mock:
519
+ return [
520
+ {"id": 1, "case_id": 101, "title": "Verify User Authentication", "status_id": 1},
521
+ {"id": 2, "case_id": 102, "title": "Verify Invoice Matching", "status_id": 1},
522
+ {"id": 3, "case_id": 103, "title": "Verify Payment Gateway", "status_id": 5},
523
+ ]
524
+
525
+ endpoint = self._testrail_url(f"get_tests/{run_id}")
526
+ resp = self._execute_request(endpoint, method="GET")
527
+ if isinstance(resp, list):
528
+ return resp
529
+ return resp.get("tests", [])
530
+
531
+ def testrail_get_case(self, case_id: int) -> Dict[str, Any]:
532
+ """
533
+ Retrieves a test case from TestRail via GET /api/v2/get_case/{case_id}.
534
+ """
535
+ if self.is_mock:
536
+ return {
537
+ "id": case_id,
538
+ "title": f"TestRail Test Case C{case_id}",
539
+ "section_id": 42,
540
+ "type_id": 1,
541
+ "priority_id": 2,
542
+ "custom_preconds": "Given user is on login page",
543
+ "custom_steps": "When entering valid credentials\nThen dashboard opens",
544
+ }
545
+
546
+ endpoint = self._testrail_url(f"get_case/{case_id}")
547
+ return self._execute_request(endpoint, method="GET")
548
+
549
+ def testrail_add_result_for_case(
550
+ self,
551
+ run_id: int,
552
+ case_id: int,
553
+ status_id: int = 1,
554
+ comment: str = "",
555
+ elapsed: str = "",
556
+ defects: str = "",
557
+ ) -> Dict[str, Any]:
558
+ """
559
+ Submits a test result to TestRail via POST /api/v2/add_result_for_case/{run_id}/{case_id}.
560
+ Status IDs: 1=Passed, 2=Blocked, 3=Untested, 4=Retest, 5=Failed.
561
+ """
562
+ if self.is_mock:
563
+ return {
564
+ "id": 1000 + case_id,
565
+ "test_id": 500 + case_id,
566
+ "status_id": status_id,
567
+ "created_on": int(datetime.now().timestamp()),
568
+ "assignedto_id": None,
569
+ "comment": comment or "Result submitted autonomously by Synapse Hub",
570
+ "version": "1.0",
571
+ "elapsed": elapsed or "1s",
572
+ "defects": defects,
573
+ }
574
+
575
+ endpoint = self._testrail_url(f"add_result_for_case/{run_id}/{case_id}")
576
+ payload: Dict[str, Any] = {"status_id": status_id}
577
+ if comment:
578
+ payload["comment"] = comment
579
+ if elapsed:
580
+ payload["elapsed"] = elapsed
581
+ if defects:
582
+ payload["defects"] = defects
583
+
584
+ return self._execute_request(endpoint, method="POST", data=payload)
585
+
586
+ # -------------------------------------------------------------------------
587
+ # 4. JIRA XRAY REST ADAPTERS
588
+ # -------------------------------------------------------------------------
589
+ def xray_import_execution(
590
+ self,
591
+ test_execution_key: Optional[str] = None,
592
+ tests: Optional[List[Dict[str, Any]]] = None,
593
+ summary: str = "",
594
+ test_environments: Optional[List[str]] = None,
595
+ ) -> Dict[str, Any]:
596
+ """
597
+ Imports execution results into Jira Xray via REST API:
598
+ Cloud: POST /api/v2/import/execution
599
+ Server/DC: POST /rest/raven/1.0/import/execution
600
+ """
601
+ tests_payload = tests or []
602
+ if self.is_mock:
603
+ return {
604
+ "testExecIssue": {
605
+ "id": "10400",
606
+ "key": test_execution_key or "EXEC-101",
607
+ "self": f"{self.base_url}/rest/api/2/issue/10400"
608
+ },
609
+ "status": "SUCCESS",
610
+ "imported_tests_count": len(tests_payload)
611
+ }
612
+
613
+ endpoint = self._xray_url("import/execution")
614
+
615
+ body: Dict[str, Any] = {
616
+ "info": {
617
+ "summary": summary or f"Automated Execution Run ({datetime.now().strftime('%Y-%m-%d %H:%M')})",
618
+ "description": "Reported autonomously via Synapse Hub TMS Bridge",
619
+ "testEnvironments": test_environments or ["Playwright-Headless"],
620
+ },
621
+ "tests": tests_payload,
622
+ }
623
+ if test_execution_key:
624
+ body["testExecutionKey"] = test_execution_key
625
+
626
+ return self._execute_request(endpoint, method="POST", data=body)
627
+
628
+ def xray_authenticate(self, client_id: str, client_secret: str) -> str:
629
+ """
630
+ Authenticates with Xray Cloud using OAuth2 client credentials and returns a Bearer JWT token.
631
+ POST /api/v2/authenticate
632
+ """
633
+ if self.is_mock:
634
+ return "mock_xray_jwt_token_sample"
635
+
636
+ endpoint = self._xray_url("authenticate")
637
+ payload = {"client_id": client_id, "client_secret": client_secret}
638
+ req = urllib.request.Request(
639
+ endpoint,
640
+ data=json.dumps(payload).encode("utf-8"),
641
+ headers={"Content-Type": "application/json", "Accept": "application/json"},
642
+ method="POST"
643
+ )
644
+ with urllib.request.urlopen(req, timeout=10) as resp: # nosec B310
645
+ token = resp.read().decode("utf-8").strip().strip('"')
646
+ self.api_token = token
647
+ self.auth_type = "bearer"
648
+ return token
649
+
650
+ # -------------------------------------------------------------------------
651
+ # 5. EXECUTION SYNC: Push Run Execution Outcomes
652
+ # -------------------------------------------------------------------------
653
+ def sync_execution_results(
654
+ self,
655
+ test_plan_key: str,
656
+ results: List[Dict[str, Any]]
657
+ ) -> Dict[str, Any]:
658
+ """
659
+ Pushes batch test execution status (PASS/FAIL/BLOCKED) to Jira, Xray, or TestRail.
660
+ """
661
+ total = len(results)
662
+ passed = sum(1 for r in results if r.get("status") in ("PASS", "PASSED"))
663
+ failed = sum(1 for r in results if r.get("status") in ("FAIL", "FAILED"))
664
+
665
+ sync_report: Dict[str, Any] = {
666
+ "test_plan_key": test_plan_key,
667
+ "provider": self.provider,
668
+ "timestamp": datetime.now().isoformat(),
669
+ "total_synced": total,
670
+ "passed": passed,
671
+ "failed": failed,
672
+ "pass_rate_pct": round((passed / total) * 100.0, 2) if total else 0.0,
673
+ "sync_status": "SUCCESS",
674
+ "destination": self.base_url,
675
+ "entries": results
676
+ }
677
+
678
+ if self.is_mock:
679
+ return sync_report
680
+
681
+ # Live Xray Execution Import
682
+ if self.provider in ("xray", "jira_xray"):
683
+ xray_tests = []
684
+ for item in results:
685
+ t_key = item.get("test_key") or item.get("tc_id") or "TEST-01"
686
+ st = "PASSED" if item.get("status") in ("PASS", "PASSED") else "FAILED"
687
+ xray_tests.append({
688
+ "testKey": t_key,
689
+ "status": st,
690
+ "comment": item.get("comment", f"Result: {st}"),
691
+ "duration": item.get("duration_sec", 0.0)
692
+ })
693
+ try:
694
+ import_resp = self.xray_import_execution(
695
+ test_execution_key=test_plan_key,
696
+ tests=xray_tests,
697
+ summary=f"Automated Suite Execution: {test_plan_key}"
698
+ )
699
+ sync_report["xray_response"] = import_resp
700
+ except Exception as e:
701
+ sync_report["sync_status"] = "PARTIAL_ERROR"
702
+ sync_report["error"] = str(e)
703
+
704
+ # Live TestRail Result Posting
705
+ elif self.provider == "testrail":
706
+ run_id = 1
707
+ clean_digits = "".join([c for c in test_plan_key if c.isdigit()])
708
+ if clean_digits:
709
+ run_id = int(clean_digits)
710
+
711
+ posted_results = []
712
+ for item in results:
713
+ t_key = item.get("test_key") or item.get("tc_id") or "1"
714
+ case_id = int("".join([c for c in t_key if c.isdigit()]) or 1)
715
+ st_id = 1 if item.get("status") in ("PASS", "PASSED") else 5
716
+ elapsed_str = f"{int(item.get('duration_sec', 1))}s"
717
+ try:
718
+ res = self.testrail_add_result_for_case(
719
+ run_id=run_id,
720
+ case_id=case_id,
721
+ status_id=st_id,
722
+ comment=item.get("comment", f"Status: {item.get('status')}"),
723
+ elapsed=elapsed_str
724
+ )
725
+ posted_results.append(res)
726
+ except Exception as e:
727
+ posted_results.append({"case_id": case_id, "error": str(e)})
728
+ sync_report["testrail_results"] = posted_results
729
+
730
+ return sync_report
731
+
732
+
733
+ def main():
734
+ parser = argparse.ArgumentParser(description="Enterprise ALM & TMS Sync Bridge")
735
+ parser.add_argument("--provider", default="jira", choices=["jira", "xray", "testrail"], help="TMS Provider")
736
+ parser.add_argument("--base-url", default="", help="Base URL of TMS")
737
+ parser.add_argument("--token", default="", help="API Token or Bearer Token")
738
+ parser.add_argument("--email", default="", help="User email for Basic Auth")
739
+ parser.add_argument("--auth-type", default="auto", choices=["auto", "basic", "bearer", "oauth2"], help="Auth scheme")
740
+
741
+ subparsers = parser.add_subparsers(dest="command", help="Sync command")
742
+
743
+ # Command: pull
744
+ pull_p = subparsers.add_parser("pull", help="Pull Acceptance Criteria from User Story")
745
+ pull_p.add_argument("issue_key", help="Jira / ALM Issue Key (e.g. PROJ-1042)")
746
+ pull_p.add_argument("--json", action="store_true", help="Output JSON format")
747
+
748
+ # Command: report-bug
749
+ bug_p = subparsers.add_parser("report-bug", help="Report defect on test failure")
750
+ bug_p.add_argument("--project", default="QA", help="Project Key (e.g. PROJ)")
751
+ bug_p.add_argument("--tc-id", required=True, help="Test Case ID")
752
+ bug_p.add_argument("--summary", required=True, help="Bug summary title")
753
+ bug_p.add_argument("--error", required=True, help="Failure error message")
754
+ bug_p.add_argument("--stack", default="", help="Error stack trace")
755
+ bug_p.add_argument("--screenshot", default="", help="Path to FAILED screenshot")
756
+ bug_p.add_argument("--json", action="store_true", help="Output JSON format")
757
+
758
+ # Command: sync-run
759
+ sync_p = subparsers.add_parser("sync-run", help="Sync batch test execution results")
760
+ sync_p.add_argument("--plan-key", default="QA-PLAN-1", help="Xray Test Plan / Run Key")
761
+ sync_p.add_argument("--results-file", help="Path to JSON test results file")
762
+ sync_p.add_argument("--json", action="store_true", help="Output JSON format")
763
+
764
+ args = parser.parse_args()
765
+ bridge = TMSBridge(
766
+ provider=args.provider,
767
+ base_url=args.base_url,
768
+ api_token=args.token,
769
+ user_email=args.email,
770
+ auth_type=args.auth_type,
771
+ )
772
+
773
+ if args.command == "pull":
774
+ story = bridge.pull_story_acceptance_criteria(args.issue_key)
775
+ if args.json:
776
+ print(json.dumps(story, indent=2))
777
+ else:
778
+ print("\n======================================================================")
779
+ print(f" ENTERPRISE ALM STORY PULL: [{story.get('issue_key')}]")
780
+ print("======================================================================")
781
+ print(f" Summary : {story.get('summary')}")
782
+ print(f" Status : {story.get('status')} | Assignee: {story.get('assignee')}")
783
+ print(f" Source : {story.get('source')}\n")
784
+ print(" šŸ“‹ Acceptance Criteria (Given-When-Then):")
785
+ for ac in story.get("acceptance_criteria", []):
786
+ print(f" • {ac}")
787
+ print("======================================================================\n")
788
+ return 0
789
+
790
+ elif args.command == "report-bug":
791
+ ticket = bridge.report_defect(
792
+ project_key=args.project,
793
+ test_case_id=args.tc_id,
794
+ summary=args.summary,
795
+ error_message=args.error,
796
+ stack_trace=args.stack,
797
+ screenshot_path=args.screenshot
798
+ )
799
+ if args.json:
800
+ print(json.dumps(ticket, indent=2))
801
+ else:
802
+ print(f"\nšŸž [TMS DEFECT CREATED] Ticket: {ticket['ticket_key']}")
803
+ print(f" Summary : {ticket['summary']}")
804
+ print(f" Status : {ticket['status']} ({ticket['mode']})")
805
+ print(f" Artifact: {ticket['screenshot_attachment'] or 'None'}\n")
806
+ return 0
807
+
808
+ elif args.command == "sync-run":
809
+ res_list = []
810
+ if args.results_file and os.path.exists(args.results_file):
811
+ with open(args.results_file, "r", encoding="utf-8") as f:
812
+ res_list = json.load(f)
813
+ else:
814
+ res_list = [
815
+ {"tc_id": "TC-01", "status": "PASS", "duration_sec": 1.2},
816
+ {"tc_id": "TC-02", "status": "PASS", "duration_sec": 0.8},
817
+ {"tc_id": "TC-03", "status": "FAIL", "duration_sec": 2.5}
818
+ ]
819
+ sync = bridge.sync_execution_results(args.plan_key, res_list)
820
+ if args.json:
821
+ print(json.dumps(sync, indent=2))
822
+ else:
823
+ print(f"\nšŸ“Š [TMS EXECUTION SYNCED] Plan: {sync['test_plan_key']}")
824
+ print(f" Total Synced: {sync['total_synced']} | Pass Rate: {sync['pass_rate_pct']}%")
825
+ print(f" Destination : {sync['destination']}\n")
826
+ return 0
827
+
828
+ else:
829
+ parser.print_help()
830
+ return 0
831
+
832
+
833
+ if __name__ == "__main__":
834
+ sys.exit(main())