@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,1267 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Cross-Platform Token & Cost Auditor (Synapse-Hub)
4
+ Author: Thế Vị (@TeeVee98) <https://github.com/TeeVee98/Synapse-Hub>
5
+ License: MIT
6
+
7
+ Audits and counts exact token usage (Prompt Input, Cache Read, Output),
8
+ tracks 5-hour and 7-day rolling window quota usage, and benchmarks token & cost
9
+ savings enabled by Synapse-Hub context engineering.
10
+
11
+ Supported Platforms via Multi-Client Adapters:
12
+ 1. Google Antigravity (native exact tokens from transcript.jsonl)
13
+ 2. Cursor Agent (parses ~/.cursor/projects/*/agent-transcripts/*/*.jsonl)
14
+ 3. Claude Code (parses ~/.claude/ and session logs)
15
+ 4. Generic / Raw JSONL files (--file <path> with auto-format detection)
16
+
17
+ Usage:
18
+ python3 tools/count_tokens.py # Audit active Antigravity session
19
+ python3 tools/count_tokens.py --platform cursor # Audit latest Cursor session
20
+ python3 tools/count_tokens.py --platform all --list # List sessions across all platforms
21
+ python3 tools/count_tokens.py --platform cursor --turns # Turn-by-turn breakdown for Cursor
22
+ python3 tools/count_tokens.py --current # Analyze current active session
23
+ python3 tools/count_tokens.py --session <id> # Analyze specific session ID
24
+ python3 tools/count_tokens.py --rolling # Show 5-hour and 7-day rolling quota
25
+ python3 tools/count_tokens.py --savings # Show Hub vs. Non-Hub token & cost savings
26
+ python3 tools/count_tokens.py --header # Output markdown lines for Pre-Flight Block
27
+ python3 tools/count_tokens.py --file <path> # Direct audit of any transcript file
28
+ python3 tools/count_tokens.py --pricing claude-sonnet # Calculate cost with specific pricing model
29
+ python3 tools/count_tokens.py --json # Output machine-readable JSON
30
+ """
31
+
32
+ import os
33
+ import sys
34
+ import glob
35
+ import json
36
+ import re
37
+ import time
38
+ import hashlib
39
+ import sqlite3
40
+ import argparse
41
+ from datetime import datetime, timezone, timedelta
42
+ from typing import Dict, List, Any, Optional
43
+
44
+ PRICING_TABLE: Dict[str, Dict[str, Any]] = {
45
+ "gemini-flash": {
46
+ "name": "Google Gemini 2.5/3.x Flash",
47
+ "input_per_m": 0.075,
48
+ "cache_per_m": 0.01875,
49
+ "output_per_m": 0.30,
50
+ },
51
+ "gemini-pro": {
52
+ "name": "Google Gemini 1.5/2.5 Pro",
53
+ "input_per_m": 1.25,
54
+ "cache_per_m": 0.3125,
55
+ "output_per_m": 5.00,
56
+ },
57
+ "claude-sonnet": {
58
+ "name": "Anthropic Claude 3.5/3.7 Sonnet",
59
+ "input_per_m": 3.00,
60
+ "cache_per_m": 0.30,
61
+ "output_per_m": 15.00,
62
+ },
63
+ "claude-opus": {
64
+ "name": "Anthropic Claude 3/3.5 Opus",
65
+ "input_per_m": 15.00,
66
+ "cache_per_m": 1.50,
67
+ "output_per_m": 75.00,
68
+ },
69
+ "gpt-4o": {
70
+ "name": "OpenAI GPT-4o",
71
+ "input_per_m": 2.50,
72
+ "cache_per_m": 1.25,
73
+ "output_per_m": 10.00,
74
+ },
75
+ "gpt-4o-mini": {
76
+ "name": "OpenAI GPT-4o Mini",
77
+ "input_per_m": 0.15,
78
+ "cache_per_m": 0.075,
79
+ "output_per_m": 0.60,
80
+ },
81
+ }
82
+
83
+ DEFAULT_MODEL = "gemini-flash"
84
+ BUDGET_CONFIG_FILE = os.path.expanduser("~/.agent_memory/token_budget.json")
85
+
86
+ # Default quota limits (billable input tokens: uncached input + output)
87
+ DEFAULT_5H_BUDGET = 10_000_000 # 10M tokens / 5h
88
+ DEFAULT_7D_BUDGET = 100_000_000 # 100M tokens / 7d
89
+
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # Utility & Token Estimation Functions
93
+ # ---------------------------------------------------------------------------
94
+
95
+ def estimate_tokens(text: str) -> int:
96
+ """Accurate token estimator for polyglot text & code when native token metadata is absent."""
97
+ if not text:
98
+ return 0
99
+ non_ascii = len([c for c in text if ord(c) > 127])
100
+ ascii_len = len(text) - non_ascii
101
+ # Standard LLM BPE heuristic: ~3.8 chars/token for ASCII, ~1.8 chars/token for Unicode/CJK/Vietnamese
102
+ est = int((ascii_len / 3.8) + (non_ascii / 1.8))
103
+ return max(1, est)
104
+
105
+
106
+ def parse_token_shorthand(val: str) -> int:
107
+ """Parses token string with suffixes like 10M, 500K, 1B into an integer."""
108
+ v = val.strip().upper()
109
+ if v.endswith("K"):
110
+ return int(float(v[:-1]) * 1_000)
111
+ if v.endswith("M"):
112
+ return int(float(v[:-1]) * 1_000_000)
113
+ if v.endswith("B"):
114
+ return int(float(v[:-1]) * 1_000_000_000)
115
+ return int(float(v))
116
+
117
+
118
+ def format_token_shorthand(num: int) -> str:
119
+ """Formats large integer into clean readable string like 5.4M, 10M, 750K."""
120
+ if abs(num) >= 1_000_000_000:
121
+ val = num / 1_000_000_000
122
+ return f"{int(val)}B" if val.is_integer() else f"{val:.1f}B"
123
+ if abs(num) >= 1_000_000:
124
+ val = num / 1_000_000
125
+ return f"{int(val)}M" if val.is_integer() else f"{val:.1f}M"
126
+ if abs(num) >= 1_000:
127
+ val = num / 1_000
128
+ return f"{int(val)}K" if val.is_integer() else f"{val:.1f}K"
129
+ return str(num)
130
+
131
+
132
+ def get_budget_config() -> Dict[str, int]:
133
+ """Reads or initializes token budget configuration with file locking."""
134
+ if os.path.exists(BUDGET_CONFIG_FILE):
135
+ try:
136
+ try:
137
+ from tools.core.file_lock import locked_json_read
138
+ data = locked_json_read(BUDGET_CONFIG_FILE, timeout=5.0)
139
+ except ImportError:
140
+ with open(BUDGET_CONFIG_FILE, "r", encoding="utf-8") as f:
141
+ data = json.load(f)
142
+ return {
143
+ "budget_5h": data.get("budget_5h", DEFAULT_5H_BUDGET),
144
+ "budget_7d": data.get("budget_7d", DEFAULT_7D_BUDGET),
145
+ }
146
+ except (OSError, json.JSONDecodeError):
147
+ _ = False
148
+ return {
149
+ "budget_5h": DEFAULT_5H_BUDGET,
150
+ "budget_7d": DEFAULT_7D_BUDGET,
151
+ }
152
+
153
+
154
+ def save_budget_config(budget_5h: Optional[int] = None, budget_7d: Optional[int] = None):
155
+ """Saves updated token budget configuration with advisory file locking."""
156
+ cfg = get_budget_config()
157
+ if budget_5h is not None:
158
+ cfg["budget_5h"] = budget_5h
159
+ if budget_7d is not None:
160
+ cfg["budget_7d"] = budget_7d
161
+ os.makedirs(os.path.dirname(BUDGET_CONFIG_FILE), exist_ok=True)
162
+ try:
163
+ from tools.core.file_lock import locked_json_write
164
+ locked_json_write(BUDGET_CONFIG_FILE, cfg, timeout=5.0)
165
+ except ImportError:
166
+ with open(BUDGET_CONFIG_FILE, "w", encoding="utf-8") as f:
167
+ json.dump(cfg, f, indent=2)
168
+
169
+
170
+ # ---------------------------------------------------------------------------
171
+ # Platform Adapters
172
+ # ---------------------------------------------------------------------------
173
+
174
+ class AntigravityAdapter:
175
+ """Adapter for Google Antigravity workspace transcripts."""
176
+ name = "antigravity"
177
+
178
+ @staticmethod
179
+ def get_brain_dir() -> str:
180
+ home = os.path.expanduser("~")
181
+ candidates = [
182
+ os.path.join(home, ".gemini", "antigravity", "brain"),
183
+ os.path.join(home, ".config", "gemini", "antigravity", "brain"),
184
+ ]
185
+ for c in candidates:
186
+ if os.path.isdir(c):
187
+ return c
188
+ return candidates[0]
189
+
190
+ @staticmethod
191
+ def get_conversation_summaries_db() -> Optional[str]:
192
+ home = os.path.expanduser("~")
193
+ db_path = os.path.join(home, ".gemini", "antigravity", "conversation_summaries.db")
194
+ if os.path.exists(db_path):
195
+ return db_path
196
+ return None
197
+
198
+ @classmethod
199
+ def get_sessions(cls) -> List[Dict[str, Any]]:
200
+ brain_dir = cls.get_brain_dir()
201
+ if not os.path.exists(brain_dir):
202
+ return []
203
+
204
+ db_path = cls.get_conversation_summaries_db()
205
+ title_map = {}
206
+ if db_path:
207
+ try:
208
+ conn = sqlite3.connect(db_path)
209
+ try:
210
+ cursor = conn.cursor()
211
+ cursor.execute("SELECT conversation_id, title, step_count, last_modified_time FROM conversation_summaries")
212
+ for row in cursor.fetchall():
213
+ title_map[row[0]] = {
214
+ "title": row[1],
215
+ "step_count": row[2],
216
+ "last_modified": row[3],
217
+ }
218
+ finally:
219
+ conn.close()
220
+ except (sqlite3.Error, OSError):
221
+ _ = False
222
+
223
+ conversations = []
224
+ for entry in os.listdir(brain_dir):
225
+ entry_path = os.path.join(brain_dir, entry)
226
+ if not os.path.isdir(entry_path):
227
+ continue
228
+ transcript_file = os.path.join(entry_path, ".system_generated", "logs", "transcript.jsonl")
229
+ if not os.path.exists(transcript_file):
230
+ continue
231
+
232
+ mtime = os.path.getmtime(transcript_file)
233
+ meta = title_map.get(entry, {})
234
+ conversations.append({
235
+ "id": entry,
236
+ "path": entry_path,
237
+ "transcript_file": transcript_file,
238
+ "mtime": mtime,
239
+ "title": meta.get("title") or entry[:12],
240
+ "step_count": meta.get("step_count", 0),
241
+ "platform": "antigravity",
242
+ })
243
+
244
+ conversations.sort(key=lambda x: x["mtime"], reverse=True)
245
+ return conversations
246
+
247
+ @classmethod
248
+ def parse_transcript(cls, transcript_path: str) -> Dict[str, Any]:
249
+ if not os.path.exists(transcript_path):
250
+ return {"error": f"Transcript not found at {transcript_path}"}
251
+
252
+ turns = []
253
+ current_turn: Optional[Dict[str, Any]] = None
254
+ total_input = 0
255
+ total_cache = 0
256
+ total_output = 0
257
+ total_steps = 0
258
+ detected_model = "gemini-flash"
259
+
260
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
261
+ for line in f:
262
+ line = line.strip()
263
+ if not line or ("input_tokens" not in line and "USER_INPUT" not in line):
264
+ continue
265
+ try:
266
+ data = json.loads(line)
267
+ except json.JSONDecodeError:
268
+ continue
269
+
270
+ msg_type = data.get("type")
271
+ source = data.get("source")
272
+
273
+ if msg_type == "USER_INPUT":
274
+ content = data.get("content", "")
275
+ if "Model Selection" in content:
276
+ m = re.search(r"Model Selection[`'\"]?\s+from\s+.*?\s+to\s+([^.\n<]+)", content, re.IGNORECASE)
277
+ if m:
278
+ val = m.group(1).lower()
279
+ if "pro" in val:
280
+ detected_model = "gemini-pro"
281
+ elif "claude" in val or "sonnet" in val:
282
+ detected_model = "claude-sonnet"
283
+ elif "opus" in val:
284
+ detected_model = "claude-opus"
285
+ elif "gpt" in val:
286
+ detected_model = "gpt-4o"
287
+ elif "flash" in val:
288
+ detected_model = "gemini-flash"
289
+
290
+ if msg_type == "USER_INPUT" and source in ("USER_EXPLICIT", "USER"):
291
+ if current_turn:
292
+ turns.append(current_turn)
293
+
294
+ content = data.get("content", "")
295
+ user_req_match = re.search(r"<USER_REQUEST>\s*(.*?)\s*</USER_REQUEST>", content, re.DOTALL)
296
+ if user_req_match:
297
+ prompt_text = user_req_match.group(1).strip()
298
+ else:
299
+ prompt_text = content.strip()
300
+
301
+ current_turn = {
302
+ "turn_index": len(turns) + 1,
303
+ "prompt": prompt_text,
304
+ "created_at": data.get("created_at", ""),
305
+ "steps": 0,
306
+ "input_tokens": 0,
307
+ "cache_read_tokens": 0,
308
+ "output_tokens": 0,
309
+ "tools_called": [],
310
+ }
311
+ elif current_turn and "input_tokens" in data:
312
+ current_turn["steps"] += 1
313
+ in_tok = data.get("input_tokens", 0)
314
+ cache_tok = data.get("cache_read_tokens", 0)
315
+ out_tok = data.get("output_tokens", 0)
316
+
317
+ current_turn["input_tokens"] += in_tok
318
+ current_turn["cache_read_tokens"] += cache_tok
319
+ current_turn["output_tokens"] += out_tok
320
+
321
+ total_input += in_tok
322
+ total_cache += cache_tok
323
+ total_output += out_tok
324
+ total_steps += 1
325
+
326
+ for tc in data.get("tool_calls", []):
327
+ tool_name = tc.get("name")
328
+ if tool_name and tool_name not in current_turn["tools_called"]:
329
+ current_turn["tools_called"].append(tool_name)
330
+
331
+ if current_turn:
332
+ turns.append(current_turn)
333
+
334
+ total_all = total_input + total_cache + total_output
335
+ cache_hit_rate = (total_cache / (total_input + total_cache) * 100.0) if (total_input + total_cache) > 0 else 0.0
336
+
337
+ return {
338
+ "platform": "antigravity",
339
+ "transcript_path": transcript_path,
340
+ "turns_count": len(turns),
341
+ "steps_count": total_steps,
342
+ "input_tokens": total_input,
343
+ "cache_read_tokens": total_cache,
344
+ "output_tokens": total_output,
345
+ "billable_tokens": total_input + total_output,
346
+ "total_tokens": total_all,
347
+ "cache_hit_rate_pct": round(cache_hit_rate, 2),
348
+ "detected_model": detected_model,
349
+ "turns": turns,
350
+ }
351
+
352
+ @classmethod
353
+ def get_rolling_usage(cls, hours: int = 5, days: int = 7) -> Dict[str, Any]:
354
+ brain_dir = cls.get_brain_dir()
355
+ now = datetime.now(timezone.utc)
356
+ cutoff_hours = now - timedelta(hours=hours)
357
+ cutoff_days = now - timedelta(days=days)
358
+
359
+ usage_hours = {"steps": 0, "input": 0, "cache": 0, "output": 0}
360
+ usage_days = {"steps": 0, "input": 0, "cache": 0, "output": 0}
361
+
362
+ cutoff_timestamp = time.time() - (days * 86400)
363
+ search_pattern = os.path.join(brain_dir, "*", ".system_generated", "logs", "transcript.jsonl")
364
+ transcript_files = [
365
+ f for f in glob.glob(search_pattern)
366
+ if os.path.getmtime(f) >= cutoff_timestamp
367
+ ]
368
+
369
+ for fpath in transcript_files:
370
+ try:
371
+ with open(fpath, "r", encoding="utf-8", errors="replace") as f:
372
+ for line in f:
373
+ if "input_tokens" not in line:
374
+ continue
375
+ try:
376
+ d = json.loads(line)
377
+ except json.JSONDecodeError:
378
+ continue
379
+
380
+ created_str = d.get("created_at")
381
+ if not created_str:
382
+ continue
383
+ t = datetime.fromisoformat(created_str.replace("Z", "+00:00"))
384
+
385
+ in_tok = d.get("input_tokens", 0)
386
+ cache_tok = d.get("cache_read_tokens", 0)
387
+ out_tok = d.get("output_tokens", 0)
388
+
389
+ if t >= cutoff_days:
390
+ usage_days["steps"] += 1
391
+ usage_days["input"] += in_tok
392
+ usage_days["cache"] += cache_tok
393
+ usage_days["output"] += out_tok
394
+
395
+ if t >= cutoff_hours:
396
+ usage_hours["steps"] += 1
397
+ usage_hours["input"] += in_tok
398
+ usage_hours["cache"] += cache_tok
399
+ usage_hours["output"] += out_tok
400
+ except (OSError, UnicodeDecodeError):
401
+ _ = False
402
+
403
+ budgets = get_budget_config()
404
+ b_5h = budgets["budget_5h"]
405
+ b_7d = budgets["budget_7d"]
406
+
407
+ billable_5h = usage_hours["input"] + usage_hours["output"]
408
+ billable_7d = usage_days["input"] + usage_days["output"]
409
+
410
+ rem_5h = max(0, b_5h - billable_5h)
411
+ rem_7d = max(0, b_7d - billable_7d)
412
+
413
+ pct_used_5h = (billable_5h / b_5h * 100.0) if b_5h > 0 else 0.0
414
+ pct_used_7d = (billable_7d / b_7d * 100.0) if b_7d > 0 else 0.0
415
+
416
+ hit_rate_5h = (usage_hours["cache"] / (usage_hours["input"] + usage_hours["cache"]) * 100.0) if (usage_hours["input"] + usage_hours["cache"]) > 0 else 0.0
417
+ hit_rate_7d = (usage_days["cache"] / (usage_days["input"] + usage_days["cache"]) * 100.0) if (usage_days["input"] + usage_days["cache"]) > 0 else 0.0
418
+
419
+ return {
420
+ "window_5h": {
421
+ "hours": hours,
422
+ "steps": usage_hours["steps"],
423
+ "input_tokens": usage_hours["input"],
424
+ "cache_read_tokens": usage_hours["cache"],
425
+ "output_tokens": usage_hours["output"],
426
+ "billable_tokens": billable_5h,
427
+ "total_tokens": usage_hours["input"] + usage_hours["cache"] + usage_hours["output"],
428
+ "budget": b_5h,
429
+ "remaining_tokens": rem_5h,
430
+ "pct_used": round(pct_used_5h, 1),
431
+ "cache_hit_rate_pct": round(hit_rate_5h, 1),
432
+ },
433
+ "window_7d": {
434
+ "days": days,
435
+ "steps": usage_days["steps"],
436
+ "input_tokens": usage_days["input"],
437
+ "cache_read_tokens": usage_days["cache"],
438
+ "output_tokens": usage_days["output"],
439
+ "billable_tokens": billable_7d,
440
+ "total_tokens": usage_days["input"] + usage_days["cache"] + usage_days["output"],
441
+ "budget": b_7d,
442
+ "remaining_tokens": rem_7d,
443
+ "pct_used": round(pct_used_7d, 1),
444
+ "cache_hit_rate_pct": round(hit_rate_7d, 1),
445
+ },
446
+ }
447
+
448
+
449
+ class CursorAdapter:
450
+ """Adapter for Cursor Agent sessions (~/.cursor/projects/*/agent-transcripts/*/*.jsonl)."""
451
+ name = "cursor"
452
+
453
+ @staticmethod
454
+ def get_cursor_dir() -> str:
455
+ return os.path.expanduser("~/.cursor")
456
+
457
+ @classmethod
458
+ def get_sessions(cls) -> List[Dict[str, Any]]:
459
+ cursor_dir = cls.get_cursor_dir()
460
+ projects_dir = os.path.join(cursor_dir, "projects")
461
+ if not os.path.isdir(projects_dir):
462
+ return []
463
+
464
+ pattern = os.path.join(projects_dir, "*", "agent-transcripts", "*", "*.jsonl")
465
+ sessions: List[Dict[str, Any]] = []
466
+ for fpath in glob.glob(pattern):
467
+ try:
468
+ mtime = os.path.getmtime(fpath)
469
+ session_id = os.path.basename(os.path.dirname(fpath))
470
+ title = session_id[:12]
471
+
472
+ # Extract first user query for title
473
+ with open(fpath, "r", encoding="utf-8", errors="replace") as fp:
474
+ for line in fp:
475
+ if '"role":"user"' in line or '"role": "user"' in line:
476
+ d = json.loads(line)
477
+ for c in d.get("message", {}).get("content", []):
478
+ if c.get("type") == "text":
479
+ t = c.get("text", "")
480
+ m = re.search(r"<user_query>\s*(.*?)\s*</user_query>", t, re.DOTALL)
481
+ title = (m.group(1).strip() if m else t.strip()).replace("\n", " ")
482
+ break
483
+ if title != session_id[:12]:
484
+ break
485
+
486
+ sessions.append({
487
+ "id": session_id,
488
+ "path": os.path.dirname(fpath),
489
+ "transcript_file": fpath,
490
+ "mtime": mtime,
491
+ "title": title,
492
+ "platform": "cursor",
493
+ })
494
+ except Exception:
495
+ continue
496
+
497
+ sessions.sort(key=lambda x: x["mtime"], reverse=True)
498
+ return sessions
499
+
500
+ @classmethod
501
+ def parse_transcript(cls, transcript_path: str) -> Dict[str, Any]:
502
+ if not os.path.exists(transcript_path):
503
+ return {"error": f"Transcript not found at {transcript_path}"}
504
+
505
+ turns = []
506
+ current_turn: Optional[Dict[str, Any]] = None
507
+ total_input = 0
508
+ total_output = 0
509
+ total_cache = 0
510
+ total_steps = 0
511
+ accumulated_context = 4000 # Base system instructions context estimation
512
+
513
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
514
+ for line in f:
515
+ line = line.strip()
516
+ if not line:
517
+ continue
518
+ try:
519
+ data = json.loads(line)
520
+ except json.JSONDecodeError:
521
+ continue
522
+
523
+ role = data.get("role")
524
+ msg = data.get("message", {})
525
+ content = msg.get("content", [])
526
+
527
+ if role == "user":
528
+ text_blocks = [c.get("text", "") for c in content if c.get("type") == "text"]
529
+ tool_results = [c for c in content if c.get("type") == "tool_result"]
530
+ full_text = " ".join(text_blocks)
531
+
532
+ # New user request turn boundary
533
+ if "<user_query>" in full_text or (not tool_results and full_text.strip()):
534
+ if current_turn:
535
+ turns.append(current_turn)
536
+
537
+ m = re.search(r"<user_query>\s*(.*?)\s*</user_query>", full_text, re.DOTALL)
538
+ prompt = m.group(1).strip() if m else full_text.strip()
539
+ p_tokens = estimate_tokens(full_text)
540
+
541
+ # Prefix cache simulation for multi-turn conversations
542
+ uncached_in = p_tokens
543
+ cached_in = int(accumulated_context * 0.85)
544
+ accumulated_context += p_tokens
545
+
546
+ current_turn = {
547
+ "turn_index": len(turns) + 1,
548
+ "prompt": prompt,
549
+ "created_at": "",
550
+ "steps": 0,
551
+ "input_tokens": uncached_in,
552
+ "cache_read_tokens": cached_in,
553
+ "output_tokens": 0,
554
+ "tools_called": [],
555
+ }
556
+ total_input += uncached_in
557
+ total_cache += cached_in
558
+
559
+ elif current_turn and tool_results:
560
+ res_tokens = sum(estimate_tokens(str(tr.get("content", ""))) for tr in tool_results)
561
+ current_turn["input_tokens"] += res_tokens
562
+ current_turn["steps"] += 1
563
+ total_input += res_tokens
564
+ total_steps += 1
565
+ accumulated_context += res_tokens
566
+
567
+ elif role == "assistant" and current_turn:
568
+ current_turn["steps"] += 1
569
+ total_steps += 1
570
+ out_tok = 0
571
+ for block in content:
572
+ b_type = block.get("type")
573
+ if b_type == "text":
574
+ out_tok += estimate_tokens(block.get("text", ""))
575
+ elif b_type == "tool_use":
576
+ tname = block.get("name", "tool")
577
+ if tname not in current_turn["tools_called"]:
578
+ current_turn["tools_called"].append(tname)
579
+ out_tok += estimate_tokens(json.dumps(block.get("input", {})))
580
+
581
+ current_turn["output_tokens"] += out_tok
582
+ total_output += out_tok
583
+ accumulated_context += out_tok
584
+
585
+ if current_turn:
586
+ turns.append(current_turn)
587
+
588
+ total_all = total_input + total_cache + total_output
589
+ cache_hit_rate = (total_cache / (total_input + total_cache) * 100.0) if (total_input + total_cache) > 0 else 0.0
590
+
591
+ return {
592
+ "platform": "cursor",
593
+ "transcript_path": transcript_path,
594
+ "turns_count": len(turns),
595
+ "steps_count": total_steps,
596
+ "input_tokens": total_input,
597
+ "cache_read_tokens": total_cache,
598
+ "output_tokens": total_output,
599
+ "billable_tokens": total_input + total_output,
600
+ "total_tokens": total_all,
601
+ "cache_hit_rate_pct": round(cache_hit_rate, 2),
602
+ "detected_model": "claude-sonnet",
603
+ "turns": turns,
604
+ }
605
+
606
+
607
+ class ClaudeCodeAdapter:
608
+ """Adapter for Claude Code sessions (~/.claude/ and session records)."""
609
+ name = "claude"
610
+
611
+ @staticmethod
612
+ def get_claude_dirs() -> List[str]:
613
+ home = os.path.expanduser("~")
614
+ return [
615
+ os.path.join(home, ".claude"),
616
+ os.path.join(home, "Library", "Application Support", "Claude"),
617
+ ]
618
+
619
+ @classmethod
620
+ def get_sessions(cls) -> List[Dict[str, Any]]:
621
+ sessions: List[Dict[str, Any]] = []
622
+ home = os.path.expanduser("~")
623
+ # Search candidate directories
624
+ patterns = [
625
+ os.path.join(home, ".claude", "projects", "*", "*.jsonl"),
626
+ os.path.join(home, ".claude", "sessions", "*.jsonl"),
627
+ os.path.join(home, "Library", "Application Support", "Claude", "claude-code-sessions", "*", "*", "*.json"),
628
+ ]
629
+ for pat in patterns:
630
+ for fpath in glob.glob(pat):
631
+ try:
632
+ mtime = os.path.getmtime(fpath)
633
+ sid = os.path.basename(fpath).split(".")[0]
634
+ sessions.append({
635
+ "id": sid,
636
+ "path": os.path.dirname(fpath),
637
+ "transcript_file": fpath,
638
+ "mtime": mtime,
639
+ "title": f"Claude Session {sid[:8]}",
640
+ "platform": "claude",
641
+ })
642
+ except Exception:
643
+ continue
644
+
645
+ sessions.sort(key=lambda x: x["mtime"], reverse=True)
646
+ return sessions
647
+
648
+ @classmethod
649
+ def parse_transcript(cls, transcript_path: str) -> Dict[str, Any]:
650
+ # Fallback to Cursor / Anthropic message format parser
651
+ data = CursorAdapter.parse_transcript(transcript_path)
652
+ data["platform"] = "claude"
653
+ data["detected_model"] = "claude-sonnet"
654
+ return data
655
+
656
+
657
+ # ---------------------------------------------------------------------------
658
+ # Sniffer & Factory Dispatcher
659
+ # ---------------------------------------------------------------------------
660
+
661
+ def detect_platform_from_file(file_path: str) -> str:
662
+ """Sniffs the first few lines of a transcript to identify the AI platform format."""
663
+ if not os.path.exists(file_path):
664
+ return "antigravity"
665
+ try:
666
+ with open(file_path, "r", encoding="utf-8", errors="replace") as f:
667
+ for _ in range(20):
668
+ line = f.readline()
669
+ if not line:
670
+ break
671
+ if "USER_EXPLICIT" in line or "USER_INPUT" in line or "input_tokens" in line:
672
+ return "antigravity"
673
+ if '"role":"user"' in line or '"role": "user"' in line or "<user_query>" in line:
674
+ return "cursor"
675
+ if "claude" in line.lower():
676
+ return "claude"
677
+ except (OSError, UnicodeDecodeError):
678
+ _ = False
679
+ return "antigravity"
680
+
681
+
682
+ def get_adapter(platform: str):
683
+ """Factory retrieving the designated platform adapter."""
684
+ p = platform.lower()
685
+ if p == "cursor":
686
+ return CursorAdapter
687
+ if p == "claude":
688
+ return ClaudeCodeAdapter
689
+ return AntigravityAdapter
690
+
691
+
692
+ def get_all_sessions() -> List[Dict[str, Any]]:
693
+ """Retrieves all sessions across all installed AI platforms."""
694
+ all_sess = []
695
+ all_sess.extend(AntigravityAdapter.get_sessions())
696
+ all_sess.extend(CursorAdapter.get_sessions())
697
+ all_sess.extend(ClaudeCodeAdapter.get_sessions())
698
+ all_sess.sort(key=lambda x: x["mtime"], reverse=True)
699
+ return all_sess
700
+
701
+
702
+ # ---------------------------------------------------------------------------
703
+ # Cost & Savings Calculations
704
+ # ---------------------------------------------------------------------------
705
+
706
+ def calculate_cost(input_tokens: int, cache_tokens: int, output_tokens: int, model_key: str = DEFAULT_MODEL) -> Dict[str, Any]:
707
+ """Calculates estimated costs in USD based on model pricing."""
708
+ pricing = PRICING_TABLE.get(model_key, PRICING_TABLE[DEFAULT_MODEL])
709
+ input_cost = (input_tokens / 1_000_000) * pricing["input_per_m"]
710
+ cache_cost = (cache_tokens / 1_000_000) * pricing["cache_per_m"]
711
+ output_cost = (output_tokens / 1_000_000) * pricing["output_per_m"]
712
+ total_cost = input_cost + cache_cost + output_cost
713
+
714
+ return {
715
+ "model_name": pricing["name"],
716
+ "input_cost_usd": round(input_cost, 6),
717
+ "cache_cost_usd": round(cache_cost, 6),
718
+ "output_cost_usd": round(output_cost, 6),
719
+ "total_cost_usd": round(total_cost, 4),
720
+ }
721
+
722
+
723
+ def calculate_hub_savings(input_tokens: int, cache_tokens: int, output_tokens: int, model_key: str = DEFAULT_MODEL) -> Dict[str, Any]:
724
+ """
725
+ Empirical Hub Savings Model:
726
+ Compares actual Synapse-Hub execution against vanilla/non-Hub agent execution:
727
+ 1. Log Distillation (Observation Masking): Hub cuts CLI noise by 95% (raw vs distilled).
728
+ 2. Sparse Retrieval (Repo Map): 500-token AST map vs reading full 4,000-line classes.
729
+ 3. Compact AOM: <500-token interactive tree vs 15,000-token raw HTML DOM.
730
+ 4. KV-Cache Alignment: 95%+ Cache Hit vs <15% without prefix stability.
731
+ """
732
+ pricing = PRICING_TABLE.get(model_key, PRICING_TABLE[DEFAULT_MODEL])
733
+
734
+ estimated_non_hub_input = int(input_tokens * 3.5 + cache_tokens * 0.82)
735
+ estimated_non_hub_cache = int(cache_tokens * 0.18)
736
+ estimated_non_hub_output = output_tokens
737
+
738
+ estimated_non_hub_total = estimated_non_hub_input + estimated_non_hub_cache + estimated_non_hub_output
739
+ actual_hub_total = input_tokens + cache_tokens + output_tokens
740
+
741
+ cost_without_hub = (
742
+ (estimated_non_hub_input / 1_000_000) * pricing["input_per_m"]
743
+ + (estimated_non_hub_cache / 1_000_000) * pricing["cache_per_m"]
744
+ + (estimated_non_hub_output / 1_000_000) * pricing["output_per_m"]
745
+ )
746
+ cost_with_hub = (
747
+ (input_tokens / 1_000_000) * pricing["input_per_m"]
748
+ + (cache_tokens / 1_000_000) * pricing["cache_per_m"]
749
+ + (output_tokens / 1_000_000) * pricing["output_per_m"]
750
+ )
751
+
752
+ tokens_saved = max(0, estimated_non_hub_total - actual_hub_total)
753
+ cost_saved_usd = max(0.0, cost_without_hub - cost_with_hub)
754
+ savings_pct = (tokens_saved / estimated_non_hub_total * 100.0) if estimated_non_hub_total > 0 else 0.0
755
+ cost_savings_pct = (cost_saved_usd / cost_without_hub * 100.0) if cost_without_hub > 0 else 0.0
756
+
757
+ return {
758
+ "model_name": pricing["name"],
759
+ "non_hub_input": estimated_non_hub_input,
760
+ "non_hub_cache": estimated_non_hub_cache,
761
+ "non_hub_total": estimated_non_hub_total,
762
+ "non_hub_cost_usd": round(cost_without_hub, 4),
763
+ "hub_input": input_tokens,
764
+ "hub_cache": cache_tokens,
765
+ "hub_total": actual_hub_total,
766
+ "hub_cost_usd": round(cost_with_hub, 4),
767
+ "tokens_saved": tokens_saved,
768
+ "tokens_saved_shorthand": format_token_shorthand(tokens_saved),
769
+ "savings_pct": round(savings_pct, 1),
770
+ "cost_saved_usd": round(cost_saved_usd, 4),
771
+ "cost_savings_pct": round(cost_savings_pct, 1),
772
+ }
773
+
774
+
775
+ def get_preflight_block_lines(platform: str = "antigravity", model_key: str = DEFAULT_MODEL, lang: str = "vi") -> List[str]:
776
+ """Generates the dynamic markdown lines for the Pre-Flight Confirmation Block."""
777
+ rolling = AntigravityAdapter.get_rolling_usage()
778
+ w5 = rolling["window_5h"]
779
+ w7 = rolling["window_7d"]
780
+
781
+ adapter = get_adapter(platform)
782
+ convs = adapter.get_sessions()
783
+ last_task_line = ""
784
+
785
+ if convs:
786
+ parsed_cur = adapter.parse_transcript(convs[0]["transcript_file"])
787
+ if model_key == DEFAULT_MODEL and parsed_cur.get("detected_model"):
788
+ model_key = parsed_cur["detected_model"]
789
+ savings = calculate_hub_savings(w5["input_tokens"], w5["cache_read_tokens"], w5["output_tokens"], model_key)
790
+ if parsed_cur.get("turns"):
791
+ turns = parsed_cur["turns"]
792
+ target_t = turns[-1]
793
+ if len(turns) > 1 and target_t["steps"] <= 2:
794
+ target_t = turns[-2]
795
+
796
+ p_snippet = target_t["prompt"].replace("\n", " ").strip()
797
+ if len(p_snippet) > 35:
798
+ p_snippet = p_snippet[:32] + "..."
799
+
800
+ t_cost = calculate_cost(target_t["input_tokens"], target_t["cache_read_tokens"], target_t["output_tokens"], model_key)
801
+ tot_t = target_t["input_tokens"] + target_t["cache_read_tokens"] + target_t["output_tokens"]
802
+ vnd_val = int(t_cost["total_cost_usd"] * 25400)
803
+
804
+ if lang == "vi":
805
+ last_task_line = (
806
+ f"> 🎯 **Task vừa xong (Turn #{target_t['turn_index']}: \"{p_snippet}\"):** "
807
+ f"{target_t['steps']} steps | In: {target_t['input_tokens']:,} | Cache: {target_t['cache_read_tokens']:,} | "
808
+ f"Out: {target_t['output_tokens']:,} | 🔥 Tổng: {tot_t:,} token | 💰 Chi phí: ${t_cost['total_cost_usd']:.4f} (~{vnd_val:,} VNĐ)"
809
+ )
810
+ else:
811
+ last_task_line = (
812
+ f"> 🎯 **Completed Turn (Turn #{target_t['turn_index']}: \"{p_snippet}\"):** "
813
+ f"{target_t['steps']} steps | In: {target_t['input_tokens']:,} | Cache: {target_t['cache_read_tokens']:,} | "
814
+ f"Out: {target_t['output_tokens']:,} | 🔥 Total: {tot_t:,} tokens | 💰 Cost: ${t_cost['total_cost_usd']:.4f} (~{vnd_val:,} VND)"
815
+ )
816
+ else:
817
+ savings = calculate_hub_savings(w5["input_tokens"], w5["cache_read_tokens"], w5["output_tokens"], model_key)
818
+
819
+ u5_str = format_token_shorthand(w5['billable_tokens'])
820
+ b5_str = format_token_shorthand(w5['budget'])
821
+ rem5_str = format_token_shorthand(w5['remaining_tokens'])
822
+
823
+ u7_str = format_token_shorthand(w7['billable_tokens'])
824
+ b7_str = format_token_shorthand(w7['budget'])
825
+ rem7_str = format_token_shorthand(w7['remaining_tokens'])
826
+
827
+ if lang == "vi":
828
+ quota_line = (
829
+ f"> 📊 **Hạn mức Token:** "
830
+ f"5 Giờ: Đã dùng {u5_str} / {b5_str} (Còn lại {rem5_str}) ┃ "
831
+ f"7 Ngày: Đã dùng {u7_str} / {b7_str} (Còn lại {rem7_str}) ┃ "
832
+ f"Cache Hit: {w5['cache_hit_rate_pct']}%"
833
+ )
834
+ savings_line = (
835
+ f"> 💡 **Tiết kiệm nhờ Hub:** -{savings['cost_savings_pct']}% chi phí "
836
+ f"(~{savings['tokens_saved_shorthand']} token / ${savings['cost_saved_usd']:.2f} đã tiết kiệm vs. Không dùng Hub)"
837
+ )
838
+ else:
839
+ quota_line = (
840
+ f"> 📊 **Token Quotas:** "
841
+ f"5-Hour: Used {u5_str} / {b5_str} (Remaining {rem5_str}) ┃ "
842
+ f"7-Day: Used {u7_str} / {b7_str} (Remaining {rem7_str}) ┃ "
843
+ f"Cache Hit: {w5['cache_hit_rate_pct']}%"
844
+ )
845
+ savings_line = (
846
+ f"> 💡 **Hub Savings:** -{savings['cost_savings_pct']}% cost "
847
+ f"(~{savings['tokens_saved_shorthand']} tokens / ${savings['cost_saved_usd']:.2f} saved vs. without Hub)"
848
+ )
849
+
850
+ res = [quota_line]
851
+ if last_task_line:
852
+ res.append(last_task_line)
853
+ res.append(savings_line)
854
+ return res
855
+
856
+
857
+ # ---------------------------------------------------------------------------
858
+ # Output Formatters
859
+ # ---------------------------------------------------------------------------
860
+
861
+ def print_rolling_quota(rolling: Dict[str, Any], model_key: str = DEFAULT_MODEL):
862
+ """Outputs a rich terminal card for 5h and 7d rolling window quota."""
863
+ CYAN = "\033[96m"
864
+ GREEN = "\033[92m"
865
+ YELLOW = "\033[93m"
866
+ BOLD = "\033[1m"
867
+ DIM = "\033[2m"
868
+ RESET = "\033[0m"
869
+
870
+ w5 = rolling["window_5h"]
871
+ w7 = rolling["window_7d"]
872
+
873
+ print(f"\n{BOLD}{CYAN}{'='*75}{RESET}")
874
+ print(f"{BOLD}{CYAN} ⏳ ROLLING TOKEN QUOTA & USAGE (5H / 7-DAY){RESET}")
875
+ print(f"{BOLD}{CYAN}{'='*75}{RESET}")
876
+
877
+ print(f" {BOLD}{YELLOW}⏱️ 5-Hour Rolling Window:{RESET}")
878
+ print(f" • Steps Processed : {w5['steps']:,} steps")
879
+ print(f" • Billable Tokens Used: {BOLD}{w5['billable_tokens']:,}{RESET} / {w5['budget']:,} ({w5['pct_used']} % quota used)")
880
+ print(f" • Tokens Remaining : {BOLD}{GREEN}{w5['remaining_tokens']:,}{RESET} ({format_token_shorthand(w5['remaining_tokens'])})")
881
+ print(f" • KV Cache Read Tokens: {w5['cache_read_tokens']:,} {GREEN}(Cache Hit: {w5['cache_hit_rate_pct']} %){RESET}")
882
+ print(f" • Total Model Context : {w5['total_tokens']:,} tokens processed")
883
+ print(f"{DIM}{'-'*75}{RESET}")
884
+
885
+ print(f" {BOLD}{YELLOW}📅 7-Day (1-Week) Rolling Window:{RESET}")
886
+ print(f" • Steps Processed : {w7['steps']:,} steps")
887
+ print(f" • Billable Tokens Used: {BOLD}{w7['billable_tokens']:,}{RESET} / {w7['budget']:,} ({w7['pct_used']} % quota used)")
888
+ print(f" • Tokens Remaining : {BOLD}{GREEN}{w7['remaining_tokens']:,}{RESET} ({format_token_shorthand(w7['remaining_tokens'])})")
889
+ print(f" • KV Cache Read Tokens: {w7['cache_read_tokens']:,} {GREEN}(Cache Hit: {w7['cache_hit_rate_pct']} %){RESET}")
890
+ print(f" • Total Model Context : {w7['total_tokens']:,} tokens processed")
891
+ print(f"{BOLD}{CYAN}{'='*75}{RESET}\n")
892
+
893
+
894
+ def print_savings_card(savings: Dict[str, Any]):
895
+ """Outputs a rich comparison card: With Synapse-Hub vs. Without Hub."""
896
+ CYAN = "\033[96m"
897
+ GREEN = "\033[92m"
898
+ RED = "\033[91m"
899
+ MAGENTA = "\033[95m"
900
+ BOLD = "\033[1m"
901
+ DIM = "\033[2m"
902
+ RESET = "\033[0m"
903
+
904
+ print(f"\n{BOLD}{CYAN}{'='*75}{RESET}")
905
+ print(f"{BOLD}{CYAN} 💡 SYNAPSE-HUB CONTEXT OPTIMIZATION & SAVINGS BENCHMARK{RESET}")
906
+ print(f"{BOLD}{CYAN}{'='*75}{RESET}")
907
+ print(f" {BOLD}Pricing Model:{RESET} {savings['model_name']}")
908
+ print(f"{DIM}{'-'*75}{RESET}")
909
+ print(f" {'Metric':<28} | {'Without Hub (Raw)':<20} | {'With Synapse-Hub':<20}")
910
+ print(f" {'-'*75}")
911
+ print(f" {'Input Tokens (Fresh)':<28} | {RED}{savings['non_hub_input']:>18,d}{RESET} | {GREEN}{savings['hub_input']:>18,d}{RESET}")
912
+ print(f" {'KV Cache Read Tokens':<28} | {DIM}{savings['non_hub_cache']:>18,d}{RESET} | {GREEN}{savings['hub_cache']:>18,d}{RESET}")
913
+ print(f" {'Total Tokens Processed':<28} | {savings['non_hub_total']:>18,d} | {savings['hub_total']:>18,d}")
914
+ print(f" {'Estimated Cost (USD)':<28} | {RED}${savings['non_hub_cost_usd']:>17.4f}{RESET} | {GREEN}${savings['hub_cost_usd']:>17.4f}{RESET}")
915
+ print(f"{DIM}{'-'*75}{RESET}")
916
+ print(f" {BOLD}{MAGENTA}🎯 TOTAL TOKENS SAVED :{RESET} {BOLD}{GREEN}~{savings['tokens_saved']:,} tokens (-{savings['savings_pct']} % reduction){RESET}")
917
+ print(f" {BOLD}{MAGENTA}💰 ESTIMATED COST SAVED:{RESET} {BOLD}{GREEN}${savings['cost_saved_usd']:.4f} USD (-{savings['cost_savings_pct']} % saved){RESET}")
918
+ print(f"{BOLD}{CYAN}{'='*75}{RESET}\n")
919
+
920
+
921
+ def format_table(parsed_data: Dict[str, Any], title: str, model_key: str = DEFAULT_MODEL, show_turns: bool = False, last_task_only: bool = False):
922
+ """Outputs a clean, rich terminal box with formatted metrics."""
923
+ cost_info = calculate_cost(
924
+ parsed_data["input_tokens"],
925
+ parsed_data["cache_read_tokens"],
926
+ parsed_data["output_tokens"],
927
+ model_key,
928
+ )
929
+
930
+ CYAN = "\033[96m"
931
+ GREEN = "\033[92m"
932
+ YELLOW = "\033[93m"
933
+ MAGENTA = "\033[95m"
934
+ BOLD = "\033[1m"
935
+ DIM = "\033[2m"
936
+ RESET = "\033[0m"
937
+
938
+ platform_tag = parsed_data.get("platform", "generic").upper()
939
+
940
+ print(f"\n{BOLD}{CYAN}{'='*75}{RESET}")
941
+ print(f"{BOLD}{CYAN} 📊 TOKEN & COST AUDITOR | Synapse-Hub [{platform_tag}]{RESET}")
942
+ print(f"{BOLD}{CYAN}{'='*75}{RESET}")
943
+ print(f" {BOLD}Context / Session:{RESET} {title}")
944
+ print(f" {BOLD}Model Rate Basis :{RESET} {cost_info['model_name']}")
945
+ print(f" {BOLD}Total Turns / Req:{RESET} {parsed_data['turns_count']} turns | {parsed_data['steps_count']} steps")
946
+ print(f"{DIM}{'-'*75}{RESET}")
947
+
948
+ print(f" {BOLD}📥 Uncached Input Tokens :{RESET} {parsed_data['input_tokens']:>14,d} {DIM}(Fresh Context & Tool Results){RESET}")
949
+ print(f" {BOLD}⚡ KV Cache Read Tokens :{RESET} {parsed_data['cache_read_tokens']:>14,d} {GREEN}(Cache Hit: {parsed_data['cache_hit_rate_pct']} %){RESET}")
950
+ print(f" {BOLD}📤 Output / Think Tokens :{RESET} {parsed_data['output_tokens']:>14,d} {DIM}(Generated Reasoning & Actions){RESET}")
951
+ print(f"{DIM}{'-'*75}{RESET}")
952
+ print(f" {BOLD}{MAGENTA}🔥 TOTAL TOKENS PROCESSED:{RESET} {BOLD}{parsed_data['total_tokens']:>14,d}{RESET}")
953
+ print(f" {BOLD}{GREEN}💰 ESTIMATED TOTAL COST :{RESET} {BOLD}{GREEN}${cost_info['total_cost_usd']:>13.4f} USD{RESET}")
954
+ print(f"{DIM} ↳ Breakdown: Input: ${cost_info['input_cost_usd']:.4f} | Cache: ${cost_info['cache_cost_usd']:.4f} | Output: ${cost_info['output_cost_usd']:.4f}{RESET}")
955
+
956
+ if last_task_only and parsed_data["turns"]:
957
+ last_turn = parsed_data["turns"][-1]
958
+ t_cost = calculate_cost(last_turn["input_tokens"], last_turn["cache_read_tokens"], last_turn["output_tokens"], model_key)
959
+ prompt_snippet = last_turn["prompt"].replace("\n", " ")
960
+ if len(prompt_snippet) > 80:
961
+ prompt_snippet = prompt_snippet[:77] + "..."
962
+
963
+ print(f"\n{BOLD}{YELLOW}🎯 TARGET TASK (LAST TURN #{last_turn['turn_index']}):{RESET}")
964
+ print(f" {BOLD}User Request :{RESET} \"{prompt_snippet}\"")
965
+ print(f" {BOLD}Steps Run :{RESET} {last_turn['steps']} steps")
966
+ print(f" {BOLD}Tokens Used :{RESET} In: {last_turn['input_tokens']:,} | Cache: {last_turn['cache_read_tokens']:,} | Out: {last_turn['output_tokens']:,} | Total: {last_turn['input_tokens'] + last_turn['cache_read_tokens'] + last_turn['output_tokens']:,}")
967
+ print(f" {BOLD}Cost (USD) :{RESET} ${t_cost['total_cost_usd']:.4f}")
968
+ if last_turn["tools_called"]:
969
+ print(f" {BOLD}Tools Used :{RESET} {', '.join(last_turn['tools_called'])}")
970
+
971
+ elif show_turns and parsed_data["turns"]:
972
+ print(f"\n{BOLD}{YELLOW}📋 TURN-BY-TURN BREAKDOWN:{RESET}")
973
+ print(f" {'#':<3} | {'Steps':<5} | {'Input':<10} | {'Cache':<12} | {'Output':<8} | {'Total':<12} | {'Cost ($)':<8} | {'User Prompt':<30}")
974
+ print(f" {'-'*105}")
975
+ for t in parsed_data["turns"]:
976
+ t_tot = t["input_tokens"] + t["cache_read_tokens"] + t["output_tokens"]
977
+ t_cost = calculate_cost(t["input_tokens"], t["cache_read_tokens"], t["output_tokens"], model_key)
978
+ prompt_snippet = t["prompt"].replace("\n", " ")
979
+ if len(prompt_snippet) > 30:
980
+ prompt_snippet = prompt_snippet[:27] + "..."
981
+ print(f" {t['turn_index']:<3} | {t['steps']:<5} | {t['input_tokens']:<10,d} | {t['cache_read_tokens']:<12,d} | {t['output_tokens']:<8,d} | {t_tot:<12,d} | ${t_cost['total_cost_usd']:<7.4f} | {prompt_snippet}")
982
+
983
+ print(f"{BOLD}{CYAN}{'='*75}{RESET}\n")
984
+
985
+
986
+ def export_opentelemetry_genai_spans(parsed: Dict[str, Any], session_id: str = "sess_001") -> Dict[str, Any]:
987
+ """
988
+ Transforms session turns and tool execution steps into an OpenTelemetry GenAI-compliant Trace payload.
989
+ Adheres to OpenTelemetry Semantic Conventions for Generative AI:
990
+ - gen_ai.system (e.g. google, anthropic, openai)
991
+ - gen_ai.request.model (e.g. gemini-2.5-flash, claude-3-7-sonnet)
992
+ - gen_ai.usage.input_tokens / gen_ai.usage.prompt_tokens
993
+ - gen_ai.usage.output_tokens / gen_ai.usage.completion_tokens
994
+ - gen_ai.usage.total_tokens
995
+ - gen_ai.usage.cache_read_tokens
996
+ - tool.name / tool.system
997
+ """
998
+ trace_id = hashlib.md5(session_id.encode('utf-8'), usedforsecurity=False).hexdigest()
999
+ platform = parsed.get("platform", "antigravity")
1000
+ model = parsed.get("detected_model", "gemini-flash")
1001
+
1002
+ system_map = {
1003
+ "antigravity": "google",
1004
+ "cursor": "anthropic",
1005
+ "claude": "anthropic",
1006
+ "generic": "custom",
1007
+ }
1008
+ gen_ai_system = system_map.get(platform, "google")
1009
+
1010
+ spans: List[Dict[str, Any]] = []
1011
+ turns = parsed.get("turns", [])
1012
+ for idx, turn in enumerate(turns, 1):
1013
+ turn_span_id = hashlib.md5(f"{session_id}_turn_{idx}".encode('utf-8'), usedforsecurity=False).hexdigest()[:16]
1014
+ turn_start_nano = int(time.time() * 1e9) - (len(turns) - idx) * int(1e9)
1015
+
1016
+ turn_span = {
1017
+ "traceId": trace_id,
1018
+ "spanId": turn_span_id,
1019
+ "parentSpanId": None,
1020
+ "name": f"chat {model}",
1021
+ "kind": "SPAN_KIND_CLIENT",
1022
+ "startTimeUnixNano": turn_start_nano,
1023
+ "status": {"code": 1}, # STATUS_CODE_OK
1024
+ "attributes": [
1025
+ {"key": "gen_ai.system", "value": {"stringValue": gen_ai_system}},
1026
+ {"key": "gen_ai.operation.name", "value": {"stringValue": "chat"}},
1027
+ {"key": "gen_ai.request.model", "value": {"stringValue": model}},
1028
+ {"key": "gen_ai.usage.input_tokens", "value": {"intValue": turn.get("input_tokens", 0)}},
1029
+ {"key": "gen_ai.usage.output_tokens", "value": {"intValue": turn.get("output_tokens", 0)}},
1030
+ {"key": "gen_ai.usage.total_tokens", "value": {"intValue": turn.get("input_tokens", 0) + turn.get("output_tokens", 0)}},
1031
+ {"key": "gen_ai.usage.cache_read_tokens", "value": {"intValue": turn.get("cache_read_tokens", 0)}},
1032
+ {"key": "agent.turn_index", "value": {"intValue": idx}},
1033
+ ]
1034
+ }
1035
+ spans.append(turn_span)
1036
+
1037
+ for t_idx, tool_name in enumerate(turn.get("tools_called", []), 1):
1038
+ tool_span_id = hashlib.md5(f"{session_id}_turn_{idx}_tool_{t_idx}".encode('utf-8'), usedforsecurity=False).hexdigest()[:16]
1039
+ tool_span = {
1040
+ "traceId": trace_id,
1041
+ "spanId": tool_span_id,
1042
+ "parentSpanId": turn_span_id,
1043
+ "name": f"execute_tool {tool_name}",
1044
+ "kind": "SPAN_KIND_INTERNAL",
1045
+ "startTimeUnixNano": turn_start_nano + t_idx * int(1e8),
1046
+ "status": {"code": 1},
1047
+ "attributes": [
1048
+ {"key": "tool.name", "value": {"stringValue": tool_name}},
1049
+ {"key": "tool.system", "value": {"stringValue": "synapse-hub"}},
1050
+ {"key": "gen_ai.system", "value": {"stringValue": gen_ai_system}},
1051
+ ]
1052
+ }
1053
+ spans.append(tool_span)
1054
+
1055
+ return {
1056
+ "resourceSpans": [
1057
+ {
1058
+ "resource": {
1059
+ "attributes": [
1060
+ {"key": "service.name", "value": {"stringValue": "synapse-hub-agent"}},
1061
+ {"key": "service.version", "value": {"stringValue": "2.4.0"}},
1062
+ {"key": "gen_ai.system", "value": {"stringValue": gen_ai_system}},
1063
+ {"key": "session.id", "value": {"stringValue": session_id}},
1064
+ ]
1065
+ },
1066
+ "scopeSpans": [
1067
+ {
1068
+ "scope": {
1069
+ "name": "synapse.agent.opentelemetry",
1070
+ "version": "1.0.0"
1071
+ },
1072
+ "spans": spans
1073
+ }
1074
+ ]
1075
+ }
1076
+ ]
1077
+ }
1078
+
1079
+
1080
+ def list_sessions(conversations: List[Dict[str, Any]], limit: int = 15):
1081
+ """Lists recent conversations across platforms."""
1082
+ CYAN = "\033[96m"
1083
+ BOLD = "\033[1m"
1084
+ RESET = "\033[0m"
1085
+
1086
+ print(f"\n{BOLD}{CYAN}{'='*80}{RESET}")
1087
+ print(f"{BOLD}{CYAN} 📂 RECENT SESSIONS (CROSS-PLATFORM AUDIT){RESET}")
1088
+ print(f"{BOLD}{CYAN}{'='*80}{RESET}")
1089
+ print(f" {'#':<4} | {'Platform':<12} | {'Session ID':<34} | {'Title / Summary':<24}")
1090
+ print(f" {'-'*80}")
1091
+
1092
+ for idx, c in enumerate(conversations[:limit], 1):
1093
+ title = c['title'].replace('\n', ' ')
1094
+ if len(title) > 23:
1095
+ title = title[:21] + ".."
1096
+ plat = c.get('platform', 'unknown').capitalize()
1097
+ sid = c['id']
1098
+ if len(sid) > 32:
1099
+ sid = sid[:30] + ".."
1100
+ print(f" {idx:<4} | {plat:<12} | {sid:<34} | {title:<24}")
1101
+ print(f"{BOLD}{CYAN}{'='*80}{RESET}\n")
1102
+
1103
+
1104
+ # ---------------------------------------------------------------------------
1105
+ # Main CLI Entrypoint
1106
+ # ---------------------------------------------------------------------------
1107
+
1108
+ def main():
1109
+ parser = argparse.ArgumentParser(description="Cross-Platform Token & Cost Auditor (Antigravity, Cursor, Claude Code)")
1110
+ parser.add_argument("--platform", "-p", choices=["auto", "antigravity", "cursor", "claude", "all"], default="auto", help="AI platform to audit (default: auto)")
1111
+ parser.add_argument("--session", type=str, help="Specific session ID or index to audit")
1112
+ parser.add_argument("--current", action="store_true", help="Audit the current active conversation")
1113
+ parser.add_argument("--last", action="store_true", help="Audit the previous completed session (default)")
1114
+ parser.add_argument("--last-task", action="store_true", help="Audit specifically the last turn of the target session")
1115
+ parser.add_argument("--turns", action="store_true", help="Show full turn-by-turn breakdown table")
1116
+ parser.add_argument("--rolling", "--budget", action="store_true", dest="rolling", help="Show 5-hour and 7-day rolling window quota & remaining tokens")
1117
+ parser.add_argument("--savings", action="store_true", help="Show Hub vs. Non-Hub token and cost savings comparison")
1118
+ parser.add_argument("--header", action="store_true", help="Print Pre-Flight confirmation block lines")
1119
+ parser.add_argument("--lang", choices=["vi", "en"], default="vi", help="Language for headers and summaries (default: vi)")
1120
+ parser.add_argument("--set-budget-5h", type=str, help="Set 5-hour quota budget (e.g. 10M, 500K)")
1121
+ parser.add_argument("--set-budget-7d", type=str, help="Set 7-day quota budget (e.g. 100M, 50M)")
1122
+ parser.add_argument("--list", action="store_true", help="List recent conversations")
1123
+ parser.add_argument("--pricing", choices=list(PRICING_TABLE.keys()), default=None, help="Model pricing basis (default: auto-detected from transcript)")
1124
+ parser.add_argument("--json", action="store_true", help="Output machine-readable JSON format")
1125
+ parser.add_argument("--otel", "--opentelemetry", action="store_true", dest="otel", help="Export session spans formatted according to OpenTelemetry GenAI Semantic Conventions")
1126
+ parser.add_argument("--file", type=str, help="Direct path to any transcript JSONL file")
1127
+
1128
+ args = parser.parse_args()
1129
+
1130
+ # Update budgets if requested
1131
+ if args.set_budget_5h or args.set_budget_7d:
1132
+ b5 = parse_token_shorthand(args.set_budget_5h) if args.set_budget_5h else None
1133
+ b7 = parse_token_shorthand(args.set_budget_7d) if args.set_budget_7d else None
1134
+ save_budget_config(b5, b7)
1135
+ print(f"✅ Token budget updated: 5h = {format_token_shorthand(b5 or get_budget_config()['budget_5h'])}, 7d = {format_token_shorthand(b7 or get_budget_config()['budget_7d'])}")
1136
+
1137
+ # Direct file audit mode
1138
+ if args.file:
1139
+ plat = detect_platform_from_file(args.file)
1140
+ adapter = get_adapter(plat)
1141
+ parsed = adapter.parse_transcript(args.file)
1142
+ active_pricing = args.pricing or parsed.get("detected_model", DEFAULT_MODEL)
1143
+
1144
+ if args.otel:
1145
+ otel_spans = export_opentelemetry_genai_spans(parsed, os.path.basename(args.file))
1146
+ print(json.dumps(otel_spans, indent=2, ensure_ascii=False))
1147
+ return
1148
+
1149
+ if args.json:
1150
+ parsed["costs"] = calculate_cost(parsed["input_tokens"], parsed["cache_read_tokens"], parsed["output_tokens"], active_pricing)
1151
+ parsed["savings"] = calculate_hub_savings(parsed["input_tokens"], parsed["cache_read_tokens"], parsed["output_tokens"], active_pricing)
1152
+ print(json.dumps(parsed, indent=2, ensure_ascii=False))
1153
+ else:
1154
+ format_table(parsed, f"File: {args.file}", active_pricing, args.turns, args.last_task)
1155
+ return
1156
+
1157
+ # Header generation mode
1158
+ if args.header:
1159
+ plat = "antigravity" if args.platform in ("auto", "all") else args.platform
1160
+ active_pricing = args.pricing or DEFAULT_MODEL
1161
+ lines = get_preflight_block_lines(plat, active_pricing, args.lang)
1162
+ for line in lines:
1163
+ print(line)
1164
+ return
1165
+
1166
+ # Rolling quota mode
1167
+ if args.rolling:
1168
+ rolling = AntigravityAdapter.get_rolling_usage()
1169
+ active_pricing = args.pricing or DEFAULT_MODEL
1170
+ if args.json:
1171
+ print(json.dumps(rolling, indent=2))
1172
+ else:
1173
+ print_rolling_quota(rolling, active_pricing)
1174
+ return
1175
+
1176
+ # Hub savings mode
1177
+ if args.savings:
1178
+ rolling = AntigravityAdapter.get_rolling_usage()
1179
+ w5 = rolling["window_5h"]
1180
+ active_pricing = args.pricing or DEFAULT_MODEL
1181
+ savings = calculate_hub_savings(w5["input_tokens"], w5["cache_read_tokens"], w5["output_tokens"], active_pricing)
1182
+ if args.json:
1183
+ print(json.dumps(savings, indent=2))
1184
+ else:
1185
+ print_savings_card(savings)
1186
+ return
1187
+
1188
+ # Platform resolution
1189
+ if args.platform == "all":
1190
+ conversations = get_all_sessions()
1191
+ elif args.platform == "cursor":
1192
+ conversations = CursorAdapter.get_sessions()
1193
+ elif args.platform == "claude":
1194
+ conversations = ClaudeCodeAdapter.get_sessions()
1195
+ else:
1196
+ # Default 'auto': check Antigravity first, fallback to Cursor if empty
1197
+ conversations = AntigravityAdapter.get_sessions()
1198
+ if not conversations:
1199
+ conversations = CursorAdapter.get_sessions()
1200
+
1201
+ if not conversations:
1202
+ print(f"❌ No AI conversation sessions found for platform '{args.platform}'.")
1203
+ sys.exit(1)
1204
+
1205
+ if args.list:
1206
+ list_sessions(conversations)
1207
+ return
1208
+
1209
+ # Target session selection logic
1210
+ target_conv = None
1211
+ if args.session:
1212
+ if args.session.isdigit():
1213
+ idx = int(args.session) - 1
1214
+ if 0 <= idx < len(conversations):
1215
+ target_conv = conversations[idx]
1216
+ else:
1217
+ print(f"❌ Index {args.session} out of range (1..{len(conversations)})")
1218
+ sys.exit(1)
1219
+ else:
1220
+ for c in conversations:
1221
+ if c["id"].startswith(args.session):
1222
+ target_conv = c
1223
+ break
1224
+ if not target_conv:
1225
+ print(f"❌ Conversation '{args.session}' not found.")
1226
+ sys.exit(1)
1227
+ elif args.current:
1228
+ target_conv = conversations[0]
1229
+ else:
1230
+ # Default: pick previous session if available
1231
+ if len(conversations) > 1 and not args.current:
1232
+ target_conv = conversations[1]
1233
+ else:
1234
+ target_conv = conversations[0]
1235
+
1236
+ # Parse selected session via its respective adapter
1237
+ session_plat = target_conv.get("platform", "antigravity")
1238
+ adapter = get_adapter(session_plat)
1239
+ parsed = adapter.parse_transcript(target_conv["transcript_file"])
1240
+
1241
+ active_pricing = args.pricing
1242
+ if not active_pricing:
1243
+ active_pricing = parsed.get("detected_model") or ("claude-sonnet" if session_plat == "cursor" else DEFAULT_MODEL)
1244
+
1245
+ if args.otel:
1246
+ otel_spans = export_opentelemetry_genai_spans(parsed, target_conv.get("id", "session_001"))
1247
+ print(json.dumps(otel_spans, indent=2, ensure_ascii=False))
1248
+ return
1249
+
1250
+ if args.json:
1251
+ parsed["session_id"] = target_conv["id"]
1252
+ parsed["title"] = target_conv["title"]
1253
+ parsed["costs"] = calculate_cost(parsed["input_tokens"], parsed["cache_read_tokens"], parsed["output_tokens"], active_pricing)
1254
+ parsed["savings"] = calculate_hub_savings(parsed["input_tokens"], parsed["cache_read_tokens"], parsed["output_tokens"], active_pricing)
1255
+ print(json.dumps(parsed, indent=2, ensure_ascii=False))
1256
+ else:
1257
+ format_table(
1258
+ parsed,
1259
+ f"{target_conv['id']} ({target_conv['title']})",
1260
+ active_pricing,
1261
+ args.turns,
1262
+ args.last_task,
1263
+ )
1264
+
1265
+
1266
+ if __name__ == "__main__":
1267
+ main()