bugx-cli 0.1.1__py3-none-any.whl

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 (762) hide show
  1. bugx_cli/__init__.py +6 -0
  2. bugx_cli/cli.py +1685 -0
  3. bugx_cli/commands/__init__.py +1 -0
  4. bugx_cli/commands/advisory.py +94 -0
  5. bugx_cli/commands/agent.py +4210 -0
  6. bugx_cli/commands/audit.py +632 -0
  7. bugx_cli/commands/autonomous.py +260 -0
  8. bugx_cli/commands/cloud.py +1371 -0
  9. bugx_cli/commands/daemon.py +50 -0
  10. bugx_cli/commands/doctor.py +1590 -0
  11. bugx_cli/commands/goal.py +107 -0
  12. bugx_cli/commands/interaction.py +248 -0
  13. bugx_cli/commands/knowledge.py +619 -0
  14. bugx_cli/commands/lifecycle.py +2763 -0
  15. bugx_cli/commands/patch.py +1014 -0
  16. bugx_cli/commands/plugin.py +2749 -0
  17. bugx_cli/commands/plugin_claude.py +1446 -0
  18. bugx_cli/commands/plugin_cline.py +269 -0
  19. bugx_cli/commands/plugin_codex.py +74 -0
  20. bugx_cli/commands/plugin_funide.py +729 -0
  21. bugx_cli/commands/plugin_qoder.py +216 -0
  22. bugx_cli/commands/plugin_zcode.py +710 -0
  23. bugx_cli/commands/project.py +670 -0
  24. bugx_cli/commands/report.py +256 -0
  25. bugx_cli/commands/skill.py +251 -0
  26. bugx_cli/commands/stats.py +133 -0
  27. bugx_cli/commands/system.py +2567 -0
  28. bugx_cli/common.py +906 -0
  29. bugx_cli/host_adapters.py +1892 -0
  30. bugx_cli/hosts/__init__.py +80 -0
  31. bugx_cli/hosts/base.py +99 -0
  32. bugx_cli/hosts/registry.py +573 -0
  33. bugx_cli/hosts/template_engine.py +188 -0
  34. bugx_cli/infra/__init__.py +209 -0
  35. bugx_cli/infra/ai_advisor.py +851 -0
  36. bugx_cli/infra/engine_installer.py +1945 -0
  37. bugx_cli/infra/host_sync.py +548 -0
  38. bugx_cli/infra/mcp_advisor.py +826 -0
  39. bugx_cli/infra/security.py +339 -0
  40. bugx_cli-0.1.1.data/data/share/bugx-agent/bugx-mcp-manifest.json +53 -0
  41. bugx_cli-0.1.1.data/data/share/bugx-agent/core/CATALOG.json +141 -0
  42. bugx_cli-0.1.1.data/data/share/bugx-agent/core/README.md +254 -0
  43. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/README.md +35 -0
  44. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android-interaction.json +81 -0
  45. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android.json +24 -0
  46. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/desktop-macos.json +20 -0
  47. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios-interaction.json +34 -0
  48. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios.json +23 -0
  49. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/memory-macos.json +24 -0
  50. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/README.md +51 -0
  51. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/__init__.py +146 -0
  52. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_artifacts.py +766 -0
  53. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_eval.py +1155 -0
  54. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_execution.py +718 -0
  55. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_orchestrator.py +1351 -0
  56. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_targets.py +877 -0
  57. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_workspace.py +770 -0
  58. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/feature_baseline.py +150 -0
  59. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/README.md +24 -0
  60. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  61. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE.txt +362 -0
  62. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/UPSTREAM.md +10 -0
  63. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/axe.min.js +12 -0
  64. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-1024.png +0 -0
  65. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-512.png +0 -0
  66. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-tight.svg +23 -0
  67. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar.svg +28 -0
  68. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-cn.png +0 -0
  69. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.png +0 -0
  70. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.svg +74 -0
  71. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-zh.svg +74 -0
  72. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/codex.png +0 -0
  73. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/dsh.png +0 -0
  74. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/project-layout.md +42 -0
  75. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/zcode.png +0 -0
  76. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/README.md +37 -0
  77. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/manifest.json +94 -0
  78. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  79. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  80. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  81. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  82. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/manifest.json +123 -0
  83. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  84. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  85. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  86. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  87. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  88. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/memory-testing.md +227 -0
  89. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/manifest.json +155 -0
  90. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/android.md +19 -0
  91. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  92. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  93. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  94. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  95. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  96. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  97. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  98. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  99. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  100. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  101. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/manifest.json +127 -0
  102. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  103. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  104. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  105. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  106. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  107. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/platform-testing.md +174 -0
  108. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/manifest.json +191 -0
  109. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/graphql.md +5 -0
  110. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/h5.md +18 -0
  111. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  112. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/oauth.md +4 -0
  113. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/upload.md +4 -0
  114. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/websocket.md +4 -0
  115. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  116. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  117. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  118. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  119. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  120. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  121. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  122. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  123. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  124. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/INTERFACE.md +61 -0
  125. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/README.md +58 -0
  126. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/SPEC.md +25 -0
  127. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/__init__.py +109 -0
  128. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph.py +1096 -0
  129. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph_store.py +1868 -0
  130. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/audit_campaign.py +1232 -0
  131. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/behavior_graph.py +465 -0
  132. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/ghsa_advisories.py +174 -0
  133. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/models.py +93 -0
  134. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/mutator.py +87 -0
  135. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/patcher.py +126 -0
  136. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/scout.py +278 -0
  137. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/synthesizer.py +207 -0
  138. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/verifier.py +103 -0
  139. bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx.md +1299 -0
  140. bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx_paths.py +1881 -0
  141. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cli-help.txt +66 -0
  142. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/INTERFACE.md +32 -0
  143. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/README.md +62 -0
  144. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/SPEC.md +25 -0
  145. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/__init__.py +23 -0
  146. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/auto_sync.py +398 -0
  147. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_client.py +1218 -0
  148. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_onboard.py +743 -0
  149. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_schema.py +648 -0
  150. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/consent.py +81 -0
  151. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/device_identity.py +307 -0
  152. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/endpoint_router.py +415 -0
  153. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/flywheel_client.py +769 -0
  154. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/network_transport.py +296 -0
  155. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/onboard_wizard.py +493 -0
  156. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sensitive_filter.py +285 -0
  157. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_pull.py +695 -0
  158. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_push.py +723 -0
  159. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/AGENT_GUIDE.md +359 -0
  160. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/README.md +34 -0
  161. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-blackbox.md +541 -0
  162. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-opencode.md +469 -0
  163. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-quick.md +44 -0
  164. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-runtime-contract.md +353 -0
  165. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-worker.md +470 -0
  166. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/engine_gap_contracts.py +473 -0
  167. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/README.md +70 -0
  168. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/__init__.py +106 -0
  169. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_ai_review.py +185 -0
  170. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_backfill.py +54 -0
  171. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_bootstrap.py +713 -0
  172. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_business.py +36 -0
  173. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_cli.py +715 -0
  174. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_discovery.py +1429 -0
  175. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_evidence.py +1024 -0
  176. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_forensics.py +124 -0
  177. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_gate.py +277 -0
  178. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_intelligence.py +734 -0
  179. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_manifest.py +396 -0
  180. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_platform.py +77 -0
  181. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_validate.py +241 -0
  182. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/module_coverage.py +157 -0
  183. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/INTERFACE.md +20 -0
  184. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/README.md +21 -0
  185. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/SPEC.md +25 -0
  186. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/__init__.py +5 -0
  187. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/interaction_preset.py +408 -0
  188. bugx_cli-0.1.1.data/data/share/bugx-agent/core/engine-integrity.json +2797 -0
  189. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/README.md +49 -0
  190. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/__init__.py +82 -0
  191. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/concurrency_fuzzer.py +435 -0
  192. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/differential_oracle.py +1164 -0
  193. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/fuzz_input.py +1291 -0
  194. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/stateful_fuzzer.py +404 -0
  195. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/README.md +61 -0
  196. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/__init__.py +130 -0
  197. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/capacity_planner.py +124 -0
  198. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/dependency_lock.py +317 -0
  199. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/goal_governor.py +754 -0
  200. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/guide_budget.py +458 -0
  201. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/lockdown.sh +50 -0
  202. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/readonly_enforcer.py +154 -0
  203. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/runtime_tool_gate.py +373 -0
  204. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/secret_redactor.py +784 -0
  205. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/token_budget.py +38 -0
  206. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/INTERFACE.md +36 -0
  207. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/README.md +51 -0
  208. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/SPEC.md +25 -0
  209. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/__init__.py +121 -0
  210. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/base.py +111 -0
  211. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/claude.py +99 -0
  212. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/cline.py +298 -0
  213. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/codex.py +300 -0
  214. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/dsh.py +106 -0
  215. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/opencode.py +209 -0
  216. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/pi.py +94 -0
  217. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/zcode.py +99 -0
  218. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/INTERFACE.md +24 -0
  219. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/README.md +62 -0
  220. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/SPEC.md +25 -0
  221. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/__init__.py +21 -0
  222. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/adapters.py +412 -0
  223. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/autonomous_runner.py +1152 -0
  224. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/cline.py +448 -0
  225. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/common.py +103 -0
  226. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/free_models.py +786 -0
  227. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_bootstrap.py +389 -0
  228. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_evaluators.py +761 -0
  229. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_probe.py +41 -0
  230. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_provider_arbitrator.py +831 -0
  231. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_registry.py +662 -0
  232. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_usage.py +127 -0
  233. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_process_tracker.py +509 -0
  234. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_registry_gate.py +379 -0
  235. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/pi.py +102 -0
  236. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/provider_facts.py +66 -0
  237. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/INTERFACE.md +51 -0
  238. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/README.md +67 -0
  239. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/SPEC.md +25 -0
  240. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/__init__.py +140 -0
  241. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_base_usage.py +152 -0
  242. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_codex_usage.py +297 -0
  243. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_dsh_usage.py +184 -0
  244. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_mcp_toml.py +365 -0
  245. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_zcode_usage.py +269 -0
  246. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/base.py +479 -0
  247. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/claude.py +212 -0
  248. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/cline.py +229 -0
  249. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/codex.py +1006 -0
  250. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/dsh.py +526 -0
  251. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/opencode.py +358 -0
  252. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/pi.py +308 -0
  253. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/zcode.py +219 -0
  254. bugx_cli-0.1.1.data/data/share/bugx-agent/core/i18n.py +252 -0
  255. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/README.md +41 -0
  256. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/__init__.py +17 -0
  257. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/build_info.py +105 -0
  258. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/client_metadata.py +185 -0
  259. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/json_utils.py +22 -0
  260. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/python_runtime.py +540 -0
  261. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/safe_xml.py +221 -0
  262. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_bugx.py +118 -0
  263. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/INTERFACE.md +31 -0
  264. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/README.md +106 -0
  265. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/SPEC.md +25 -0
  266. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/__init__.py +29 -0
  267. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/candidate_revalidation.py +484 -0
  268. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/common.py +1060 -0
  269. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_confirm_phase.py +391 -0
  270. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_settlement.py +1432 -0
  271. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_adjudication.py +666 -0
  272. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_snapshot.py +357 -0
  273. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/judge_phase.py +848 -0
  274. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lesson_context.py +536 -0
  275. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lifecycle_reporter.py +627 -0
  276. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/orchestrator_controls.py +686 -0
  277. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_commit.py +567 -0
  278. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_coverage_sync.py +598 -0
  279. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_dry_run.py +817 -0
  280. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_observability.py +367 -0
  281. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_phase.py +1223 -0
  282. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_receipt.py +373 -0
  283. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_round_lifecycle.py +786 -0
  284. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_phase.py +1029 -0
  285. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_recon_scout.py +879 -0
  286. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_state_builder.py +1133 -0
  287. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/report_sharing.py +414 -0
  288. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/round_orchestrator.py +1116 -0
  289. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/session_runtime.py +1670 -0
  290. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_gates.py +1050 -0
  291. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_interaction.py +1003 -0
  292. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_version_gate.py +879 -0
  293. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_bridge.py +1253 -0
  294. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_coverage.py +423 -0
  295. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_degraded.py +1211 -0
  296. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_barriers.py +424 -0
  297. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_orchestrator.py +1246 -0
  298. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_prior.py +749 -0
  299. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/INTERFACE.md +35 -0
  300. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/README.md +160 -0
  301. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/SPEC.md +25 -0
  302. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/__init__.py +67 -0
  303. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/_facade.py +227 -0
  304. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/archive_ops.py +630 -0
  305. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/auto_materialization.py +459 -0
  306. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/bug-log.md +22 -0
  307. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/cli.py +275 -0
  308. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/export_ops.py +554 -0
  309. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_confirmation.py +1316 -0
  310. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_io.py +299 -0
  311. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_lifecycle.py +730 -0
  312. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_verification.py +405 -0
  313. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/incidents.py +1005 -0
  314. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson-replay-cases.json +20 -0
  315. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_ledger.py +241 -0
  316. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_replay.py +272 -0
  317. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/life_ledger.py +668 -0
  318. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/mistake-book.md +130 -0
  319. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/patterns.py +684 -0
  320. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/receipt_contract.py +269 -0
  321. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/schema.py +1192 -0
  322. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/sync_ops.py +940 -0
  323. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/tool_experience.py +683 -0
  324. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/verify_life.py +1597 -0
  325. bugx_cli-0.1.1.data/data/share/bugx-agent/core/lesson-ledger.json +275 -0
  326. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/README.md +19 -0
  327. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/en-US.json +462 -0
  328. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/zh-CN.json +462 -0
  329. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/INTERFACE.md +75 -0
  330. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/README.md +62 -0
  331. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/SPEC.md +25 -0
  332. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/__init__.py +128 -0
  333. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/base.py +717 -0
  334. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/channel_lifecycle.py +751 -0
  335. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/graph_handlers.py +222 -0
  336. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/knowledge_handlers.py +536 -0
  337. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/mining_handlers.py +586 -0
  338. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/resource_prompt_table.py +116 -0
  339. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/retrieval_handlers.py +249 -0
  340. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/rpc_server.py +470 -0
  341. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/supervisor_handlers.py +1461 -0
  342. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/telemetry_handlers.py +227 -0
  343. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/tool_table.py +1030 -0
  344. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/README.md +21 -0
  345. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/__init__.py +1 -0
  346. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/common.py +363 -0
  347. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/environment.py +567 -0
  348. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/verifier.py +758 -0
  349. bugx_cli-0.1.1.data/data/share/bugx-agent/core/metadata.txt +4 -0
  350. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/README.md +157 -0
  351. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/__init__.py +242 -0
  352. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_plan.py +187 -0
  353. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_planner.py +195 -0
  354. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_archetype.py +542 -0
  355. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_router.py +269 -0
  356. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/dynamic_flow_analyzer.py +533 -0
  357. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/impact_pruner.py +435 -0
  358. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/intent_adjudicator.py +175 -0
  359. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/judge_pipeline.py +1246 -0
  360. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/logic_analysis.py +419 -0
  361. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/prompt_harness.py +1704 -0
  362. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/source_inspector.py +267 -0
  363. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/spec_harvester.py +449 -0
  364. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/target_sandbox_manager.py +573 -0
  365. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/test_capability_verifier.py +1364 -0
  366. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/tools-kb.md +38 -0
  367. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/unit_kind.py +122 -0
  368. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/INTERFACE.md +83 -0
  369. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/README.md +51 -0
  370. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/SPEC.md +36 -0
  371. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/__init__.py +76 -0
  372. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/android_probe.py +552 -0
  373. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/base.py +147 -0
  374. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/codebase_memory_probe.py +647 -0
  375. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/desktop_probe.py +342 -0
  376. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/differential_probe.py +434 -0
  377. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/efficiency_probe.py +232 -0
  378. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ios_binary_probe.py +472 -0
  379. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/memory_probe.py +392 -0
  380. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/miniprogram_probe.py +385 -0
  381. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/mobile_probe.py +466 -0
  382. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/native_probe.py +302 -0
  383. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/openwiki_probe.py +263 -0
  384. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/pattern_probe.py +453 -0
  385. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/platform_probe.py +424 -0
  386. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/probe_registry.py +1770 -0
  387. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_fixture_corpus.py +340 -0
  388. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_probe.py +1510 -0
  389. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_rules.py +1481 -0
  390. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sca_scanner.py +779 -0
  391. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_accessibility.py +149 -0
  392. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_audit.py +513 -0
  393. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_contract.py +273 -0
  394. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_evidence.py +212 -0
  395. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_measurements.py +314 -0
  396. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_repair.py +250 -0
  397. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_review.py +133 -0
  398. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_storybook.py +107 -0
  399. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_tokens.py +185 -0
  400. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_visual_diff.py +131 -0
  401. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/web_probe.py +714 -0
  402. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/INTERFACE.md +62 -0
  403. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/README.md +53 -0
  404. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/SPEC.md +28 -0
  405. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/__init__.py +201 -0
  406. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/arbitrator.py +316 -0
  407. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/constants.py +247 -0
  408. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/detector.py +399 -0
  409. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/extractors.py +836 -0
  410. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/fingerprint.py +116 -0
  411. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/storage.py +258 -0
  412. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/strategy.py +301 -0
  413. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/README.md +35 -0
  414. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/codex_dialog_dispatch.md +9 -0
  415. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_en.md +42 -0
  416. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_zh.md +42 -0
  417. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/l0_router.md +47 -0
  418. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/anti_patterns.md +16 -0
  419. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/concurrency_rules.md +14 -0
  420. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/memory_leak_rules.md +13 -0
  421. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/prompt_injection_defense.md +13 -0
  422. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_explore.md +31 -0
  423. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_gate.md +43 -0
  424. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_mutate.md +42 -0
  425. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_repair.md +85 -0
  426. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/README.md +74 -0
  427. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/__init__.py +169 -0
  428. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/fix_watchlist.py +391 -0
  429. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_dynamic.py +418 -0
  430. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_repair_loop.py +462 -0
  431. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_selfcheck.py +862 -0
  432. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/minimize_repro.py +466 -0
  433. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/patch_synthesizer.py +617 -0
  434. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/regression_pack.py +379 -0
  435. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_fixer.py +910 -0
  436. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_loop.py +311 -0
  437. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_repair.py +348 -0
  438. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_rounds.py +212 -0
  439. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_scope.py +281 -0
  440. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/self_heal.py +604 -0
  441. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_generator.py +1108 -0
  442. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_quality_auditor.py +410 -0
  443. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_strategy.py +511 -0
  444. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/INTERFACE.md +59 -0
  445. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/README.md +69 -0
  446. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/SPEC.md +28 -0
  447. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/__init__.py +47 -0
  448. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/attestation.py +228 -0
  449. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/authority.py +255 -0
  450. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/finding_report.py +418 -0
  451. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/formal_report_builder.py +924 -0
  452. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/html_renderers.py +696 -0
  453. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/models.py +759 -0
  454. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/pdf_exporter.py +231 -0
  455. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/projects_assets.py +730 -0
  456. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_client.py +743 -0
  457. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_data_builder.py +388 -0
  458. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_share.py +459 -0
  459. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/sast_bridge.py +116 -0
  460. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/server.py +832 -0
  461. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/visual_report_builder.py +796 -0
  462. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web-conformance.md +168 -0
  463. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web_conformance.py +428 -0
  464. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/workbench_assets.py +484 -0
  465. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/INTERFACE.md +20 -0
  466. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/README.md +161 -0
  467. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/SPEC.md +25 -0
  468. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/__init__.py +3 -0
  469. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/code_analyzer.py +1720 -0
  470. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/codebase_memory_bridge.py +337 -0
  471. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/context_assembler.py +240 -0
  472. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/corpus_fetch.py +369 -0
  473. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/graph_ego.py +597 -0
  474. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_auto.py +662 -0
  475. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sources.py +168 -0
  476. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sync.py +1003 -0
  477. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/memory_store.py +480 -0
  478. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/query_planner.py +1020 -0
  479. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/rrf_engine.py +137 -0
  480. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_extractor.py +1209 -0
  481. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_normalizer.py +373 -0
  482. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_spec.py +357 -0
  483. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/symbol_index.py +1151 -0
  484. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/universal_code_matcher.py +622 -0
  485. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_bridge.py +476 -0
  486. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_supervisor.py +362 -0
  487. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/README.md +33 -0
  488. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/PROVENANCE.json +30 -0
  489. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/crypto.yaml +36 -0
  490. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/network.yaml +20 -0
  491. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/resilience.yaml +47 -0
  492. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/storage.yaml +48 -0
  493. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/LICENSE +173 -0
  494. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/PROVENANCE.json +270 -0
  495. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  496. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  497. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  498. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  499. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  500. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  501. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  502. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  503. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  504. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  505. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  506. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  507. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  508. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  509. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  510. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  511. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  512. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  513. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  514. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  515. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  516. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  517. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  518. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  519. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  520. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  521. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  522. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  523. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  524. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  525. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  526. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  527. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  528. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  529. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  530. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  531. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  532. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  533. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  534. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  535. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  536. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  537. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  538. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  539. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  540. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  541. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  542. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  543. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  544. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  545. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/PROVENANCE.json +26 -0
  546. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/network.yaml +37 -0
  547. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/platform.yaml +36 -0
  548. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/storage.yaml +48 -0
  549. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/LICENSE +165 -0
  550. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  551. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/auth.yaml +59 -0
  552. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  553. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  554. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  555. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/logging.yaml +23 -0
  556. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/network.yaml +55 -0
  557. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  558. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  559. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/storage.yaml +29 -0
  560. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/webview.yaml +32 -0
  561. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/README.md +198 -0
  562. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/__init__.py +3 -0
  563. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/bugx_logging.py +1464 -0
  564. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/daemon_runner.py +623 -0
  565. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/fixture_solidify.py +444 -0
  566. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/global_telemetry.py +549 -0
  567. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/incident_eval.py +148 -0
  568. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction.py +605 -0
  569. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction_store.py +435 -0
  570. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interactive_menu.py +95 -0
  571. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/log_analytics.py +922 -0
  572. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/mining_quality_framework.py +1387 -0
  573. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/model_runner.py +732 -0
  574. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/platform_adapter.py +579 -0
  575. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/prep_validate.py +478 -0
  576. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_graph.py +827 -0
  577. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_init.py +481 -0
  578. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_profile.py +224 -0
  579. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_settings.py +964 -0
  580. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/provider_window.py +97 -0
  581. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/resume_ticket.py +115 -0
  582. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/scenario_eval.py +856 -0
  583. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/seed_drill.py +549 -0
  584. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/self_audit.py +550 -0
  585. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/session_profile.py +205 -0
  586. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/setup_ui_env.py +229 -0
  587. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/startup_environment.py +859 -0
  588. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/sync_store.py +1421 -0
  589. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/tool_install_targets.py +18 -0
  590. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/README.md +35 -0
  591. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/agent-graph.schema.json +368 -0
  592. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/attack-graph.schema.json +88 -0
  593. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/evidence-bundle.schema.json +33 -0
  594. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/skill-pack.schema.json +230 -0
  595. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/worker-checkpoint.schema.json +119 -0
  596. bugx_cli-0.1.1.data/data/share/bugx-agent/core/secure_atomic.py +289 -0
  597. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/README.md +55 -0
  598. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/c.txt +29 -0
  599. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/cpp.txt +32 -0
  600. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/css.txt +70 -0
  601. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/go.txt +46 -0
  602. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/java.txt +30 -0
  603. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/javascript.txt +55 -0
  604. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/kotlin.txt +28 -0
  605. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/python.txt +71 -0
  606. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/rust.txt +53 -0
  607. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/swift.txt +29 -0
  608. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/typescript.txt +29 -0
  609. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/README.md +53 -0
  610. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/__init__.py +189 -0
  611. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_docs_mcp_server.py +418 -0
  612. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_mcp_server.py +1161 -0
  613. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_runtime.py +968 -0
  614. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_session_proof.py +605 -0
  615. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mobile_ui_inspector.py +405 -0
  616. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_pack.py +1214 -0
  617. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_synthesizer.py +1153 -0
  618. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/tools_kb.py +313 -0
  619. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/INTERFACE.md +121 -0
  620. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/README.md +209 -0
  621. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/SPEC.md +25 -0
  622. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/__init__.py +175 -0
  623. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/audit_supervisor.py +1015 -0
  624. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/budget_governor.py +1254 -0
  625. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_handler.py +368 -0
  626. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_pipeline.py +1564 -0
  627. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_sync.py +653 -0
  628. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_events.py +74 -0
  629. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_sync.py +590 -0
  630. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/cli.py +812 -0
  631. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/context_sync.py +55 -0
  632. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/coverage_sync.py +115 -0
  633. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_commit.py +470 -0
  634. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_sync.py +688 -0
  635. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_workflow.py +676 -0
  636. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_policy.py +224 -0
  637. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_sync.py +185 -0
  638. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/graph_sync.py +669 -0
  639. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lease_manager.py +788 -0
  640. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lifecycle_blocks.py +129 -0
  641. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/next_round_sync.py +126 -0
  642. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/observability.py +140 -0
  643. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/recovery_sync.py +165 -0
  644. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/rejection_remedies.py +355 -0
  645. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/round_governor.py +306 -0
  646. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/serial_authorization.py +544 -0
  647. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/start_sync.py +87 -0
  648. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/state_store.py +249 -0
  649. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_host.py +511 -0
  650. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_models.py +1143 -0
  651. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/systemic_failure.py +104 -0
  652. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/task_scheduler.py +1640 -0
  653. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_checkpoint.py +230 -0
  654. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_execution.py +265 -0
  655. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_handoff.py +192 -0
  656. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_lifecycle.py +396 -0
  657. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_runtime.py +1005 -0
  658. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_sync.py +89 -0
  659. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/README.md +36 -0
  660. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/__init__.py +0 -0
  661. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/exceptions.py +52 -0
  662. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/graph_models.py +357 -0
  663. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/path_containment.py +151 -0
  664. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/target_fingerprint.py +310 -0
  665. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/worker_claim.py +411 -0
  666. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/INTERFACE.md +50 -0
  667. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/README.md +57 -0
  668. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/SPEC.md +26 -0
  669. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/__init__.py +11 -0
  670. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/__init__.py +27 -0
  671. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/base.py +87 -0
  672. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/bugx.py +102 -0
  673. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/claude.py +222 -0
  674. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/cline.py +407 -0
  675. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/codex.py +260 -0
  676. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/dsh.py +177 -0
  677. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/opencode.py +218 -0
  678. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/pi.py +272 -0
  679. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/registry.py +100 -0
  680. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/zcode.py +312 -0
  681. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/api_routes_post.py +668 -0
  682. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/dispatcher.py +1376 -0
  683. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/docs_session_service.py +473 -0
  684. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/handler.py +674 -0
  685. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/ide_cloud_service.py +526 -0
  686. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/mcp_inspector.py +1747 -0
  687. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/00-base.css +1060 -0
  688. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/01-monitoring.css +802 -0
  689. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/02-header-actions.css +321 -0
  690. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/03-trigger-popover.css +697 -0
  691. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/04-composer.css +628 -0
  692. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/05-skills-center.css +878 -0
  693. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/06-mcp-center.css +623 -0
  694. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/07-skill-detail.css +265 -0
  695. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/08-files-management.css +167 -0
  696. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/09-files-center.css +386 -0
  697. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/10-icons.css +105 -0
  698. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/11-project-options.css +185 -0
  699. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/12-profile-tab.css +383 -0
  700. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  701. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  702. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  703. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  704. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  705. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  706. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  707. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  708. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  709. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  710. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  711. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  712. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  713. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  714. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  715. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  716. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  717. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  718. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  719. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  720. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  721. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  722. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  723. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  724. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  725. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  726. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/design-tokens.css +113 -0
  727. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/favicon.png +0 -0
  728. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/icon-192.png +0 -0
  729. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/index.html +55 -0
  730. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/manifest.webmanifest +19 -0
  731. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/project-settings.js +9602 -0
  732. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/sw.js +8 -0
  733. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/workspace_service.py +218 -0
  734. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/agents/bugx.md +27 -0
  735. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/dsh-patch.yml +18 -0
  736. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/cordis.patch.yml +4 -0
  737. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/index.js +219 -0
  738. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/package.json +28 -0
  739. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx/SKILL.md +70 -0
  740. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx-dsh/SKILL.md +229 -0
  741. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/client.js +87 -0
  742. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/cordis.patch.yml +4 -0
  743. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/index.js +7 -0
  744. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/package.json +27 -0
  745. bugx_cli-0.1.1.data/data/share/bugx-agent/mcp-lock.json +3075 -0
  746. bugx_cli-0.1.1.data/data/share/bugx-agent/opencode.json +129 -0
  747. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/README.md +12 -0
  748. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/index.ts +299 -0
  749. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/manifest.json +11 -0
  750. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/skills/bugx/SKILL.md +69 -0
  751. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  752. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  753. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  754. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/connector-meta.json +19 -0
  755. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/icon.png +0 -0
  756. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/skills/bugx/SKILL.md +70 -0
  757. bugx_cli-0.1.1.dist-info/METADATA +335 -0
  758. bugx_cli-0.1.1.dist-info/RECORD +762 -0
  759. bugx_cli-0.1.1.dist-info/WHEEL +5 -0
  760. bugx_cli-0.1.1.dist-info/entry_points.txt +2 -0
  761. bugx_cli-0.1.1.dist-info/licenses/LICENSE +55 -0
  762. bugx_cli-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1421 @@
1
+ #!/usr/bin/env python3
2
+ """BugX Cloud Sync 本地状态存储(DOC-008 §6.1,ADR-008-02)。
3
+
4
+ 独立于运行时 Ledger 的 sync SQLite:只拥有传输、暂存与冲突状态,
5
+ Ledger 仍是知识事实源。项目 scope 写 ``<root>/.bugx/cloud-sync/state.sqlite3``;
6
+ global scope 写 ``~/.bugx/cloud-sync/state.sqlite3``。
7
+
8
+ 表:
9
+ - ``sync_scope_state`` committed cursor / snapshot / remote_version(唯一键 account+scope+project)
10
+ - ``sync_outbox`` operation 幂等(operation_id 主键)、重试、dead-letter
11
+ - ``sync_inbox_snapshot`` staged → validated → imported / rejected 快照生命周期
12
+ - ``sync_inbox_record`` 每记录 payload + hash + 校验状态
13
+ - ``sync_conflict`` 同 version 不同 hash 等冲突队列
14
+
15
+ 关键不变量(AD-008-02/05):
16
+ - committed cursor 只在快照成功导入后随 ``inbox_commit_import`` 原子提交;
17
+ - 相同 operation_id 重复 enqueue 不产生第二行、不改变已 acked 状态;
18
+ - 不可重试错误或超过最大尝试次数进入 dead-letter,绝不静默丢弃。
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import datetime as dt
24
+ import hashlib
25
+ import os
26
+ import sqlite3
27
+ import urllib.parse
28
+ from contextlib import contextmanager
29
+ from pathlib import Path
30
+ from typing import Any, Iterator
31
+
32
+ STORE_SCHEMA_VERSION = 2
33
+ OUTBOX_STATES = ("pending", "inflight", "acked", "dead_letter")
34
+ SNAPSHOT_STATES = ("staged", "validated", "imported", "rejected")
35
+ INBOX_RECORD_TYPES = (
36
+ "patterns", "incidents", "tool_experience", "consumption_events", "tombstones",
37
+ )
38
+ CONFLICT_STATES = ("open", "resolved_local", "resolved_remote", "merged")
39
+ DEFAULT_MAX_ATTEMPTS = 5
40
+ _RETRY_BASE_SECONDS = 30
41
+
42
+
43
+ class SyncStoreError(RuntimeError):
44
+ """sync store 打不开、迁移不安全或状态转换非法。"""
45
+
46
+
47
+ def _validate_scope(scope: str) -> None:
48
+ if scope not in {"global", "project"}:
49
+ raise SyncStoreError(f"非法同步 scope: {scope}")
50
+
51
+
52
+ def _validate_nonnegative_int(value: Any, field: str) -> int:
53
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
54
+ raise SyncStoreError(f"{field} 必须是非负整数")
55
+ return value
56
+
57
+
58
+ # V2 wire record_type 的新旧单复数写法在历史队列/元数据行中并存,
59
+ # 按记录身份操作(clear/resolve/prune)时必须覆盖全部别名。
60
+ _RECORD_TYPE_ALIASES = {
61
+ "pattern": ("pattern", "patterns"),
62
+ "patterns": ("pattern", "patterns"),
63
+ "incident": ("incident", "incidents"),
64
+ "incidents": ("incident", "incidents"),
65
+ "tool": ("tool", "tool_experience"),
66
+ "tool_experience": ("tool", "tool_experience"),
67
+ }
68
+
69
+
70
+ def _record_type_aliases(record_type: str) -> tuple[str, ...]:
71
+ return _RECORD_TYPE_ALIASES.get(str(record_type or ""), (str(record_type or ""),))
72
+
73
+
74
+ from core.bugx_paths import assert_no_symlink_components
75
+
76
+
77
+ def _now() -> str:
78
+ return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
79
+
80
+
81
+ def _assert_no_symlink_components(path: Path) -> None:
82
+ """拒绝让本地同步状态库跟随目录或目标文件符号链接。"""
83
+ assert_no_symlink_components(path, error_cls=SyncStoreError)
84
+
85
+
86
+ def project_store_path(root: Path) -> Path:
87
+ return Path(root).expanduser().absolute() / ".bugx" / "cloud-sync" / "state.sqlite3"
88
+
89
+
90
+ def global_store_path() -> Path:
91
+ """global scope 的 sync store 路径(默认 ~/.bugx/cloud-sync/state.sqlite3)。
92
+
93
+ BUGX_GLOBAL_KNOWLEDGE_ROOT 覆盖时跟随其父目录,便于测试隔离。
94
+ """
95
+ import os
96
+ override = os.environ.get("BUGX_GLOBAL_KNOWLEDGE_ROOT")
97
+ if override:
98
+ return Path(override).expanduser().absolute().parent / "cloud-sync" / "state.sqlite3"
99
+ return Path.home() / ".bugx" / "cloud-sync" / "state.sqlite3"
100
+
101
+
102
+ _SCHEMA = """
103
+ CREATE TABLE IF NOT EXISTS sync_store_meta(
104
+ key TEXT PRIMARY KEY, value TEXT NOT NULL);
105
+ CREATE TABLE IF NOT EXISTS sync_scope_state(
106
+ account_id TEXT NOT NULL DEFAULT '',
107
+ scope TEXT NOT NULL,
108
+ project_id TEXT NOT NULL DEFAULT '',
109
+ committed_cursor TEXT NOT NULL DEFAULT '',
110
+ committed_snapshot_id TEXT NOT NULL DEFAULT '',
111
+ remote_version INTEGER NOT NULL DEFAULT 0,
112
+ last_success_at TEXT,
113
+ last_error_code TEXT,
114
+ last_request_id TEXT,
115
+ protocol_version INTEGER NOT NULL DEFAULT 2,
116
+ PRIMARY KEY(account_id, scope, project_id));
117
+ CREATE TABLE IF NOT EXISTS sync_outbox(
118
+ operation_id TEXT PRIMARY KEY,
119
+ account_id TEXT NOT NULL DEFAULT '',
120
+ scope TEXT NOT NULL,
121
+ project_id TEXT NOT NULL DEFAULT '',
122
+ record_type TEXT NOT NULL DEFAULT 'batch',
123
+ record_id TEXT NOT NULL DEFAULT '',
124
+ local_version INTEGER NOT NULL DEFAULT 0,
125
+ base_version INTEGER NOT NULL DEFAULT 0,
126
+ payload_hash TEXT NOT NULL DEFAULT '',
127
+ state TEXT NOT NULL CHECK(state IN ('pending','inflight','acked','dead_letter')),
128
+ attempts INTEGER NOT NULL DEFAULT 0,
129
+ next_retry_at TEXT,
130
+ last_error_code TEXT,
131
+ created_at TEXT NOT NULL,
132
+ updated_at TEXT NOT NULL,
133
+ acked_at TEXT);
134
+ CREATE TABLE IF NOT EXISTS sync_inbox_snapshot(
135
+ snapshot_id TEXT PRIMARY KEY,
136
+ account_id TEXT NOT NULL DEFAULT '',
137
+ scope TEXT NOT NULL,
138
+ project_id TEXT NOT NULL DEFAULT '',
139
+ manifest_hash TEXT NOT NULL DEFAULT '',
140
+ cursor_before TEXT NOT NULL DEFAULT '',
141
+ cursor_after TEXT NOT NULL DEFAULT '',
142
+ state TEXT NOT NULL CHECK(state IN ('staged','validated','imported','rejected')),
143
+ record_count INTEGER NOT NULL DEFAULT 0,
144
+ received_at TEXT NOT NULL,
145
+ validated_at TEXT,
146
+ imported_at TEXT,
147
+ reject_code TEXT);
148
+ CREATE TABLE IF NOT EXISTS sync_inbox_record(
149
+ snapshot_id TEXT NOT NULL,
150
+ record_type TEXT NOT NULL,
151
+ record_id TEXT NOT NULL,
152
+ payload_json TEXT NOT NULL,
153
+ payload_hash TEXT NOT NULL,
154
+ remote_version INTEGER NOT NULL DEFAULT 0,
155
+ tombstone INTEGER NOT NULL DEFAULT 0,
156
+ validation_state TEXT NOT NULL DEFAULT 'staged',
157
+ reject_code TEXT,
158
+ PRIMARY KEY(snapshot_id, record_type, record_id));
159
+ CREATE TABLE IF NOT EXISTS sync_conflict(
160
+ conflict_id TEXT PRIMARY KEY,
161
+ account_id TEXT NOT NULL DEFAULT '',
162
+ scope TEXT NOT NULL,
163
+ project_id TEXT NOT NULL DEFAULT '',
164
+ record_type TEXT NOT NULL,
165
+ record_id TEXT NOT NULL,
166
+ local_version INTEGER NOT NULL DEFAULT 0,
167
+ remote_version INTEGER NOT NULL DEFAULT 0,
168
+ local_hash TEXT NOT NULL DEFAULT '',
169
+ remote_hash TEXT NOT NULL DEFAULT '',
170
+ reason TEXT NOT NULL DEFAULT '',
171
+ state TEXT NOT NULL DEFAULT 'open'
172
+ CHECK(state IN ('open','resolved_local','resolved_remote','merged')),
173
+ created_at TEXT NOT NULL,
174
+ resolved_at TEXT,
175
+ resolver_identity TEXT);
176
+ CREATE TABLE IF NOT EXISTS sync_record_state(
177
+ account_id TEXT NOT NULL DEFAULT '',
178
+ scope TEXT NOT NULL,
179
+ project_id TEXT NOT NULL DEFAULT '',
180
+ record_type TEXT NOT NULL,
181
+ record_id TEXT NOT NULL,
182
+ remote_version INTEGER NOT NULL DEFAULT 0,
183
+ remote_hash TEXT NOT NULL DEFAULT '',
184
+ remote_deleted INTEGER NOT NULL DEFAULT 0,
185
+ updated_at TEXT NOT NULL,
186
+ PRIMARY KEY(account_id, scope, project_id, record_type, record_id));
187
+ """
188
+
189
+
190
+ class SyncStore:
191
+ """sync state SQLite 封装:所有变更单事务,打开即幂等迁移。"""
192
+
193
+ def __init__(self, path: str | Path) -> None:
194
+ self.path = Path(path).expanduser().absolute()
195
+ try:
196
+ _assert_no_symlink_components(self.path)
197
+ self.path.parent.mkdir(parents=True, exist_ok=True)
198
+ _assert_no_symlink_components(self.path)
199
+ if self.path.parent.stat().st_mode & 0o777 != 0o700:
200
+ os.chmod(self.path.parent, 0o700)
201
+ except OSError as exc:
202
+ raise SyncStoreError(f"sync store 目录不可创建: {self.path}: {exc}") from exc
203
+ try:
204
+ if self.path.exists() and not self.path.is_file():
205
+ raise SyncStoreError(f"sync store 不是普通文件: {self.path}")
206
+ self._conn = sqlite3.connect(str(self.path), timeout=10)
207
+ if self.path.stat().st_mode & 0o777 != 0o600:
208
+ os.chmod(self.path, 0o600)
209
+ self._conn.row_factory = sqlite3.Row
210
+ self._conn.execute("PRAGMA foreign_keys=ON")
211
+ self._conn.execute("PRAGMA journal_mode=WAL")
212
+ self._migrate()
213
+ except sqlite3.Error as exc:
214
+ raise SyncStoreError(f"sync store 无法打开: {self.path}: {exc}") from exc
215
+
216
+ # ---- 生命周期 ----
217
+ def _migrate(self) -> None:
218
+ with self._conn:
219
+ row = self._conn.execute(
220
+ "SELECT value FROM sync_store_meta WHERE key='store_schema_version'"
221
+ ).fetchone() if self._table_exists("sync_store_meta") else None
222
+ current = int(row["value"]) if row else 0
223
+ if current > STORE_SCHEMA_VERSION:
224
+ raise SyncStoreError(
225
+ f"sync store schema 版本更新({current} > {STORE_SCHEMA_VERSION}),"
226
+ "拒绝以旧代码写入"
227
+ )
228
+ self._conn.executescript(_SCHEMA)
229
+ self._conn.execute(
230
+ "INSERT INTO sync_store_meta(key,value) VALUES('store_schema_version',?) "
231
+ "ON CONFLICT(key) DO UPDATE SET value=excluded.value",
232
+ (str(STORE_SCHEMA_VERSION),),
233
+ )
234
+
235
+ def _table_exists(self, name: str) -> bool:
236
+ return self._conn.execute(
237
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,)
238
+ ).fetchone() is not None
239
+
240
+ @contextmanager
241
+ def _tx(self) -> Iterator[sqlite3.Connection]:
242
+ """check-then-act 序列必须整体跑在一个显式 ``BEGIN IMMEDIATE`` 事务里。
243
+
244
+ 连接默认是 deferred 隔离:守卫 SELECT 不持写锁,另一个进程完全可以在
245
+ 本进程守卫与写入之间提交同键行,把"已存在检查"变成竞态窗口。
246
+ ``BEGIN IMMEDIATE`` 在第一条语句前就取得写保留,使并发写方排队而非
247
+ 穿插;与 core/lesson_ledger.py 的 ``_tx`` 同型。异常时 ROLLBACK,
248
+ 成功时 COMMIT。
249
+ """
250
+ self._conn.execute("BEGIN IMMEDIATE")
251
+ try:
252
+ yield self._conn
253
+ except BaseException:
254
+ self._conn.execute("ROLLBACK")
255
+ raise
256
+ self._conn.execute("COMMIT")
257
+
258
+ def close(self) -> None:
259
+ self._conn.close()
260
+
261
+ def __enter__(self) -> "SyncStore":
262
+ return self
263
+
264
+ def __exit__(self, *exc_info) -> None:
265
+ self.close()
266
+
267
+ @staticmethod
268
+ def record_payload_hash(record: dict[str, Any]) -> str:
269
+ canonical = json_canonical(record)
270
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
271
+
272
+ # ---- scope state / committed cursor ----
273
+ def get_scope_state(self, account_id: str, scope: str,
274
+ project_id: str = "") -> dict[str, Any] | None:
275
+ row = self._conn.execute(
276
+ "SELECT * FROM sync_scope_state WHERE account_id=? AND scope=? AND project_id=?",
277
+ (account_id, scope, project_id),
278
+ ).fetchone()
279
+ return dict(row) if row else None
280
+
281
+ @staticmethod
282
+ def inspect_scope(path: str | Path, account_id: str, scope: str,
283
+ project_id: str = "") -> dict[str, Any]:
284
+ """以只读方式查看一个 scope 的同步状态,不创建或迁移数据库。
285
+
286
+ ``cloud status`` 必须是诊断操作:不存在的 store 不能因为查看状态而被
287
+ 创建,已有 store 也不能触发 schema 写入。因此这里使用 SQLite
288
+ ``mode=ro``,并把不存在/尚未初始化与损坏明确区分。
289
+ """
290
+ if scope not in {"global", "project"}:
291
+ raise SyncStoreError(f"非法同步 scope: {scope}")
292
+ target = Path(path).expanduser().absolute()
293
+ _assert_no_symlink_components(target)
294
+ base: dict[str, Any] = {
295
+ "path": str(target), "scope": scope, "project_id": project_id,
296
+ "state": "not_initialized",
297
+ "scope_state": None,
298
+ "outbox": {state: 0 for state in OUTBOX_STATES},
299
+ "inbox": {state: 0 for state in SNAPSHOT_STATES},
300
+ "conflicts": {state: 0 for state in CONFLICT_STATES},
301
+ }
302
+ if not target.exists():
303
+ return base
304
+ if target.is_symlink() or not target.is_file():
305
+ raise SyncStoreError(f"sync store 不是安全的普通文件: {target}")
306
+ uri = "file:" + urllib.parse.quote(str(target), safe="/") + "?mode=ro"
307
+ try:
308
+ try:
309
+ conn = sqlite3.connect(uri, uri=True, timeout=10)
310
+ try:
311
+ # WAL 库在 -wal/-shm 不存在或状态过期时,mode=ro 连接
312
+ # 无法创建索引文件而报 "unable to open database file"。
313
+ # 该失败可能在 connect 时惰性出现,用一次探测查询触发。
314
+ conn.execute("SELECT 1 FROM sqlite_master LIMIT 1").fetchone()
315
+ except sqlite3.OperationalError:
316
+ conn.close()
317
+ raise
318
+ except sqlite3.OperationalError:
319
+ # 降级为普通连接 + query_only(同 lesson_ledger._conn 的
320
+ # 0.6.76 模式):连接可补建 -shm/-wal,任何数据写入仍被
321
+ # SQLite 拒绝,只读语义不变。
322
+ conn = sqlite3.connect(str(target), timeout=10)
323
+ conn.execute("PRAGMA query_only=ON")
324
+ conn.row_factory = sqlite3.Row
325
+ try:
326
+ tables = {
327
+ row[0] for row in conn.execute(
328
+ "SELECT name FROM sqlite_master WHERE type='table'"
329
+ ).fetchall()
330
+ }
331
+ required = {"sync_store_meta", "sync_scope_state", "sync_outbox",
332
+ "sync_inbox_snapshot", "sync_inbox_record",
333
+ "sync_record_state", "sync_conflict"}
334
+ if not required.issubset(tables):
335
+ base["state"] = "uninitialized"
336
+ return base
337
+ row = conn.execute(
338
+ "SELECT * FROM sync_scope_state "
339
+ "WHERE account_id=? AND scope=? AND project_id=?",
340
+ (account_id, scope, project_id),
341
+ ).fetchone()
342
+ base["scope_state"] = dict(row) if row else None
343
+ for table, key in (("sync_outbox", "outbox"),
344
+ ("sync_inbox_snapshot", "inbox"),
345
+ ("sync_conflict", "conflicts")):
346
+ rows = conn.execute(
347
+ f"SELECT state, COUNT(*) AS count FROM {table} "
348
+ "WHERE account_id=? AND scope=? AND project_id=? GROUP BY state",
349
+ (account_id, scope, project_id),
350
+ ).fetchall()
351
+ for item in rows:
352
+ if item["state"] in base[key]:
353
+ base[key][item["state"]] = int(item["count"])
354
+ base["state"] = "ready"
355
+ return base
356
+ finally:
357
+ conn.close()
358
+ except sqlite3.Error as exc:
359
+ raise SyncStoreError(f"sync store 只读检查失败: {target}: {exc}") from exc
360
+
361
+ def commit_scope_sync(self, account_id: str, scope: str, project_id: str, *,
362
+ cursor: str, snapshot_id: str, remote_version: int,
363
+ request_id: str | None = None,
364
+ record_states: list[dict[str, Any]] | None = None) -> dict[str, Any]:
365
+ """committed cursor 只能伴随成功导入推进;单事务 upsert。"""
366
+ _validate_scope(scope)
367
+ if not isinstance(cursor, str) or not isinstance(snapshot_id, str):
368
+ raise SyncStoreError("cursor/snapshot_id 必须是字符串")
369
+ remote_version = _validate_nonnegative_int(remote_version, "remote_version")
370
+ now = _now()
371
+ with self._tx():
372
+ current = self._conn.execute(
373
+ "SELECT * FROM sync_scope_state WHERE account_id=? AND scope=? AND project_id=?",
374
+ (account_id, scope, project_id),
375
+ ).fetchone()
376
+ if current and remote_version < int(current["remote_version"] or 0) \
377
+ and (str(current["committed_cursor"] or "") != cursor
378
+ or str(current["committed_snapshot_id"] or "") != snapshot_id):
379
+ raise SyncStoreError(
380
+ "remote_version 下降且 cursor/snapshot 不同,拒绝回退同步状态"
381
+ )
382
+ if current and (str(current["committed_snapshot_id"] or "")
383
+ or str(current["committed_cursor"] or "")) \
384
+ and (str(current["committed_snapshot_id"] or "") != snapshot_id
385
+ or str(current["committed_cursor"] or "") != cursor):
386
+ raise SyncStoreError(
387
+ "已有不同的 committed snapshot/cursor,必须通过 inbox 暂存并校验后推进"
388
+ )
389
+ self._conn.execute(
390
+ "INSERT INTO sync_scope_state(account_id,scope,project_id,committed_cursor,"
391
+ "committed_snapshot_id,remote_version,last_success_at,last_request_id,"
392
+ "protocol_version) VALUES(?,?,?,?,?,?,?,?,2) "
393
+ "ON CONFLICT(account_id,scope,project_id) DO UPDATE SET "
394
+ "committed_cursor=excluded.committed_cursor,"
395
+ "committed_snapshot_id=excluded.committed_snapshot_id,"
396
+ "remote_version=MAX(sync_scope_state.remote_version,excluded.remote_version),"
397
+ "last_success_at=excluded.last_success_at,"
398
+ "last_request_id=excluded.last_request_id,"
399
+ "last_error_code=NULL",
400
+ (account_id, scope, project_id, cursor, snapshot_id,
401
+ remote_version, now, request_id),
402
+ )
403
+ self._upsert_record_states_tx(
404
+ account_id, scope, project_id, record_states or [], now,
405
+ )
406
+ return self.get_scope_state(account_id, scope, project_id) or {}
407
+
408
+ def adopt_import_snapshot(self, account_id: str, scope: str, project_id: str,
409
+ *, snapshot_id: str, remote_version: int) -> dict[str, Any]:
410
+ """Adopt an explicit local-authoritative import without inventing a cursor."""
411
+ _validate_scope(scope)
412
+ if not isinstance(snapshot_id, str) or not snapshot_id:
413
+ raise SyncStoreError("snapshot_id 必须是非空字符串")
414
+ remote_version = _validate_nonnegative_int(remote_version, "remote_version")
415
+ now = _now()
416
+ with self._tx():
417
+ current = self._conn.execute(
418
+ "SELECT remote_version FROM sync_scope_state "
419
+ "WHERE account_id=? AND scope=? AND project_id=?",
420
+ (account_id, scope, project_id),
421
+ ).fetchone()
422
+ if current and remote_version < int(current["remote_version"] or 0):
423
+ raise SyncStoreError("导入 snapshot 的 remote_version 不能回退")
424
+ self._conn.execute(
425
+ "INSERT INTO sync_scope_state(account_id,scope,project_id,"
426
+ "committed_cursor,committed_snapshot_id,remote_version,last_success_at,"
427
+ "protocol_version) VALUES(?,?,?,?,?,?,?,2) "
428
+ "ON CONFLICT(account_id,scope,project_id) DO UPDATE SET "
429
+ "committed_cursor='',committed_snapshot_id=excluded.committed_snapshot_id,"
430
+ "remote_version=MAX(sync_scope_state.remote_version,excluded.remote_version),"
431
+ "last_success_at=excluded.last_success_at,last_error_code=NULL",
432
+ (account_id, scope, project_id, "", snapshot_id, remote_version, now),
433
+ )
434
+ self._conn.execute(
435
+ "UPDATE sync_conflict SET state='resolved_local',resolved_at=?,"
436
+ "resolver_identity='cloud-upload-local-authoritative' "
437
+ "WHERE account_id=? AND scope=? AND project_id=? AND state='open'",
438
+ (now, account_id, scope, project_id),
439
+ )
440
+ self._conn.execute(
441
+ "UPDATE sync_outbox SET state='acked',acked_at=?,updated_at=?,"
442
+ "last_error_code=NULL WHERE account_id=? AND scope=? AND project_id=? "
443
+ "AND state IN ('pending','inflight')",
444
+ (now, now, account_id, scope, project_id),
445
+ )
446
+ self.prune_converged_conflicts(account_id, scope, project_id, resolver_identity="adopt-import-snapshot")
447
+ return self.get_scope_state(account_id, scope, project_id) or {}
448
+
449
+ def record_scope_error(self, account_id: str, scope: str, project_id: str, *,
450
+ error_code: str, request_id: str | None = None) -> None:
451
+ """只记录诊断信息,绝不触碰 committed cursor/snapshot。"""
452
+ _validate_scope(scope)
453
+ with self._conn:
454
+ self._conn.execute(
455
+ "INSERT INTO sync_scope_state(account_id,scope,project_id,"
456
+ "last_error_code,last_request_id,protocol_version) "
457
+ "VALUES(?,?,?,?,?,2) "
458
+ "ON CONFLICT(account_id,scope,project_id) DO UPDATE SET "
459
+ "last_error_code=excluded.last_error_code,"
460
+ "last_request_id=excluded.last_request_id",
461
+ (account_id, scope, project_id, error_code, request_id),
462
+ )
463
+
464
+ def reset_scope(self, account_id: str, scope: str, project_id: str = "",
465
+ *, error_code: str = "SYNC_RESYNC_REQUIRED",
466
+ request_id: str | None = None) -> None:
467
+ """Discard transport state for exactly one scope.
468
+
469
+ A server tombstone floor can make a committed cursor unrecoverable.
470
+ Reset removes staged snapshots, remote record metadata, conflicts and
471
+ all pending/acked outbox rows for this account/scope/project, then
472
+ leaves an explicit empty scope row so the next pull is a baseline.
473
+ Other accounts and scopes remain untouched.
474
+ """
475
+ _validate_scope(scope)
476
+ if not isinstance(error_code, str) or not error_code.strip():
477
+ raise SyncStoreError("error_code 必须是非空字符串")
478
+ with self._tx():
479
+ self._conn.execute(
480
+ "DELETE FROM sync_inbox_record WHERE snapshot_id IN ("
481
+ "SELECT snapshot_id FROM sync_inbox_snapshot "
482
+ "WHERE account_id=? AND scope=? AND project_id=? )",
483
+ (account_id, scope, project_id),
484
+ )
485
+ self._conn.execute(
486
+ "DELETE FROM sync_inbox_snapshot "
487
+ "WHERE account_id=? AND scope=? AND project_id=?",
488
+ (account_id, scope, project_id),
489
+ )
490
+ self._conn.execute(
491
+ "DELETE FROM sync_outbox WHERE account_id=? AND scope=? AND project_id=?",
492
+ (account_id, scope, project_id),
493
+ )
494
+ self._conn.execute(
495
+ "DELETE FROM sync_record_state WHERE account_id=? AND scope=? AND project_id=?",
496
+ (account_id, scope, project_id),
497
+ )
498
+ self._conn.execute(
499
+ "DELETE FROM sync_conflict WHERE account_id=? AND scope=? AND project_id=?",
500
+ (account_id, scope, project_id),
501
+ )
502
+ self._conn.execute(
503
+ "INSERT INTO sync_scope_state(account_id,scope,project_id,"
504
+ "committed_cursor,committed_snapshot_id,remote_version,last_success_at,"
505
+ "last_error_code,last_request_id,protocol_version) VALUES(?,?,?,?,?,?,?,?,?,2) "
506
+ "ON CONFLICT(account_id,scope,project_id) DO UPDATE SET "
507
+ "committed_cursor='',committed_snapshot_id='',remote_version=0,"
508
+ "last_success_at=NULL,last_error_code=excluded.last_error_code,"
509
+ "last_request_id=excluded.last_request_id,protocol_version=2",
510
+ (account_id, scope, project_id, "", "", 0, None,
511
+ error_code.strip(), request_id),
512
+ )
513
+
514
+ # ---- per-record remote metadata ----
515
+ def get_record_state(self, account_id: str, scope: str,
516
+ project_id: str, record_type: str,
517
+ record_id: str) -> dict[str, Any] | None:
518
+ row = self._conn.execute(
519
+ "SELECT * FROM sync_record_state "
520
+ "WHERE account_id=? AND scope=? AND project_id=? "
521
+ "AND record_type=? AND record_id=?",
522
+ (account_id, scope, project_id, record_type, record_id),
523
+ ).fetchone()
524
+ return dict(row) if row else None
525
+
526
+ def get_record_states(self, account_id: str, scope: str,
527
+ project_id: str = "") -> dict[tuple[str, str], dict[str, Any]]:
528
+ rows = self._conn.execute(
529
+ "SELECT * FROM sync_record_state "
530
+ "WHERE account_id=? AND scope=? AND project_id=?",
531
+ (account_id, scope, project_id),
532
+ ).fetchall()
533
+ return {(str(row["record_type"]), str(row["record_id"])): dict(row)
534
+ for row in rows}
535
+
536
+ def upsert_record_states(self, account_id: str, scope: str,
537
+ project_id: str,
538
+ records: list[dict[str, Any]]) -> None:
539
+ """批量记录远端版本,和 snapshot/cursor 使用同一 sync-store 事务。
540
+
541
+ 该表是传输元数据,不是知识事实源;因此只保存远端版本、内容哈希和
542
+ 删除标记,不能用它直接把本地 candidate 晋级为 active。
543
+ """
544
+ _validate_scope(scope)
545
+ if not records:
546
+ return
547
+ now = _now()
548
+ for item in records:
549
+ record_type = str(item.get("record_type") or "")
550
+ record_id = str(item.get("record_id") or "")
551
+ if not record_type or not record_id:
552
+ raise SyncStoreError("远端记录元数据缺少 record_type/record_id")
553
+ with self._conn:
554
+ self._upsert_record_states_tx(account_id, scope, project_id, records, now)
555
+
556
+ def clear_record_state(self, account_id: str, scope: str,
557
+ project_id: str, record_type: str,
558
+ record_id: str) -> int:
559
+ """resolve --side local:删除该记录的远端版本元数据。
560
+
561
+ 本地权威但**不发明版本**(与 adopt_import_snapshot 同语义):清掉
562
+ record_state 后,下一轮正常 push 以变更内容走服务器分配新版本,
563
+ 客户端绝不自增版本号。record_type 接受新旧单复数写法。
564
+ """
565
+ _validate_scope(scope)
566
+ if not record_type or not record_id:
567
+ raise SyncStoreError("清除记录元数据缺少 record_type/record_id")
568
+ deleted = 0
569
+ with self._conn:
570
+ for alias in _record_type_aliases(record_type):
571
+ deleted += self._conn.execute(
572
+ "DELETE FROM sync_record_state "
573
+ "WHERE account_id=? AND scope=? AND project_id=? "
574
+ "AND record_type=? AND record_id=?",
575
+ (account_id, scope, project_id, alias, record_id),
576
+ ).rowcount
577
+ return deleted
578
+
579
+ def _upsert_record_states_tx(self, account_id: str, scope: str,
580
+ project_id: str,
581
+ records: list[dict[str, Any]], now: str) -> None:
582
+ values = []
583
+ for item in records:
584
+ record_type = str(item.get("record_type") or "")
585
+ record_id = str(item.get("record_id") or "")
586
+ if not record_type or not record_id:
587
+ raise SyncStoreError("远端记录元数据缺少 record_type/record_id")
588
+ values.append((
589
+ account_id, scope, project_id, record_type, record_id,
590
+ int(item.get("remote_version", item.get("version", 0)) or 0),
591
+ str(item.get("remote_hash") or item.get("content_hash") or ""),
592
+ 1 if bool(item.get("remote_deleted", item.get("deleted", False))) else 0,
593
+ now,
594
+ ))
595
+ if values:
596
+ self._conn.executemany(
597
+ "INSERT INTO sync_record_state(account_id,scope,project_id,"
598
+ "record_type,record_id,remote_version,remote_hash,remote_deleted,updated_at) "
599
+ "VALUES(?,?,?,?,?,?,?,?,?) "
600
+ "ON CONFLICT(account_id,scope,project_id,record_type,record_id) DO UPDATE SET "
601
+ "remote_version=CASE WHEN excluded.remote_version >= remote_version "
602
+ "THEN excluded.remote_version ELSE remote_version END,"
603
+ "remote_hash=CASE WHEN excluded.remote_version >= remote_version "
604
+ "THEN excluded.remote_hash ELSE remote_hash END,"
605
+ "remote_deleted=CASE WHEN excluded.remote_version >= remote_version "
606
+ "THEN excluded.remote_deleted ELSE remote_deleted END,"
607
+ "updated_at=CASE WHEN excluded.remote_version >= remote_version "
608
+ "THEN excluded.updated_at ELSE updated_at END",
609
+ values,
610
+ )
611
+
612
+ # ---- outbox(幂等 operation / 重试 / dead-letter)----
613
+ def outbox_enqueue(self, *, operation_id: str, account_id: str = "",
614
+ scope: str, project_id: str = "",
615
+ payload_hash: str, base_version: int = 0,
616
+ local_version: int = 0,
617
+ record_type: str = "batch",
618
+ record_id: str = "") -> tuple[dict[str, Any], bool]:
619
+ """相同 operation_id 幂等:返回 (row, created);已存在行原样返回。"""
620
+ _validate_scope(scope)
621
+ if not operation_id or not payload_hash:
622
+ raise SyncStoreError("operation_id/payload_hash 不能为空")
623
+ local_version = _validate_nonnegative_int(local_version, "local_version")
624
+ base_version = _validate_nonnegative_int(base_version, "base_version")
625
+ now = _now()
626
+ with self._tx():
627
+ existing = self._conn.execute(
628
+ "SELECT * FROM sync_outbox WHERE operation_id=?", (operation_id,)
629
+ ).fetchone()
630
+ if existing:
631
+ identity = {
632
+ "account_id": account_id, "scope": scope,
633
+ "project_id": project_id, "record_type": record_type,
634
+ "record_id": record_id, "local_version": local_version,
635
+ # base_version is a retry fence, not operation identity:
636
+ # a deterministic replay may observe a newer remote
637
+ # version after a successful pull/rebase.
638
+ "payload_hash": payload_hash,
639
+ }
640
+ if any(existing[key] != value for key, value in identity.items()):
641
+ raise SyncStoreError(
642
+ f"operation_id 已存在但请求身份/内容不一致,拒绝复用: {operation_id}"
643
+ )
644
+ return dict(existing), False
645
+ self._conn.execute(
646
+ "INSERT INTO sync_outbox(operation_id,account_id,scope,project_id,"
647
+ "record_type,record_id,local_version,base_version,payload_hash,"
648
+ "state,created_at,updated_at) "
649
+ "VALUES(?,?,?,?,?,?,?,?,?,'pending',?,?)",
650
+ (operation_id, account_id, scope, project_id, record_type,
651
+ record_id, local_version, base_version, payload_hash,
652
+ now, now),
653
+ )
654
+ row = self._conn.execute(
655
+ "SELECT * FROM sync_outbox WHERE operation_id=?", (operation_id,)
656
+ ).fetchone()
657
+ return dict(row), True
658
+
659
+ def get_operation(self, operation_id: str) -> dict[str, Any] | None:
660
+ row = self._conn.execute(
661
+ "SELECT * FROM sync_outbox WHERE operation_id=?", (operation_id,)
662
+ ).fetchone()
663
+ return dict(row) if row else None
664
+
665
+ def active_operation_ids(self, *, account_id: str, scope: str,
666
+ project_id: str = "") -> list[str]:
667
+ """List pending/inflight operations without exposing the SQLite connection."""
668
+ _validate_scope(scope)
669
+ rows = self._conn.execute(
670
+ "SELECT operation_id FROM sync_outbox WHERE account_id=? AND scope=? "
671
+ "AND project_id=? AND state IN ('pending','inflight') ORDER BY created_at",
672
+ (account_id, scope, project_id),
673
+ ).fetchall()
674
+ return [str(row["operation_id"]) for row in rows]
675
+
676
+ def has_active_operations(self, *, account_id: str, scope: str,
677
+ project_id: str = "") -> bool:
678
+ _validate_scope(scope)
679
+ return self._conn.execute(
680
+ "SELECT 1 FROM sync_outbox WHERE account_id=? AND scope=? AND project_id=? "
681
+ "AND state IN ('pending','inflight') LIMIT 1",
682
+ (account_id, scope, project_id),
683
+ ).fetchone() is not None
684
+
685
+ def has_acked_payload(self, *, account_id: str, scope: str,
686
+ project_id: str, payload_hash: str) -> bool:
687
+ _validate_scope(scope)
688
+ return self._conn.execute(
689
+ "SELECT 1 FROM sync_outbox WHERE account_id=? AND scope=? AND project_id=? "
690
+ "AND payload_hash=? AND state='acked' LIMIT 1",
691
+ (account_id, scope, project_id, payload_hash),
692
+ ).fetchone() is not None
693
+
694
+ def due_operations(self, *, account_id: str = "", scope: str,
695
+ project_id: str = "", now: str | None = None) -> list[dict[str, Any]]:
696
+ stamp = now or _now()
697
+ rows = self._conn.execute(
698
+ "SELECT * FROM sync_outbox WHERE account_id=? AND scope=? AND project_id=? "
699
+ "AND state='pending' AND (next_retry_at IS NULL OR next_retry_at<=?) "
700
+ "ORDER BY created_at",
701
+ (account_id, scope, project_id, stamp),
702
+ ).fetchall()
703
+ return [dict(r) for r in rows]
704
+
705
+ def outbox_mark_inflight(self, operation_id: str) -> None:
706
+ with self._conn:
707
+ changed = self._conn.execute(
708
+ "UPDATE sync_outbox SET state='inflight',updated_at=? "
709
+ "WHERE operation_id=? AND state IN ('pending','inflight')",
710
+ (_now(), operation_id),
711
+ ).rowcount
712
+ if not changed:
713
+ raise SyncStoreError(f"operation {operation_id} 不能进入 inflight")
714
+
715
+ def outbox_requeue(self, operation_id: str) -> dict[str, Any]:
716
+ """显式重放 dead-letter operation,保留原记录与内容指纹。
717
+
718
+ dead-letter 表示本次尝试已停止,不表示 operation 永久失效。服务端
719
+ 升级、凭据恢复或人工修复后,下一次显式同步应能复用同一 operation_id
720
+ 做幂等重放,而不是卡在 ``不能进入 inflight``。重置本地尝试次数,
721
+ 但保留 ``last_error_code`` 作为诊断证据。
722
+ """
723
+ now = _now()
724
+ with self._conn:
725
+ row = self._conn.execute(
726
+ "SELECT state FROM sync_outbox WHERE operation_id=?",
727
+ (operation_id,),
728
+ ).fetchone()
729
+ if not row:
730
+ raise SyncStoreError(f"operation 不存在: {operation_id}")
731
+ if row["state"] != "dead_letter":
732
+ raise SyncStoreError(
733
+ f"operation {operation_id} 状态 {row['state']} 不是 dead_letter,不能重放"
734
+ )
735
+ self._conn.execute(
736
+ "UPDATE sync_outbox SET state='pending',attempts=0,next_retry_at=NULL,"
737
+ "updated_at=? WHERE operation_id=? AND state='dead_letter'",
738
+ (now, operation_id),
739
+ )
740
+ return self.get_operation(operation_id) or {}
741
+
742
+ def outbox_ack(self, operation_id: str, *, remote_version: int | None = None,
743
+ request_id: str | None = None) -> None:
744
+ if remote_version is not None:
745
+ remote_version = _validate_nonnegative_int(remote_version, "remote_version")
746
+ now = _now()
747
+ with self._conn:
748
+ row = self._conn.execute(
749
+ "SELECT state,account_id,scope,project_id FROM sync_outbox "
750
+ "WHERE operation_id=?", (operation_id,),
751
+ ).fetchone()
752
+ if not row:
753
+ raise SyncStoreError(f"operation 不存在: {operation_id}")
754
+ if row["state"] in {"dead_letter"}:
755
+ raise SyncStoreError(f"operation {operation_id} 已进入 dead_letter,不能 ack")
756
+ changed = self._conn.execute(
757
+ "UPDATE sync_outbox SET state='acked',acked_at=?,updated_at=?,"
758
+ "last_error_code=NULL "
759
+ "WHERE operation_id=? AND state IN ('pending','inflight','acked')",
760
+ (now, now, operation_id),
761
+ ).rowcount
762
+ if not changed:
763
+ raise SyncStoreError(f"operation {operation_id} 不能 ack")
764
+ # 注意:outbox_ack 刻意不写 sync_scope_state.remote_version。
765
+ # outbox_ack 也被 200-partial(服务端已提交但存在冲突)路径调用,
766
+ # 若在此推进 scope 版本,pull 回退守卫会拒绝更低的权威快照、
767
+ # rebase 永不发生,而 operation_id 幂等又会永久抑制重发——
768
+ # 真分歧的本地知识将静默欠提交(Round 7 红队 BLOCK 条款)。
769
+ # clean-200 的版本回写必须走 advance_remote_version 窄方法。
770
+ if request_id is not None:
771
+ self._conn.execute(
772
+ "UPDATE sync_scope_state SET last_request_id=? "
773
+ "WHERE account_id=? AND scope=? AND project_id=?",
774
+ (request_id, row["account_id"], row["scope"], row["project_id"]),
775
+ )
776
+
777
+ def advance_remote_version(self, account_id: str, scope: str,
778
+ project_id: str, remote_version: int) -> None:
779
+ """clean-200 push 专属的窄版本回写:MAX 守卫只升不降。
780
+
781
+ 只允许在 push 返回 200 且零冲突的路径调用;只动 remote_version,
782
+ 绝不触碰 committed_cursor/committed_snapshot_id——否则 pull 侧的
783
+ 版本回退守卫与幂等重放豁免会失真(Round 7 红队 BLOCK 约束)。
784
+ """
785
+ _validate_scope(scope)
786
+ remote_version = _validate_nonnegative_int(remote_version, "remote_version")
787
+ with self._conn:
788
+ self._conn.execute(
789
+ "INSERT INTO sync_scope_state(account_id,scope,project_id,"
790
+ "remote_version,protocol_version) VALUES(?,?,?,?,2) "
791
+ "ON CONFLICT(account_id,scope,project_id) DO UPDATE SET "
792
+ "remote_version=MAX(sync_scope_state.remote_version,excluded.remote_version)",
793
+ (account_id, scope, project_id, remote_version),
794
+ )
795
+
796
+ def recover_stale_inflight(self, *, max_age_seconds: int = 900,
797
+ error_code: str = "SYNC_WORKER_INTERRUPTED") -> int:
798
+ """将被杀死或断网遗留的 inflight 操作恢复为 pending。"""
799
+ if not isinstance(max_age_seconds, int) or isinstance(max_age_seconds, bool) \
800
+ or max_age_seconds < 1:
801
+ raise SyncStoreError("max_age_seconds 必须是正整数")
802
+ cutoff = (dt.datetime.now(dt.timezone.utc)
803
+ - dt.timedelta(seconds=max_age_seconds)
804
+ ).isoformat(timespec="seconds")
805
+ now = _now()
806
+ with self._conn:
807
+ return self._conn.execute(
808
+ "UPDATE sync_outbox SET state='pending',next_retry_at=?,"
809
+ "last_error_code=?,updated_at=? "
810
+ "WHERE state='inflight' AND updated_at<?",
811
+ (now, error_code, now, cutoff),
812
+ ).rowcount
813
+
814
+ def outbox_fail(self, operation_id: str, error_code: str, *,
815
+ retryable: bool = True, retry_after_seconds: int | None = None,
816
+ max_attempts: int | None = DEFAULT_MAX_ATTEMPTS) -> dict[str, Any]:
817
+ """可重试错误按退避排队;网络故障可保持 pending 等待恢复。"""
818
+ now = _now()
819
+ with self._conn:
820
+ row = self._conn.execute(
821
+ "SELECT * FROM sync_outbox WHERE operation_id=?", (operation_id,)
822
+ ).fetchone()
823
+ if not row:
824
+ raise SyncStoreError(f"operation 不存在: {operation_id}")
825
+ if row["state"] not in {"pending", "inflight"}:
826
+ raise SyncStoreError(
827
+ f"operation {operation_id} 状态 {row['state']} 不能重试或进入 dead_letter"
828
+ )
829
+ if max_attempts is not None and (
830
+ not isinstance(max_attempts, int) or isinstance(max_attempts, bool)
831
+ or max_attempts < 1
832
+ ):
833
+ raise SyncStoreError("max_attempts 必须是正整数")
834
+ attempts = int(row["attempts"]) + 1
835
+ # ponytail: network retries stay pending with capped backoff; a
836
+ # durable daemon is unnecessary because startup/boundary triggers
837
+ # already provide the next recovery opportunity.
838
+ dead = (not retryable) or (
839
+ max_attempts is not None and attempts >= max_attempts
840
+ )
841
+ next_retry = None
842
+ if not dead:
843
+ delay = retry_after_seconds if retry_after_seconds is not None \
844
+ else _RETRY_BASE_SECONDS * (2 ** (attempts - 1))
845
+ next_retry = (dt.datetime.now(dt.timezone.utc)
846
+ + dt.timedelta(seconds=min(delay, 3600))
847
+ ).isoformat(timespec="seconds")
848
+ self._conn.execute(
849
+ "UPDATE sync_outbox SET attempts=?,state=?,next_retry_at=?,"
850
+ "last_error_code=?,updated_at=? WHERE operation_id=?",
851
+ (attempts, "dead_letter" if dead else "pending",
852
+ next_retry, error_code, now, operation_id),
853
+ )
854
+ return self.get_operation(operation_id) or {}
855
+
856
+ def list_dead_letters(self, *, older_than_days: int = 0) -> list[dict[str, Any]]:
857
+ """列出 outbox 中的 dead_letter 行(死信治理用,按 created_at 排序)。
858
+
859
+ ``older_than_days`` 为 0 时返回全部死信;大于 0 时只返回
860
+ ``created_at`` 早于该天数的滞留行(ISO UTC 字符串可直接字典序比较)。
861
+ """
862
+ if not isinstance(older_than_days, int) or isinstance(older_than_days, bool) \
863
+ or older_than_days < 0:
864
+ raise SyncStoreError("older_than_days 必须是非负整数")
865
+ query = "SELECT * FROM sync_outbox WHERE state='dead_letter'"
866
+ params: list[Any] = []
867
+ if older_than_days > 0:
868
+ cutoff = (dt.datetime.now(dt.timezone.utc)
869
+ - dt.timedelta(days=older_than_days)).isoformat(timespec="seconds")
870
+ query += " AND created_at <= ?"
871
+ params.append(cutoff)
872
+ query += " ORDER BY created_at"
873
+ return [dict(r) for r in self._conn.execute(query, params).fetchall()]
874
+
875
+ def purge_dead_letters(self, operation_ids: list[str]) -> int:
876
+ """按 operation_id 删除 dead_letter 行,返回实际删除数。
877
+
878
+ 死信清理只能由显式的治理命令在归档留档后调用;DELETE 语句限定
879
+ ``state='dead_letter'``,pending/inflight/acked 行绝不会因此丢失。
880
+ """
881
+ if not isinstance(operation_ids, list) \
882
+ or any(not isinstance(op, str) or not op for op in operation_ids):
883
+ raise SyncStoreError("operation_ids 必须是非空字符串列表")
884
+ if not operation_ids:
885
+ return 0
886
+ deleted = 0
887
+ with self._conn:
888
+ for operation_id in operation_ids:
889
+ deleted += self._conn.execute(
890
+ "DELETE FROM sync_outbox WHERE operation_id=? AND state='dead_letter'",
891
+ (operation_id,),
892
+ ).rowcount
893
+ return deleted
894
+
895
+ # ---- inbox(staged → validated → imported;rejected 保留诊断)----
896
+ def inbox_stage_snapshot(self, *, snapshot_id: str, account_id: str = "",
897
+ scope: str, project_id: str = "",
898
+ manifest_hash: str, cursor_before: str = "",
899
+ cursor_after: str = "",
900
+ records: dict[str, list[dict[str, Any]]]) -> int:
901
+ """整页/全量暂存进 inbox;同 snapshot 追加仅限 staged 态。"""
902
+ _validate_scope(scope)
903
+ if not snapshot_id or not isinstance(manifest_hash, str):
904
+ raise SyncStoreError("snapshot_id 非空且 manifest_hash 必须是字符串")
905
+ if not isinstance(records, dict):
906
+ raise SyncStoreError("inbox records 必须是对象")
907
+ unknown_types = set(records) - set(INBOX_RECORD_TYPES)
908
+ if unknown_types:
909
+ raise SyncStoreError(f"inbox 含未知 record type: {', '.join(sorted(unknown_types))}")
910
+ now = _now()
911
+ total = 0
912
+ with self._conn:
913
+ existing = self._conn.execute(
914
+ "SELECT * FROM sync_inbox_snapshot WHERE snapshot_id=?",
915
+ (snapshot_id,),
916
+ ).fetchone()
917
+ if existing and existing["state"] != "staged":
918
+ raise SyncStoreError(
919
+ f"snapshot {snapshot_id} 已处于 {existing['state']},不可改写"
920
+ )
921
+ if existing:
922
+ for field, expected in (
923
+ ("account_id", account_id), ("scope", scope),
924
+ ("project_id", project_id), ("cursor_before", cursor_before),
925
+ ):
926
+ if str(existing[field] or "") != str(expected or ""):
927
+ raise SyncStoreError(
928
+ f"snapshot {snapshot_id} {field} 不匹配,拒绝跨 scope 改写"
929
+ )
930
+ if (existing["manifest_hash"] and manifest_hash
931
+ and existing["manifest_hash"] != manifest_hash):
932
+ raise SyncStoreError(
933
+ f"snapshot {snapshot_id} manifest_hash 不匹配,拒绝覆盖"
934
+ )
935
+ if not existing["manifest_hash"] and manifest_hash:
936
+ self._conn.execute(
937
+ "UPDATE sync_inbox_snapshot SET manifest_hash=? WHERE snapshot_id=?",
938
+ (manifest_hash, snapshot_id),
939
+ )
940
+ if not existing:
941
+ self._conn.execute(
942
+ "INSERT INTO sync_inbox_snapshot(snapshot_id,account_id,scope,"
943
+ "project_id,manifest_hash,cursor_before,cursor_after,state,"
944
+ "record_count,received_at) VALUES(?,?,?,?,?,?,'','staged',0,?)",
945
+ (snapshot_id, account_id, scope, project_id, manifest_hash,
946
+ cursor_before, now),
947
+ )
948
+ for kind, items in records.items():
949
+ if not isinstance(items, list):
950
+ raise SyncStoreError(f"inbox {kind} 必须是数组")
951
+ for record in items:
952
+ if not isinstance(record, dict):
953
+ raise SyncStoreError(f"inbox 记录必须是对象: {kind}")
954
+ if kind == "tool_experience":
955
+ tool_name = str(record.get("tool_name") or "")
956
+ category = str(record.get("category") or "")
957
+ rid = f"{tool_name}/{category}" if tool_name and category else tool_name
958
+ elif kind == "consumption_events":
959
+ rid = str(record.get("event_id") or "")
960
+ else:
961
+ rid = str(record.get("incident_id") or record.get("lesson_id")
962
+ or record.get("record_id") or "")
963
+ if not rid:
964
+ raise SyncStoreError(f"{kind} 记录缺少主键字段")
965
+ version = record.get("version", record.get("record_version", 0))
966
+ try:
967
+ version = _validate_nonnegative_int(version or 0, "record version")
968
+ except (SyncStoreError, TypeError, ValueError) as exc:
969
+ raise SyncStoreError(f"{kind}/{rid} version 无效") from exc
970
+ payload_json = json_compact(record)
971
+ payload_hash = hashlib.sha256(payload_json.encode("utf-8")).hexdigest()
972
+ previous = self._conn.execute(
973
+ "SELECT payload_hash,remote_version,tombstone "
974
+ "FROM sync_inbox_record WHERE snapshot_id=? AND record_type=? "
975
+ "AND record_id=?", (snapshot_id, kind, rid),
976
+ ).fetchone()
977
+ if previous:
978
+ if (previous["payload_hash"] != payload_hash
979
+ or int(previous["remote_version"]) != version
980
+ or bool(previous["tombstone"]) != (kind == "tombstones")):
981
+ # Keep the first immutable payload. The complete
982
+ # pull still sees both copies and performs the
983
+ # version/conflict decision before import; this
984
+ # prevents INSERT OR REPLACE from hiding a conflict.
985
+ total += 1
986
+ continue
987
+ total += 1
988
+ continue
989
+ self._conn.execute(
990
+ "INSERT INTO sync_inbox_record(snapshot_id,record_type,"
991
+ "record_id,payload_json,payload_hash,remote_version,tombstone,"
992
+ "validation_state) VALUES(?,?,?,?,?,?,?,'staged')",
993
+ (snapshot_id, kind, rid, payload_json, payload_hash,
994
+ version, 1 if kind == "tombstones" else 0),
995
+ )
996
+ total += 1
997
+ count = self._conn.execute(
998
+ "SELECT COUNT(*) FROM sync_inbox_record WHERE snapshot_id=?",
999
+ (snapshot_id,),
1000
+ ).fetchone()[0]
1001
+ self._conn.execute(
1002
+ "UPDATE sync_inbox_snapshot SET record_count=?,cursor_after="
1003
+ "CASE WHEN ? <> '' THEN ? ELSE cursor_after END "
1004
+ "WHERE snapshot_id=?",
1005
+ (count, cursor_after, cursor_after, snapshot_id),
1006
+ )
1007
+ return total
1008
+
1009
+ def get_snapshot(self, snapshot_id: str) -> dict[str, Any] | None:
1010
+ row = self._conn.execute(
1011
+ "SELECT * FROM sync_inbox_snapshot WHERE snapshot_id=?", (snapshot_id,)
1012
+ ).fetchone()
1013
+ return dict(row) if row else None
1014
+
1015
+ def inbox_records(self, snapshot_id: str) -> list[dict[str, Any]]:
1016
+ rows = self._conn.execute(
1017
+ "SELECT * FROM sync_inbox_record WHERE snapshot_id=? ORDER BY record_type,record_id",
1018
+ (snapshot_id,),
1019
+ ).fetchall()
1020
+ return [dict(r) for r in rows]
1021
+
1022
+ def inbox_mark_validated(self, snapshot_id: str) -> None:
1023
+ with self._conn:
1024
+ snap = self._conn.execute(
1025
+ "SELECT state FROM sync_inbox_snapshot WHERE snapshot_id=?",
1026
+ (snapshot_id,),
1027
+ ).fetchone()
1028
+ if not snap:
1029
+ raise SyncStoreError(f"snapshot 不存在: {snapshot_id}")
1030
+ invalid = self._conn.execute(
1031
+ "SELECT record_type,record_id,validation_state FROM sync_inbox_record "
1032
+ "WHERE snapshot_id=? AND validation_state NOT IN ('staged','validated')",
1033
+ (snapshot_id,),
1034
+ ).fetchone()
1035
+ if invalid:
1036
+ raise SyncStoreError(
1037
+ f"snapshot {snapshot_id} 含未通过校验的记录 "
1038
+ f"{invalid['record_type']}/{invalid['record_id']}="
1039
+ f"{invalid['validation_state']}"
1040
+ )
1041
+ self._conn.execute(
1042
+ "UPDATE sync_inbox_record SET validation_state='validated',reject_code=NULL "
1043
+ "WHERE snapshot_id=? AND validation_state='staged'",
1044
+ (snapshot_id,),
1045
+ )
1046
+ changed = self._conn.execute(
1047
+ "UPDATE sync_inbox_snapshot SET state='validated',validated_at=? "
1048
+ "WHERE snapshot_id=? AND state IN ('staged','validated')",
1049
+ (_now(), snapshot_id),
1050
+ ).rowcount
1051
+ if not changed:
1052
+ raise SyncStoreError(f"snapshot {snapshot_id} 不能标记 validated")
1053
+
1054
+ def inbox_mark_rejected(self, snapshot_id: str, reject_code: str) -> None:
1055
+ with self._conn:
1056
+ changed = self._conn.execute(
1057
+ "UPDATE sync_inbox_snapshot SET state='rejected',reject_code=? "
1058
+ "WHERE snapshot_id=? AND state IN ('staged','validated')",
1059
+ (reject_code, snapshot_id),
1060
+ ).rowcount
1061
+ if not changed:
1062
+ raise SyncStoreError(f"snapshot {snapshot_id} 不能标记 rejected")
1063
+ self._conn.execute(
1064
+ "UPDATE sync_inbox_record SET validation_state='rejected',"
1065
+ "reject_code=COALESCE(reject_code,?) WHERE snapshot_id=?",
1066
+ (reject_code, snapshot_id),
1067
+ )
1068
+
1069
+ def inbox_commit_import(self, snapshot_id: str, *, account_id: str,
1070
+ scope: str, project_id: str, cursor: str,
1071
+ remote_version: int,
1072
+ record_states: list[dict[str, Any]] | None = None) -> dict[str, Any]:
1073
+ """单一事务:snapshot→imported 且 committed cursor 推进(原子,AD-008-02)。
1074
+
1075
+ Ledger 写入由调用方在进入本事务前完成;本方法保证「cursor 提交」与
1076
+ 「inbox imported」要么同时发生、要么都不发生。失败抛错时两者均不变。
1077
+ """
1078
+ remote_version = _validate_nonnegative_int(remote_version, "remote_version")
1079
+ now = _now()
1080
+ with self._tx():
1081
+ snap = self._conn.execute(
1082
+ "SELECT * FROM sync_inbox_snapshot WHERE snapshot_id=?",
1083
+ (snapshot_id,),
1084
+ ).fetchone()
1085
+ if not snap:
1086
+ raise SyncStoreError(f"snapshot 不存在: {snapshot_id}")
1087
+ if snap["state"] != "validated":
1088
+ raise SyncStoreError(f"snapshot {snapshot_id} 状态 {snap['state']} 不可导入")
1089
+ invalid = self._conn.execute(
1090
+ "SELECT record_type,record_id,validation_state FROM sync_inbox_record "
1091
+ "WHERE snapshot_id=? AND validation_state != 'validated'",
1092
+ (snapshot_id,),
1093
+ ).fetchone()
1094
+ if invalid:
1095
+ raise SyncStoreError(
1096
+ f"snapshot {snapshot_id} 含未校验记录 "
1097
+ f"{invalid['record_type']}/{invalid['record_id']}="
1098
+ f"{invalid['validation_state']}"
1099
+ )
1100
+ for field, expected in (
1101
+ ("account_id", account_id), ("scope", scope),
1102
+ ("project_id", project_id),
1103
+ ):
1104
+ if str(snap[field] or "") != str(expected or ""):
1105
+ raise SyncStoreError(
1106
+ f"snapshot {snapshot_id} {field} 不匹配,拒绝跨 scope 导入"
1107
+ )
1108
+ current = self._conn.execute(
1109
+ "SELECT committed_cursor FROM sync_scope_state "
1110
+ "WHERE account_id=? AND scope=? AND project_id=?",
1111
+ (account_id, scope, project_id),
1112
+ ).fetchone()
1113
+ current_cursor = str(current["committed_cursor"] if current else "")
1114
+ current_meta = self._conn.execute(
1115
+ "SELECT committed_snapshot_id,remote_version FROM sync_scope_state "
1116
+ "WHERE account_id=? AND scope=? AND project_id=?",
1117
+ (account_id, scope, project_id),
1118
+ ).fetchone()
1119
+ if current_meta and remote_version < int(current_meta["remote_version"] or 0) \
1120
+ and (current_cursor != cursor
1121
+ or str(current_meta["committed_snapshot_id"] or "") != snapshot_id):
1122
+ raise SyncStoreError(
1123
+ "remote_version 下降且 cursor/snapshot 不同,拒绝回退同步状态"
1124
+ )
1125
+ snapshot_cursor_before = str(snap["cursor_before"] or "")
1126
+ if current_cursor != snapshot_cursor_before:
1127
+ raise SyncStoreError(
1128
+ f"snapshot {snapshot_id} cursor_before={snapshot_cursor_before!r} "
1129
+ f"与当前 committed_cursor={current_cursor!r} 不一致"
1130
+ )
1131
+ snapshot_cursor_after = str(snap["cursor_after"] or "")
1132
+ if snapshot_cursor_after and cursor != snapshot_cursor_after:
1133
+ raise SyncStoreError(
1134
+ f"snapshot {snapshot_id} cursor={cursor!r} 与快照 cursor_after="
1135
+ f"{snapshot_cursor_after!r} 不一致"
1136
+ )
1137
+ self._conn.execute(
1138
+ "UPDATE sync_inbox_snapshot SET state='imported',imported_at=? "
1139
+ "WHERE snapshot_id=?",
1140
+ (now, snapshot_id),
1141
+ )
1142
+ self._conn.execute(
1143
+ "UPDATE sync_inbox_record SET validation_state='imported' "
1144
+ "WHERE snapshot_id=?",
1145
+ (snapshot_id,),
1146
+ )
1147
+ self._upsert_record_states_tx(
1148
+ account_id, scope, project_id, record_states or [], now,
1149
+ )
1150
+ self._conn.execute(
1151
+ "INSERT INTO sync_scope_state(account_id,scope,project_id,"
1152
+ "committed_cursor,committed_snapshot_id,remote_version,"
1153
+ "last_success_at,protocol_version) VALUES(?,?,?,?,?,?,?,2) "
1154
+ "ON CONFLICT(account_id,scope,project_id) DO UPDATE SET "
1155
+ "committed_cursor=excluded.committed_cursor,"
1156
+ "committed_snapshot_id=excluded.committed_snapshot_id,"
1157
+ "remote_version=MAX(sync_scope_state.remote_version,excluded.remote_version),"
1158
+ "last_success_at=excluded.last_success_at,last_error_code=NULL",
1159
+ (account_id, scope, project_id, cursor, snapshot_id,
1160
+ int(remote_version), now),
1161
+ )
1162
+ return self.get_scope_state(account_id, scope, project_id) or {}
1163
+
1164
+ # ---- conflict queue ----
1165
+ def record_conflict(self, *, account_id: str = "", scope: str,
1166
+ project_id: str = "", record_type: str, record_id: str,
1167
+ local_version: int, remote_version: int,
1168
+ local_hash: str, remote_hash: str,
1169
+ reason: str) -> tuple[str, bool]:
1170
+ """确定性 conflict_id 保证同一冲突重复上报只入队一次。"""
1171
+ _validate_scope(scope)
1172
+ local_version = _validate_nonnegative_int(local_version, "local_version")
1173
+ remote_version = _validate_nonnegative_int(remote_version, "remote_version")
1174
+ if not record_type or not record_id:
1175
+ raise SyncStoreError("冲突记录缺少 record_type/record_id")
1176
+ raw = "|".join((account_id, scope, project_id, record_type, record_id,
1177
+ str(local_version), str(remote_version), local_hash, remote_hash))
1178
+ conflict_id = "cf-" + hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
1179
+ try:
1180
+ with self._tx():
1181
+ # 同一份本地/远端内容在一次启动的 baseline pull 与 final pull
1182
+ # 中可能各被观测一次;版本号可能已由第一次观测写入 metadata,
1183
+ # 但它们仍是同一个待治理冲突,不能重复堆积。
1184
+ same_open = self._conn.execute(
1185
+ "SELECT conflict_id FROM sync_conflict WHERE account_id=? AND scope=? "
1186
+ "AND project_id=? AND record_type=? AND record_id=? "
1187
+ "AND local_hash=? AND remote_hash=? AND state='open' "
1188
+ "ORDER BY created_at LIMIT 1",
1189
+ (account_id, scope, project_id, record_type, record_id,
1190
+ local_hash, remote_hash),
1191
+ ).fetchone()
1192
+ if same_open:
1193
+ return str(same_open[0]), False
1194
+ exists = self._conn.execute(
1195
+ "SELECT 1 FROM sync_conflict WHERE conflict_id=?", (conflict_id,)
1196
+ ).fetchone()
1197
+ if exists:
1198
+ return conflict_id, False
1199
+ self._conn.execute(
1200
+ "INSERT INTO sync_conflict(conflict_id,account_id,scope,project_id,"
1201
+ "record_type,record_id,local_version,remote_version,local_hash,"
1202
+ "remote_hash,reason,state,created_at) "
1203
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,'open',?)",
1204
+ (conflict_id, account_id, scope, project_id, record_type,
1205
+ record_id, local_version, remote_version,
1206
+ local_hash, remote_hash, reason, _now()),
1207
+ )
1208
+ except sqlite3.IntegrityError:
1209
+ # 并发写方在本事务守卫 SELECT 之后插入了同一 conflict_id(确定性
1210
+ # 主键撞车):整个事务已回滚,这里退化为幂等返回,不堆积重复冲突。
1211
+ return conflict_id, False
1212
+ return conflict_id, True
1213
+
1214
+ def get_conflict(self, conflict_id: str) -> dict[str, Any] | None:
1215
+ row = self._conn.execute(
1216
+ "SELECT * FROM sync_conflict WHERE conflict_id=?", (conflict_id,),
1217
+ ).fetchone()
1218
+ return dict(row) if row else None
1219
+
1220
+ def list_conflicts(self, *, state: str = "open", scope: str | None = None,
1221
+ project_id: str | None = None) -> list[dict[str, Any]]:
1222
+ if state not in CONFLICT_STATES:
1223
+ raise SyncStoreError(f"非法冲突状态: {state}")
1224
+ if scope is not None:
1225
+ _validate_scope(scope)
1226
+ query = "SELECT * FROM sync_conflict WHERE state=?"
1227
+ params: list[Any] = [state]
1228
+ if scope is not None:
1229
+ query += " AND scope=?"
1230
+ params.append(scope)
1231
+ if project_id is not None:
1232
+ query += " AND project_id=?"
1233
+ params.append(project_id)
1234
+ query += " ORDER BY created_at"
1235
+ return [dict(r) for r in self._conn.execute(query, params).fetchall()]
1236
+
1237
+ def resolve_conflict(self, conflict_id: str, resolution: str, *,
1238
+ resolver_identity: str = "") -> None:
1239
+ if resolution not in ("resolved_local", "resolved_remote", "merged"):
1240
+ raise SyncStoreError(f"非法冲突解决状态: {resolution}")
1241
+ now = _now()
1242
+ with self._conn:
1243
+ conflict_row = self._conn.execute(
1244
+ "SELECT account_id,scope,project_id,record_type,record_id,remote_version,remote_hash "
1245
+ "FROM sync_conflict WHERE conflict_id=? AND state='open'",
1246
+ (conflict_id,),
1247
+ ).fetchone()
1248
+ if not conflict_row:
1249
+ raise SyncStoreError(f"冲突 {conflict_id} 不存在或已解决")
1250
+ changed = self._conn.execute(
1251
+ "UPDATE sync_conflict SET state=?,resolved_at=?,resolver_identity=? "
1252
+ "WHERE conflict_id=? AND state='open'",
1253
+ (resolution, now, resolver_identity, conflict_id),
1254
+ ).rowcount
1255
+ if not changed:
1256
+ raise SyncStoreError(f"冲突 {conflict_id} 不存在或已解决")
1257
+ if resolution == "resolved_remote":
1258
+ self._upsert_record_states_tx(
1259
+ conflict_row["account_id"], conflict_row["scope"], conflict_row["project_id"],
1260
+ [{
1261
+ "record_type": conflict_row["record_type"],
1262
+ "record_id": conflict_row["record_id"],
1263
+ "remote_version": conflict_row["remote_version"],
1264
+ "remote_hash": conflict_row["remote_hash"],
1265
+ }],
1266
+ now,
1267
+ )
1268
+ elif resolution == "resolved_local":
1269
+ # 本地权威但**不发明版本**:清除该记录的远端版本元数据,
1270
+ # 让下一轮正常 push 以变更内容走服务器分配新版本
1271
+ # (Round 7 审计 C:与 adopt_import_snapshot 同语义)。
1272
+ for alias in _record_type_aliases(conflict_row["record_type"]):
1273
+ self._conn.execute(
1274
+ "DELETE FROM sync_record_state "
1275
+ "WHERE account_id=? AND scope=? AND project_id=? "
1276
+ "AND record_type=? AND record_id=?",
1277
+ (conflict_row["account_id"], conflict_row["scope"],
1278
+ conflict_row["project_id"], alias, conflict_row["record_id"]),
1279
+ )
1280
+
1281
+ def resolve_remote_conflicts(self, account_id: str, scope: str,
1282
+ project_id: str,
1283
+ records: list[dict[str, Any]], *,
1284
+ resolver_identity: str = "sync") -> int:
1285
+ """关闭已被权威远端快照收敛的冲突。
1286
+
1287
+ 这里只处理调用方已经确认导入/保留的记录。版本冲突以观测到的
1288
+ ``remote_version`` 作为下界;内容冲突还必须拥有完全相同的非空
1289
+ ``remote_hash``。因此一次普通 pull 不会因为“版本变大”而误关闭
1290
+ 仍然存在的内容分歧。
1291
+
1292
+ record_type 同时接受新旧单复数写法,便于升级期间收敛历史队列。
1293
+ """
1294
+ _validate_scope(scope)
1295
+ if not records:
1296
+ return 0
1297
+ aliases = {
1298
+ "pattern": ("pattern", "patterns"),
1299
+ "patterns": ("pattern", "patterns"),
1300
+ "incident": ("incident", "incidents"),
1301
+ "incidents": ("incident", "incidents"),
1302
+ "tool": ("tool", "tool_experience"),
1303
+ "tool_experience": ("tool", "tool_experience"),
1304
+ }
1305
+ changed_total = 0
1306
+ now = _now()
1307
+ with self._conn:
1308
+ for item in records:
1309
+ record_type = str(item.get("record_type") or "")
1310
+ record_id = str(item.get("record_id") or "")
1311
+ if not record_type or not record_id:
1312
+ continue
1313
+ try:
1314
+ remote_version = _validate_nonnegative_int(
1315
+ int(item.get("remote_version") or 0), "remote_version",
1316
+ )
1317
+ except (TypeError, ValueError, SyncStoreError):
1318
+ continue
1319
+ remote_hash = str(item.get("remote_hash") or "")
1320
+ if remote_version <= 0 and not remote_hash:
1321
+ continue
1322
+ record_types = aliases.get(record_type, (record_type,))
1323
+ placeholders = ",".join("?" for _ in record_types)
1324
+ params: list[Any] = [
1325
+ now, resolver_identity, account_id, scope, project_id,
1326
+ record_id, *record_types, remote_version,
1327
+ ]
1328
+ hash_clause = ""
1329
+ if remote_hash:
1330
+ hash_clause = " OR (remote_hash <> '' AND remote_hash = ?)"
1331
+ params.append(remote_hash)
1332
+ changed_total += self._conn.execute(
1333
+ "UPDATE sync_conflict SET state='resolved_remote',"
1334
+ "resolved_at=?,resolver_identity=? "
1335
+ "WHERE account_id=? AND scope=? AND project_id=? "
1336
+ "AND record_id=? AND record_type IN (" + placeholders + ") "
1337
+ "AND state='open' AND remote_version <= ? AND ("
1338
+ "reason='stale_version'" + hash_clause + ")",
1339
+ params,
1340
+ ).rowcount
1341
+ return changed_total
1342
+
1343
+ def prune_converged_conflicts(self, account_id: str, scope: str,
1344
+ project_id: str = "", *,
1345
+ resolver_identity: str = "sync-prune") -> int:
1346
+ """自动修剪和关闭已收敛的历史冲突。
1347
+
1348
+ 比对当前 sync_record_state 中的最新状态:
1349
+ 1. 若冲突为 stale_version,且当前记录的 remote_version >= conflict.remote_version;
1350
+ 2. 或冲突的 local_hash == remote_hash(零内容分歧的版本漂移冲突);
1351
+ 3. 或当前记录的 remote_hash == conflict.local_hash(本地版本已被远端吸收);
1352
+ 自动将其标记为 resolved_remote。
1353
+ """
1354
+ _validate_scope(scope)
1355
+ now = _now()
1356
+ with self._conn:
1357
+ open_conflicts = self._conn.execute(
1358
+ "SELECT conflict_id, record_type, record_id, local_version, remote_version, "
1359
+ "local_hash, remote_hash, reason FROM sync_conflict "
1360
+ "WHERE account_id=? AND scope=? AND project_id=? AND state='open'",
1361
+ (account_id, scope, project_id),
1362
+ ).fetchall()
1363
+ if not open_conflicts:
1364
+ return 0
1365
+
1366
+ states = self.get_record_states(account_id, scope, project_id)
1367
+ pruned = 0
1368
+ aliases = {
1369
+ "pattern": ("pattern", "patterns"),
1370
+ "patterns": ("pattern", "patterns"),
1371
+ "incident": ("incident", "incidents"),
1372
+ "incidents": ("incident", "incidents"),
1373
+ "tool": ("tool", "tool_experience"),
1374
+ "tool_experience": ("tool", "tool_experience"),
1375
+ }
1376
+ for conf in open_conflicts:
1377
+ cid = conf["conflict_id"]
1378
+ rtype = conf["record_type"]
1379
+ rid = conf["record_id"]
1380
+ c_lhash = conf["local_hash"] or ""
1381
+ c_rhash = conf["remote_hash"] or ""
1382
+ c_rver = int(conf["remote_version"] or 0)
1383
+ reason = conf["reason"] or ""
1384
+
1385
+ if c_lhash and c_rhash and c_lhash == c_rhash:
1386
+ self._conn.execute(
1387
+ "UPDATE sync_conflict SET state='resolved_remote', resolved_at=?, resolver_identity=? "
1388
+ "WHERE conflict_id=? AND state='open'",
1389
+ (now, resolver_identity, cid),
1390
+ )
1391
+ pruned += 1
1392
+ continue
1393
+
1394
+ curr_state = None
1395
+ for alias in aliases.get(rtype, (rtype,)):
1396
+ if (alias, rid) in states:
1397
+ curr_state = states[(alias, rid)]
1398
+ break
1399
+ if curr_state:
1400
+ curr_rver = int(curr_state.get("remote_version") or 0)
1401
+ curr_rhash = curr_state.get("remote_hash") or ""
1402
+ if (reason == "stale_version" and curr_rver >= c_rver) or (c_lhash and curr_rhash == c_lhash):
1403
+ self._conn.execute(
1404
+ "UPDATE sync_conflict SET state='resolved_remote', resolved_at=?, resolver_identity=? "
1405
+ "WHERE conflict_id=? AND state='open'",
1406
+ (now, resolver_identity, cid),
1407
+ )
1408
+ pruned += 1
1409
+ return pruned
1410
+
1411
+
1412
+
1413
+ # ---- 小工具(避免循环依赖 cloud_schema)----
1414
+ def json_canonical(value: Any) -> str:
1415
+ import json
1416
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
1417
+
1418
+
1419
+ def json_compact(value: Any) -> str:
1420
+ import json
1421
+ return json.dumps(value, ensure_ascii=False, sort_keys=False, separators=(",", ":"))