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,1192 @@
1
+ #!/usr/bin/env python3
2
+ """core/ledger/schema.py - 错题集 SQLite DDL、Schema 迁移与连接事务基础设施 (DOC-072)。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import datetime as dt
7
+ import errno
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import re
12
+ import sqlite3
13
+ import stat
14
+ import sys
15
+ import tempfile
16
+ import threading
17
+ import time
18
+ from contextlib import contextmanager
19
+ from collections.abc import Iterable
20
+ from pathlib import Path
21
+ from typing import Any, Callable, Iterator, Mapping
22
+ from urllib.parse import quote
23
+
24
+ try:
25
+ import fcntl as _fcntl
26
+ except ImportError: # pragma: no cover - Windows
27
+ _fcntl = None
28
+
29
+ try:
30
+ import msvcrt as _msvcrt
31
+ except ImportError: # pragma: no cover - POSIX
32
+ _msvcrt = None
33
+
34
+ SCHEMA_VERSION = 14
35
+ DEFAULT_LEDGER = Path(".bugx/knowledge/lesson-ledger.json")
36
+
37
+
38
+ def resolve_default_ledger(db: Path) -> Path:
39
+ """DOC-212 设计项 3:把 DEFAULT_LEDGER 相对哨兵解析为项目根锚定的绝对路径。
40
+
41
+ R9 events=0 根因:该值是 CWD 相对路径,宿主在不同子目录操作时事件写进
42
+ 不同 db(路径分离)。解析顺序:
43
+ ① 非哨兵路径(绝对路径/用户显式相对路径)原样返回——``--ledger`` 显式
44
+ 传参行为完全不变;
45
+ ② ``BUGX_PROJECT_ROOT`` env 优先(与 bugx_paths.project_root 同语义);
46
+ ③ 从 CWD 向上找最近的项目根标记(``.git`` 目录**或文件**——worktree 是
47
+ 文件 / ``pyproject.toml``),锚定标记所在目录的账本路径(允许尚不
48
+ 存在,create 落在项目根而非子目录——这正是要修的分裂);
49
+ ④ 无任何标记 → 回退 CWD 相对(旧行为)。
50
+ 注意:哨兵值相等即锚定(Path 值比较),tools_kb/pattern_probe/
51
+ fix_watchlist/regression_pack 四处同值常量与全部默认参数路径经 ``connect_ledger``
52
+ 咽喉统一覆盖。惰性调用期解析,禁止 import 期锚定。
53
+ """
54
+ db = Path(db)
55
+ if db != DEFAULT_LEDGER:
56
+ return db
57
+ env_root = os.environ.get("BUGX_PROJECT_ROOT")
58
+ if env_root:
59
+ return Path(env_root).expanduser().resolve() / ".bugx" / "knowledge" / "lesson-ledger.json"
60
+ cur = Path.cwd().resolve()
61
+ for p in (cur, *cur.parents):
62
+ if (p / ".git").exists() or (p / "pyproject.toml").is_file():
63
+ return p / ".bugx" / "knowledge" / "lesson-ledger.json"
64
+ return db
65
+
66
+
67
+ DEFAULT_LIMIT = 6
68
+ DEFAULT_TOKEN_BUDGET = 1500
69
+ DEFAULT_BYTE_BUDGET = 12000
70
+ MAX_EVENTS = 100000
71
+ MAX_TEXT_LENGTH = 8192
72
+ # DOC-SCAN-BOUNDARY:秘钥形 token 必须是**词边界独立**的——标识符指纹
73
+ # (如 "task-kwargs-typeerror-…")内嵌的 "sk-" 子串不是秘钥。加负向后顾
74
+ # 断言排除紧贴标识符字符的假阳性(实测:finding fingerprint
75
+ # "models.load_tasks:task-kwargs-typeerror-schema-drift" 误触,cycle-review
76
+ # 无法落账)。
77
+ SECRET_REGEX = re.compile(
78
+ r"(?<![A-Za-z0-9_-])(?:AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}"
79
+ r"|sk-[A-Za-z0-9_-]{20,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,})",
80
+ re.I,
81
+ )
82
+ MAX_LIST_ITEMS = 64
83
+ PATTERN_STATUSES = {"candidate", "active", "superseded", "retired", "revoked"}
84
+ LESSON_STATUSES = PATTERN_STATUSES
85
+ OUTCOMES = {"hit", "miss", "false_positive", "rejected"}
86
+ PATTERN_OUTCOMES = OUTCOMES | {"not_applicable"}
87
+ TOOL_EXPERIENCE_LEVELS = {"unproven", "candidate", "active"}
88
+ TOOL_EXPERIENCE_FIELDS = (
89
+ "tool_name", "category", "experience_level",
90
+ "use_count", "hit_count", "miss_count",
91
+ "false_positive_count", "rejected_count",
92
+ "independent_lifecycle_count",
93
+ "first_observed_at", "last_observed_at",
94
+ "tool_version", "record_version", "device_id",
95
+ "deleted", "deleted_at",
96
+ )
97
+ TOOL_EXPERIENCE_FORBIDDEN_KEYS = frozenset({
98
+ "run_id", "lifecycle_id", "lifecycle_ids", "finding", "findings",
99
+ "command", "arguments", "file_path", "paths", "user_input",
100
+ "signature", "summary", "context", "snippet",
101
+ })
102
+ TOOL_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/+-]{0,127}$")
103
+ MAX_TOOLS_PER_FEEDBACK = 8
104
+ TOOL_LOOKUP_LIMIT = 4
105
+ TOOL_LOOKUP_TOKEN_BUDGET = 800
106
+ TOOL_LOOKUP_BYTE_BUDGET = 6000
107
+ AUDITED_TABLES = (
108
+ "patterns", "probes", "aliases", "sources", "occurrences", "reviews",
109
+ "review_patterns", "review_findings", "feedback", "incidents",
110
+ "tool_usage", "evidence_receipts", "consumption_events",
111
+ "tool_experience", "sync_import_receipts",
112
+ )
113
+ FTS_COLUMNS = ("pattern_id", "category", "title", "root_cause", "reflection", "probes", "aliases")
114
+ ID_REGEX = re.compile(r"^L-[0-9a-f]{12}$")
115
+ INCIDENT_ID_REGEX = re.compile(r"^I-[0-9a-f]{12}$")
116
+ FP_REGEX = re.compile(r"^(?:sha256:)?[A-Za-z0-9_.:/-]{8,256}$")
117
+ INCIDENT_STATUSES = {"candidate", "active", "retired", "revoked"}
118
+ CARD_FIELDS = (
119
+ "severity", "language", "cwe_id", "error_signature",
120
+ "before_code", "after_code", "fix_summary", "repro_oracle",
121
+ )
122
+ CARD_OPTIONAL_FIELDS = (
123
+ "playbook", "attempts_tried", "successful_solution",
124
+ "applicability", "false_positive_patterns", "oracle_hints", "tags",
125
+ "aliases", "negative_controls", "evidence_requirements",
126
+ )
127
+ ROUTING_TAG_KEYS = (
128
+ "forms", "languages", "runtimes", "frameworks", "surfaces", "targets",
129
+ "check_profiles",
130
+ )
131
+ CARD_LIMITS = {
132
+ "severity": 20, "language": 50, "cwe_id": 20, "error_signature": 500,
133
+ "before_code": 65536, "after_code": 65536,
134
+ "fix_summary": 2000, "repro_oracle": 2000,
135
+ }
136
+
137
+
138
+ SCHEMA = """
139
+ CREATE TABLE patterns(pattern_id TEXT PRIMARY KEY,category TEXT,title TEXT,root_cause TEXT,
140
+ reflection TEXT,status TEXT,superseded_by TEXT,created_at TEXT,updated_at TEXT,last_used_at TEXT,
141
+ use_count INTEGER,hit_count INTEGER,miss_count INTEGER,false_positive_count INTEGER,rejected_count INTEGER);
142
+ CREATE TABLE probes(pattern_id TEXT,kind TEXT,value TEXT,ordinal INTEGER,PRIMARY KEY(pattern_id,kind,value));
143
+ CREATE TABLE aliases(pattern_id TEXT,alias TEXT,PRIMARY KEY(pattern_id,alias));
144
+ CREATE TABLE sources(pattern_id TEXT,source_ref TEXT,PRIMARY KEY(pattern_id,source_ref));
145
+ CREATE TABLE occurrences(pattern_id TEXT,fingerprint TEXT,observed_at TEXT,PRIMARY KEY(pattern_id,fingerprint));
146
+ -- R6 复盘 S4:三张复盘表主键补 polling_id 维度。项目级账本跨 polling
147
+ -- 重用 lifecycle 编号(都是 lifecycle-000001/round=1),旧主键会让第二个
148
+ -- polling 静默覆盖第一个 polling 的复盘事实;polling_id='' 表示遗留行。
149
+ CREATE TABLE reviews(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,finding_count INTEGER,credited_count INTEGER,reason TEXT,created_at TEXT,PRIMARY KEY(polling_id,lifecycle_id,round));
150
+ CREATE TABLE review_patterns(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,pattern_id TEXT,relation TEXT,PRIMARY KEY(polling_id,lifecycle_id,round,pattern_id));
151
+ CREATE TABLE review_findings(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,fingerprint TEXT,PRIMARY KEY(polling_id,lifecycle_id,round,fingerprint));
152
+ CREATE TABLE feedback(lifecycle_id TEXT,round INTEGER,pattern_id TEXT,fingerprint TEXT,outcome TEXT,created_at TEXT,signature TEXT,PRIMARY KEY(lifecycle_id,round,pattern_id,fingerprint));
153
+ CREATE TABLE incidents(incident_id TEXT PRIMARY KEY,pattern_id TEXT,signature TEXT NOT NULL,summary TEXT NOT NULL,
154
+ context TEXT NOT NULL,before_snippet TEXT NOT NULL,after_snippet TEXT NOT NULL,diff_ref TEXT,commit_ref TEXT,
155
+ decision TEXT NOT NULL,duration_seconds REAL NOT NULL,lifecycle_id TEXT,round INTEGER,status TEXT NOT NULL,
156
+ created_at TEXT NOT NULL,updated_at TEXT NOT NULL,content_hash TEXT NOT NULL,
157
+ routing_tags TEXT NOT NULL DEFAULT '{}',finding_fingerprint TEXT);
158
+ CREATE INDEX idx_incidents_finding_fingerprint ON incidents(finding_fingerprint);
159
+ CREATE TABLE tool_usage(lifecycle_id TEXT NOT NULL,round INTEGER NOT NULL,tool_name TEXT NOT NULL,category TEXT NOT NULL,
160
+ outcome TEXT NOT NULL,finding_fingerprint TEXT NOT NULL,created_at TEXT NOT NULL,
161
+ PRIMARY KEY(lifecycle_id,round,tool_name,category,finding_fingerprint));
162
+ CREATE TABLE evidence_receipts(receipt_id TEXT PRIMARY KEY,subject_type TEXT NOT NULL,subject_id TEXT NOT NULL,
163
+ run_id TEXT NOT NULL,lifecycle_id TEXT NOT NULL,round INTEGER NOT NULL,artifact_hash TEXT NOT NULL,
164
+ created_at TEXT NOT NULL,content_hash TEXT NOT NULL);
165
+ CREATE TABLE consumption_events(event_id TEXT PRIMARY KEY,subject_type TEXT NOT NULL,subject_id TEXT NOT NULL,
166
+ event_type TEXT NOT NULL,lifecycle_id TEXT,run_id TEXT,created_at TEXT NOT NULL,content_hash TEXT NOT NULL);
167
+ CREATE TABLE events(seq INTEGER PRIMARY KEY,type TEXT,at TEXT,payload TEXT,prev_hash TEXT,hash TEXT);
168
+ CREATE TABLE meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
169
+ CREATE TABLE state_table_digests(table_name TEXT PRIMARY KEY,row_digest TEXT NOT NULL,row_count INTEGER NOT NULL,snapshot_json TEXT NOT NULL,updated_at TEXT NOT NULL);
170
+ CREATE TABLE tool_experience(tool_name TEXT NOT NULL,category TEXT NOT NULL,experience_level TEXT NOT NULL,
171
+ record_version INTEGER NOT NULL,use_count INTEGER NOT NULL,hit_count INTEGER NOT NULL,miss_count INTEGER NOT NULL,
172
+ false_positive_count INTEGER NOT NULL,rejected_count INTEGER NOT NULL,independent_lifecycle_count INTEGER NOT NULL,
173
+ first_observed_at TEXT,last_observed_at TEXT,tool_version TEXT,device_id TEXT,
174
+ deleted INTEGER NOT NULL DEFAULT 0,deleted_at TEXT,origin TEXT NOT NULL,content_hash TEXT NOT NULL,
175
+ PRIMARY KEY(tool_name,category));
176
+ CREATE TABLE sync_import_receipts(snapshot_id TEXT PRIMARY KEY,manifest_hash TEXT NOT NULL,
177
+ content_hash TEXT NOT NULL,record_count INTEGER NOT NULL,created_at TEXT NOT NULL,
178
+ committed_at TEXT NOT NULL);
179
+ CREATE TABLE project_profile(project_key TEXT PRIMARY KEY,schema_version INTEGER NOT NULL,
180
+ profile_json TEXT NOT NULL,classification_json TEXT NOT NULL,profile_hash TEXT NOT NULL,
181
+ source_fingerprint TEXT NOT NULL,revision INTEGER NOT NULL,status TEXT NOT NULL,
182
+ updated_at TEXT NOT NULL,producer_version TEXT NOT NULL);
183
+ """
184
+
185
+
186
+ class LessonLedgerError(ValueError):
187
+ pass
188
+
189
+
190
+ class ManagedConnection(sqlite3.Connection):
191
+ """sqlite3's context manager commits but does not close the connection."""
192
+
193
+ def __enter__(self):
194
+ super().__enter__()
195
+ return self
196
+
197
+ def __exit__(self, exc_type, exc_value, traceback):
198
+ try:
199
+ super().__exit__(exc_type, exc_value, traceback)
200
+ finally:
201
+ try:
202
+ self.close()
203
+ except Exception:
204
+ pass
205
+
206
+ def __del__(self) -> None:
207
+ try:
208
+ self.close()
209
+ except Exception:
210
+ pass
211
+
212
+
213
+ def now_iso() -> str:
214
+ return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
215
+
216
+
217
+ def canonical_bytes(value: Any) -> bytes:
218
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
219
+
220
+
221
+ def sanitize_text(value: Any, field: str) -> str:
222
+ if not isinstance(value, str) or not value.strip():
223
+ raise LessonLedgerError(f"{field} 必须是非空字符串")
224
+ clean = " ".join(value.split())
225
+ if len(clean) > MAX_TEXT_LENGTH:
226
+ raise LessonLedgerError(f"{field} 超过最大长度 {MAX_TEXT_LENGTH}")
227
+ if SECRET_REGEX.search(clean):
228
+ raise LessonLedgerError(f"{field} 包含疑似凭据/秘钥,已拒绝写入")
229
+ return clean
230
+
231
+
232
+ def sanitize_text_long(value: Any, field: str, max_len: int = 65536) -> str:
233
+ if not isinstance(value, str) or not value.strip():
234
+ raise LessonLedgerError(f"{field} 必须是非空字符串")
235
+ clean = " ".join(value.split())
236
+ if len(clean) > max_len:
237
+ raise LessonLedgerError(f"{field} 超过最大长度 {max_len}")
238
+ if SECRET_REGEX.search(clean):
239
+ raise LessonLedgerError(f"{field} 包含疑似凭据/秘钥,已拒绝写入")
240
+ return clean
241
+
242
+
243
+ def parse_json_list(value: Any, field: str, required: bool = True) -> list[str]:
244
+ if value is None and not required:
245
+ return []
246
+ if not isinstance(value, list) or any(not isinstance(x, str) or not x.strip() for x in value):
247
+ raise LessonLedgerError(f"{field} 必须是非空字符串数组")
248
+ if len(value) > MAX_LIST_ITEMS:
249
+ raise LessonLedgerError(f"{field} 项数超过 {MAX_LIST_ITEMS}")
250
+ result = [sanitize_text(x, field) for x in value]
251
+ if required and not result:
252
+ raise LessonLedgerError(f"{field} 不能为空")
253
+ if len(result) != len(set(result)):
254
+ raise LessonLedgerError(f"{field} 不得重复")
255
+ return result
256
+
257
+
258
+
259
+ def sanitize_text_opt(value: Any, field: str, max_len: int = 2000) -> str:
260
+ if value is None:
261
+ return ""
262
+ if not isinstance(value, str):
263
+ raise LessonLedgerError(f"{field} 必须是字符串")
264
+ clean = " ".join(value.split())
265
+ if len(clean) > max_len:
266
+ raise LessonLedgerError(f"{field} 超过最大长度 {max_len}")
267
+ if SECRET_REGEX.search(clean):
268
+ raise LessonLedgerError(f"{field} 包含疑似凭据/秘钥,已拒绝写入")
269
+ return clean
270
+
271
+
272
+ def normalize_id(value: str) -> str:
273
+ return " ".join(value.strip().lower().split())
274
+
275
+
276
+ def parse_not_after(stamp: str, ceiling: str) -> bool:
277
+ try:
278
+ ts = dt.datetime.fromisoformat(stamp.replace("Z", "+00:00"))
279
+ tc = dt.datetime.fromisoformat(ceiling.replace("Z", "+00:00"))
280
+ return ts <= tc
281
+ except Exception:
282
+ return stamp <= ceiling
283
+
284
+
285
+ def database_path(path: str | os.PathLike[str] = DEFAULT_LEDGER) -> Path:
286
+ # DOC-212:派生前先锚定——哨兵的 .sqlite3 派生值不等于 JSON 哨兵本体,
287
+ # 不在此解析则 ledger_transaction/read/migrate 等库内调用方全部绕过锚定。
288
+ p = resolve_default_ledger(Path(path))
289
+ return p.with_suffix(".sqlite3") if p.suffix == ".json" else p
290
+
291
+
292
+ def seed_path(path: str | os.PathLike[str] = DEFAULT_LEDGER) -> Path:
293
+ p = resolve_default_ledger(Path(path))
294
+ return p.with_suffix(".json") if p.suffix == ".sqlite3" else p
295
+
296
+
297
+ def is_regular_file(path: Path, label: str, required: bool = True) -> None:
298
+ if not path.exists():
299
+ if required:
300
+ raise LessonLedgerError(f"{label} 不存在: {path}")
301
+ return
302
+ if not path.is_file() or path.is_symlink():
303
+ raise LessonLedgerError(f"{label} 必须是普通文件,拒绝符号链接与目录: {path}")
304
+
305
+
306
+ def assert_no_symlink_components(path: Path) -> None:
307
+ from core.bugx_paths import assert_no_symlink_components
308
+ assert_no_symlink_components(path, error_cls=LessonLedgerError)
309
+
310
+
311
+ def connect_ledger(db: Path, create: bool = False, readonly: bool = False,
312
+ enable_wal: bool = True) -> sqlite3.Connection:
313
+ # DOC-212:单一咽喉——默认账本哨兵在打开前锚定到项目根;symlink 词法
314
+ # 检查锚定后的最终路径,安全链不变。
315
+ db = resolve_default_ledger(db)
316
+ assert_no_symlink_components(db)
317
+ if not create:
318
+ is_regular_file(db, "SQLite 运行库")
319
+ elif db.is_symlink():
320
+ raise LessonLedgerError(f"拒绝覆盖符号链接 SQLite 运行库: {db}")
321
+
322
+ def _open(query_only: bool, wal: bool) -> sqlite3.Connection:
323
+ if query_only:
324
+ uri = f"file:{quote(str(db.resolve()), safe='/')}?mode=ro"
325
+ c = sqlite3.connect(uri, uri=True, timeout=10, isolation_level=None,
326
+ factory=ManagedConnection)
327
+ else:
328
+ c = sqlite3.connect(str(db), timeout=10, isolation_level=None,
329
+ factory=ManagedConnection)
330
+ try:
331
+ c.row_factory = sqlite3.Row
332
+ c.execute("PRAGMA foreign_keys=ON")
333
+ c.execute("PRAGMA busy_timeout=10000")
334
+ if query_only:
335
+ c.execute("PRAGMA query_only=ON")
336
+ elif wal:
337
+ c.execute("PRAGMA journal_mode=WAL")
338
+ return c
339
+ except sqlite3.Error:
340
+ c.close()
341
+ raise
342
+
343
+ if readonly:
344
+ try:
345
+ return _open(query_only=True, wal=False)
346
+ except sqlite3.Error:
347
+ try:
348
+ return _open(query_only=False, wal=False)
349
+ except sqlite3.Error as exc:
350
+ raise LessonLedgerError(f"SQLite 无法打开: {exc}") from exc
351
+ if not create and enable_wal:
352
+ return _open_with_wal_mode(
353
+ db, lambda: _open(query_only=False, wal=False),
354
+ )
355
+ try:
356
+ return _open(query_only=False, wal=False)
357
+ except sqlite3.Error as exc:
358
+ raise LessonLedgerError(f"SQLite 无法打开: {exc}") from exc
359
+
360
+
361
+ _JOURNAL_MODE_THREAD_LOCK = threading.Lock()
362
+ _WAL_MODE_READY_GUARD = threading.Lock()
363
+ _WAL_MODE_READY: set[str] = set()
364
+
365
+
366
+ @contextmanager
367
+ def _journal_mode_lock(db: Path) -> Iterator[None]:
368
+ """Serialize SQLite journal-mode transitions across threads and processes."""
369
+ canonical_db = db.resolve(strict=False)
370
+ lock_path = canonical_db.with_name(canonical_db.name + ".journal-mode.lock")
371
+ assert_no_symlink_components(lock_path)
372
+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
373
+ flags |= getattr(os, "O_BINARY", 0)
374
+ try:
375
+ descriptor = os.open(lock_path, flags, 0o600)
376
+ except OSError as exc:
377
+ raise LessonLedgerError("SQLite journal-mode 锁无法安全打开") from exc
378
+
379
+ acquired = False
380
+ thread_acquired = False
381
+ try:
382
+ if not _JOURNAL_MODE_THREAD_LOCK.acquire(timeout=10.0):
383
+ raise LessonLedgerError("SQLite journal-mode 线程锁等待超过 10 秒")
384
+ thread_acquired = True
385
+ if not stat.S_ISREG(os.fstat(descriptor).st_mode):
386
+ raise LessonLedgerError("SQLite journal-mode 锁必须是普通文件")
387
+ if os.name != "nt":
388
+ os.fchmod(descriptor, 0o600)
389
+ deadline = time.monotonic() + 10.0
390
+ if _fcntl is not None:
391
+ while True:
392
+ try:
393
+ _fcntl.flock(
394
+ descriptor, _fcntl.LOCK_EX | _fcntl.LOCK_NB,
395
+ )
396
+ acquired = True
397
+ break
398
+ except BlockingIOError:
399
+ if time.monotonic() >= deadline:
400
+ raise LessonLedgerError(
401
+ "SQLite journal-mode 锁等待超过 10 秒"
402
+ )
403
+ time.sleep(0.05)
404
+ elif _msvcrt is not None: # pragma: no cover - Windows
405
+ if os.fstat(descriptor).st_size == 0:
406
+ os.write(descriptor, b"\0")
407
+ while True:
408
+ try:
409
+ os.lseek(descriptor, 0, os.SEEK_SET)
410
+ _msvcrt.locking(descriptor, _msvcrt.LK_NBLCK, 1)
411
+ acquired = True
412
+ break
413
+ except OSError as exc:
414
+ if exc.errno not in {
415
+ errno.EACCES, errno.EAGAIN, errno.EDEADLK,
416
+ getattr(errno, "EWOULDBLOCK", errno.EAGAIN),
417
+ }:
418
+ raise LessonLedgerError(
419
+ "SQLite journal-mode 锁获取失败"
420
+ ) from exc
421
+ if time.monotonic() >= deadline:
422
+ raise LessonLedgerError(
423
+ "SQLite journal-mode 锁等待超过 10 秒"
424
+ ) from exc
425
+ time.sleep(0.05)
426
+ else: # pragma: no cover - unsupported platform
427
+ raise LessonLedgerError(
428
+ "当前平台没有可用的 SQLite journal-mode 文件锁"
429
+ )
430
+ yield
431
+ finally:
432
+ try:
433
+ if acquired:
434
+ if _fcntl is not None:
435
+ _fcntl.flock(descriptor, _fcntl.LOCK_UN)
436
+ elif _msvcrt is not None: # pragma: no cover - Windows
437
+ os.lseek(descriptor, 0, os.SEEK_SET)
438
+ _msvcrt.locking(descriptor, _msvcrt.LK_UNLCK, 1)
439
+ finally:
440
+ try:
441
+ os.close(descriptor)
442
+ finally:
443
+ if thread_acquired:
444
+ _JOURNAL_MODE_THREAD_LOCK.release()
445
+
446
+
447
+ def _ensure_wal_mode(connection: sqlite3.Connection) -> bool:
448
+ """Ensure WAL while the caller holds the per-ledger lock before opening SQLite."""
449
+ row = connection.execute("PRAGMA journal_mode").fetchone()
450
+ if row is not None and str(row[0]).lower() == "wal":
451
+ return True
452
+ # PRAGMA returns the selected mode as a row; fetch it so the statement and
453
+ # any SQLite lock are finalized before this connection is returned.
454
+ row = connection.execute("PRAGMA journal_mode=WAL").fetchone()
455
+ return row is not None and str(row[0]).lower() == "wal"
456
+
457
+
458
+ def _wal_mode_cache_key(db: Path) -> str:
459
+ return str(db.resolve(strict=False))
460
+
461
+
462
+ def _open_with_wal_mode(
463
+ db: Path, opener: Callable[[], sqlite3.Connection],
464
+ ) -> sqlite3.Connection:
465
+ """Open a writable connection only after first-use WAL setup is serialized."""
466
+ key = _wal_mode_cache_key(db)
467
+ with _WAL_MODE_READY_GUARD:
468
+ if key in _WAL_MODE_READY:
469
+ return opener()
470
+ with _journal_mode_lock(db):
471
+ if key in _WAL_MODE_READY:
472
+ return opener()
473
+ connection = opener()
474
+ try:
475
+ if _ensure_wal_mode(connection):
476
+ _WAL_MODE_READY.add(key)
477
+ except BaseException:
478
+ connection.close()
479
+ raise
480
+ return connection
481
+
482
+
483
+
484
+ def read_seed(path: Path) -> tuple[dict[str, dict[str, Any]], str]:
485
+ from .patterns import normalize_pattern
486
+ assert_no_symlink_components(path)
487
+ is_regular_file(path, "JSON 种子")
488
+ try:
489
+ raw = path.read_bytes()
490
+ data = json.loads(raw)
491
+ except (OSError, json.JSONDecodeError) as exc:
492
+ raise LessonLedgerError(f"JSON 种子无法解析: {exc}") from exc
493
+ if not isinstance(data, dict) or data.get("schema_version") not in {2, 3}:
494
+ raise LessonLedgerError("JSON 种子 schema_version 不受支持")
495
+ lessons = data.get("lessons")
496
+ if not isinstance(lessons, dict) or not lessons:
497
+ raise LessonLedgerError("JSON 种子 lessons 不能为空")
498
+ result = {}
499
+ for key, value in lessons.items():
500
+ item = normalize_pattern(value)
501
+ if item["pattern_id"] != key:
502
+ raise LessonLedgerError("JSON 种子 key 与 pattern_id 不一致")
503
+ result[key] = item
504
+ return result, hashlib.sha256(raw).hexdigest()
505
+
506
+
507
+ def init_fts(c: sqlite3.Connection) -> bool:
508
+ try:
509
+ c.execute("CREATE VIRTUAL TABLE patterns_fts USING fts5(pattern_id UNINDEXED,category,title,root_cause,reflection,probes,aliases)")
510
+ return True
511
+ except sqlite3.OperationalError:
512
+ c.execute("CREATE TABLE patterns_fts(pattern_id TEXT PRIMARY KEY,category TEXT,title TEXT,root_cause TEXT,reflection TEXT,probes TEXT,aliases TEXT)")
513
+ return False
514
+
515
+
516
+ def execute_script(c: sqlite3.Connection, script: str) -> None:
517
+ for statement in script.split(";"):
518
+ text = statement.strip()
519
+ if text:
520
+ c.execute(text)
521
+
522
+
523
+ _REVIEW_TABLE_POLLING_SPECS = (
524
+ (
525
+ "reviews",
526
+ "CREATE TABLE {staged}(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,"
527
+ "finding_count INTEGER,credited_count INTEGER,reason TEXT,created_at TEXT,"
528
+ "PRIMARY KEY(polling_id,lifecycle_id,round))",
529
+ "INSERT INTO {staged}(polling_id,lifecycle_id,round,finding_count,credited_count,reason,created_at) "
530
+ "SELECT '',lifecycle_id,round,finding_count,credited_count,reason,created_at FROM {table}",
531
+ ("polling_id", "lifecycle_id", "round", "finding_count", "credited_count", "reason", "created_at"),
532
+ ),
533
+ (
534
+ "review_patterns",
535
+ "CREATE TABLE {staged}(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,"
536
+ "pattern_id TEXT,relation TEXT,PRIMARY KEY(polling_id,lifecycle_id,round,pattern_id))",
537
+ "INSERT INTO {staged}(polling_id,lifecycle_id,round,pattern_id,relation) "
538
+ "SELECT '',lifecycle_id,round,pattern_id,relation FROM {table}",
539
+ ("polling_id", "lifecycle_id", "round", "pattern_id", "relation"),
540
+ ),
541
+ (
542
+ "review_findings",
543
+ "CREATE TABLE {staged}(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,"
544
+ "fingerprint TEXT,PRIMARY KEY(polling_id,lifecycle_id,round,fingerprint))",
545
+ "INSERT INTO {staged}(polling_id,lifecycle_id,round,fingerprint) "
546
+ "SELECT '',lifecycle_id,round,fingerprint FROM {table}",
547
+ ("polling_id", "lifecycle_id", "round", "fingerprint"),
548
+ ),
549
+ )
550
+
551
+
552
+ def _rebuild_review_tables_with_polling(c: sqlite3.Connection) -> None:
553
+ """R6 复盘 S4(v12→v13):复盘三表主键补 polling_id 维度。
554
+
555
+ 项目级账本跨 polling 重用 lifecycle 编号,旧主键 (lifecycle_id, round)
556
+ 会让第二个 polling 静默覆盖第一个 polling 的复盘事实。旧表在**当前事务
557
+ 内**staged 重建(SQLite 原子 DDL + 事务回滚保证 crash-safe),遗留行
558
+ polling_id 置 ''。表不存在(极早期库)或缺 polling_id 列之外的任何
559
+ 结构差异照旧交给调用方的完整性校验兜底。
560
+ """
561
+ for table, create_sql, copy_sql, _columns in _REVIEW_TABLE_POLLING_SPECS:
562
+ exists = c.execute(
563
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)
564
+ ).fetchone()
565
+ if not exists:
566
+ continue
567
+ columns = {row[1] for row in c.execute(f"PRAGMA table_info({table})")}
568
+ if "polling_id" in columns:
569
+ continue
570
+ staged = f"{table}__polling_migrate"
571
+ c.execute(f"DROP TABLE IF EXISTS {staged}")
572
+ c.execute(create_sql.format(staged=staged))
573
+ c.execute(copy_sql.format(staged=staged, table=table))
574
+ c.execute(f"DROP TABLE {table}")
575
+ c.execute(f"ALTER TABLE {staged} RENAME TO {table}")
576
+
577
+
578
+ def ensure_schema(c: sqlite3.Connection, *, migrate: bool = False) -> None:
579
+ from .incidents import incident_content_hash
580
+ row = c.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()
581
+ if row is None:
582
+ raise LessonLedgerError("SQLite schema_version 缺失")
583
+ version = int(row[0])
584
+ if version == SCHEMA_VERSION:
585
+ return
586
+ if not migrate or version not in {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}:
587
+ raise LessonLedgerError(f"SQLite schema_version={version},请显式执行 lesson migrate")
588
+ c.execute("BEGIN IMMEDIATE")
589
+ try:
590
+ if version == 13:
591
+ columns = {row[1] for row in c.execute("PRAGMA table_info(incidents)")}
592
+ if "finding_fingerprint" not in columns:
593
+ c.execute("ALTER TABLE incidents ADD COLUMN finding_fingerprint TEXT")
594
+ c.execute(
595
+ "CREATE INDEX IF NOT EXISTS idx_incidents_finding_fingerprint "
596
+ "ON incidents(finding_fingerprint)"
597
+ )
598
+ c.execute(
599
+ "UPDATE meta SET value=? WHERE key='schema_version'",
600
+ (str(SCHEMA_VERSION),),
601
+ )
602
+ record_event(c, "schema-migrated", {"from": version, "to": SCHEMA_VERSION})
603
+ _sync_table_digests(c)
604
+ c.execute("COMMIT")
605
+ return
606
+ if version == 2:
607
+ execute_script(c, """
608
+ CREATE TABLE IF NOT EXISTS reviews(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,finding_count INTEGER,credited_count INTEGER,reason TEXT,created_at TEXT,PRIMARY KEY(polling_id,lifecycle_id,round));
609
+ CREATE TABLE IF NOT EXISTS review_patterns(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,pattern_id TEXT,relation TEXT,PRIMARY KEY(polling_id,lifecycle_id,round,pattern_id));
610
+ CREATE TABLE IF NOT EXISTS review_findings(polling_id TEXT NOT NULL DEFAULT '',lifecycle_id TEXT,round INTEGER,fingerprint TEXT,PRIMARY KEY(polling_id,lifecycle_id,round,fingerprint));
611
+ CREATE TABLE IF NOT EXISTS feedback(lifecycle_id TEXT,round INTEGER,pattern_id TEXT,fingerprint TEXT,outcome TEXT,created_at TEXT,PRIMARY KEY(lifecycle_id,round,pattern_id,fingerprint));
612
+ CREATE TABLE IF NOT EXISTS patterns_fts(pattern_id TEXT PRIMARY KEY,category TEXT,title TEXT,root_cause TEXT,reflection TEXT,probes TEXT,aliases TEXT);
613
+ """)
614
+ if version == 9:
615
+ pass
616
+ _rebuild_review_tables_with_polling(c)
617
+ execute_script(c, """
618
+ CREATE TABLE IF NOT EXISTS incidents(incident_id TEXT PRIMARY KEY,pattern_id TEXT,signature TEXT NOT NULL,summary TEXT NOT NULL,
619
+ context TEXT NOT NULL,before_snippet TEXT NOT NULL,after_snippet TEXT NOT NULL,diff_ref TEXT,commit_ref TEXT,
620
+ decision TEXT NOT NULL,duration_seconds REAL NOT NULL,lifecycle_id TEXT,round INTEGER,status TEXT NOT NULL,
621
+ created_at TEXT NOT NULL,updated_at TEXT NOT NULL,content_hash TEXT NOT NULL);
622
+ CREATE TABLE IF NOT EXISTS tool_usage(lifecycle_id TEXT NOT NULL,round INTEGER NOT NULL,tool_name TEXT NOT NULL,category TEXT NOT NULL,
623
+ outcome TEXT NOT NULL,finding_fingerprint TEXT NOT NULL,created_at TEXT NOT NULL,
624
+ PRIMARY KEY(lifecycle_id,round,tool_name,category,finding_fingerprint));
625
+ CREATE TABLE IF NOT EXISTS evidence_receipts(receipt_id TEXT PRIMARY KEY,subject_type TEXT NOT NULL,subject_id TEXT NOT NULL,
626
+ run_id TEXT NOT NULL,lifecycle_id TEXT NOT NULL,round INTEGER NOT NULL,artifact_hash TEXT NOT NULL,
627
+ created_at TEXT NOT NULL,content_hash TEXT NOT NULL);
628
+ CREATE TABLE IF NOT EXISTS consumption_events(event_id TEXT PRIMARY KEY,subject_type TEXT NOT NULL,subject_id TEXT NOT NULL,
629
+ event_type TEXT NOT NULL,lifecycle_id TEXT,run_id TEXT,created_at TEXT NOT NULL,content_hash TEXT NOT NULL);
630
+ """)
631
+ execute_script(c, """
632
+ CREATE TABLE IF NOT EXISTS tool_experience(tool_name TEXT NOT NULL,category TEXT NOT NULL,experience_level TEXT NOT NULL,
633
+ record_version INTEGER NOT NULL,use_count INTEGER NOT NULL,hit_count INTEGER NOT NULL,miss_count INTEGER NOT NULL,
634
+ false_positive_count INTEGER NOT NULL,rejected_count INTEGER NOT NULL,independent_lifecycle_count INTEGER NOT NULL,
635
+ first_observed_at TEXT,last_observed_at TEXT,tool_version TEXT,device_id TEXT,
636
+ deleted INTEGER NOT NULL DEFAULT 0,deleted_at TEXT,origin TEXT NOT NULL,content_hash TEXT NOT NULL,
637
+ PRIMARY KEY(tool_name,category));
638
+ """)
639
+ c.execute("""
640
+ CREATE TABLE IF NOT EXISTS sync_import_receipts(
641
+ snapshot_id TEXT PRIMARY KEY,
642
+ manifest_hash TEXT NOT NULL,
643
+ content_hash TEXT NOT NULL,
644
+ record_count INTEGER NOT NULL,
645
+ created_at TEXT NOT NULL,
646
+ committed_at TEXT NOT NULL
647
+ )
648
+ """)
649
+ c.execute("""
650
+ CREATE TABLE IF NOT EXISTS project_profile(
651
+ project_key TEXT PRIMARY KEY,
652
+ schema_version INTEGER NOT NULL,
653
+ profile_json TEXT NOT NULL,
654
+ classification_json TEXT NOT NULL,
655
+ profile_hash TEXT NOT NULL,
656
+ source_fingerprint TEXT NOT NULL,
657
+ revision INTEGER NOT NULL,
658
+ status TEXT NOT NULL,
659
+ updated_at TEXT NOT NULL,
660
+ producer_version TEXT NOT NULL
661
+ )
662
+ """)
663
+ c.execute("""
664
+ CREATE TABLE IF NOT EXISTS state_table_digests(
665
+ table_name TEXT PRIMARY KEY,
666
+ row_digest TEXT NOT NULL,
667
+ row_count INTEGER NOT NULL,
668
+ snapshot_json TEXT NOT NULL DEFAULT '[]',
669
+ updated_at TEXT NOT NULL
670
+ )
671
+ """)
672
+ digest_columns = {row[1] for row in c.execute("PRAGMA table_info(state_table_digests)")}
673
+ if "snapshot_json" not in digest_columns:
674
+ c.execute("ALTER TABLE state_table_digests ADD COLUMN snapshot_json TEXT NOT NULL DEFAULT '[]'")
675
+ columns = {row[1] for row in c.execute("PRAGMA table_info(feedback)")}
676
+ if "signature" not in columns:
677
+ c.execute("ALTER TABLE feedback ADD COLUMN signature TEXT")
678
+ incident_columns = {row[1] for row in c.execute("PRAGMA table_info(incidents)")}
679
+ if "routing_tags" not in incident_columns:
680
+ c.execute("ALTER TABLE incidents ADD COLUMN routing_tags TEXT NOT NULL DEFAULT '{}'")
681
+ for row in c.execute(
682
+ "SELECT incident_id,pattern_id,signature,summary,context,before_snippet,after_snippet,diff_ref,commit_ref,decision,duration_seconds,lifecycle_id,round FROM incidents"
683
+ ).fetchall():
684
+ content = {
685
+ "signature": row[2], "summary": row[3], "context": row[4],
686
+ "before_snippet": row[5], "after_snippet": row[6],
687
+ "diff_ref": row[7], "commit_ref": row[8], "decision": row[9],
688
+ "duration_seconds": row[10], "lifecycle_id": row[11],
689
+ "round": row[12], "pattern_id": row[1], "routing_tags": {},
690
+ }
691
+ c.execute(
692
+ "UPDATE incidents SET content_hash=? WHERE incident_id=?",
693
+ (incident_content_hash(content), row[0]),
694
+ )
695
+ incident_columns = {row[1] for row in c.execute("PRAGMA table_info(incidents)")}
696
+ if "finding_fingerprint" not in incident_columns:
697
+ c.execute("ALTER TABLE incidents ADD COLUMN finding_fingerprint TEXT")
698
+ c.execute(
699
+ "CREATE INDEX IF NOT EXISTS idx_incidents_finding_fingerprint "
700
+ "ON incidents(finding_fingerprint)"
701
+ )
702
+ c.execute("INSERT OR REPLACE INTO meta(key,value) VALUES('schema_version',?)", (str(SCHEMA_VERSION),))
703
+ c.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('fts5','0')")
704
+ c.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('state_hash','')")
705
+ c.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('head_hash','')")
706
+ c.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('archive_manifest','')")
707
+ c.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('archive_root_hash','')")
708
+ c.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('archive_last_seq','')")
709
+ c.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('archive_last_hash','')")
710
+ c.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('archive_dir','')")
711
+ for key in [r[0] for r in c.execute("SELECT pattern_id FROM patterns")]:
712
+ refresh_materialized_views(c, key)
713
+ record_event(c, "schema-migrated", {"from": version, "to": SCHEMA_VERSION})
714
+ _sync_table_digests(c)
715
+ c.execute("COMMIT")
716
+ except BaseException:
717
+ c.execute("ROLLBACK")
718
+ raise
719
+
720
+
721
+ def refresh_materialized_views(c: sqlite3.Connection, key: str) -> None:
722
+ row = c.execute("SELECT category,title,root_cause,reflection FROM patterns WHERE pattern_id=?", (key,)).fetchone()
723
+ if not row:
724
+ return
725
+ probes = " ".join(x[0] for x in c.execute("SELECT value FROM probes WHERE pattern_id=? AND kind!='card' ORDER BY ordinal", (key,)))
726
+ aliases = " ".join(x[0] for x in c.execute("SELECT alias FROM aliases WHERE pattern_id=?", (key,)))
727
+ c.execute("DELETE FROM patterns_fts WHERE pattern_id=?", (key,))
728
+ c.execute("INSERT INTO patterns_fts VALUES (?,?,?,?,?,?,?)", (key, row[0], row[1], row[2], row[3], probes, aliases))
729
+
730
+
731
+ def insert_pattern(c: sqlite3.Connection, p: Mapping[str, Any]) -> None:
732
+ from .patterns import CARD_FIELDS
733
+ c.execute("INSERT INTO patterns VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", tuple(p[x] for x in (
734
+ "pattern_id","category","title","root_cause","reflection","status","superseded_by",
735
+ "created_at","updated_at","last_used_at","use_count","hit_count","miss_count","false_positive_count","rejected_count")))
736
+ for kind, values in (
737
+ ("probe", p["probes"]),
738
+ ("negative_control", p["negative_controls"]),
739
+ ("evidence", p["evidence_requirements"]),
740
+ ("applicability", p["applicability"]),
741
+ ("false_positive", p["false_positive_patterns"]),
742
+ ("oracle", p["oracle_hints"]),
743
+ ("tag", p["tags"]),
744
+ ("playbook", p["playbook"]),
745
+ ("attempts_tried", p["attempts_tried"]),
746
+ ("successful_solution", p["successful_solution"]),
747
+ ):
748
+ c.executemany("INSERT INTO probes VALUES (?,?,?,?)", [(p["pattern_id"],kind,x,i) for i,x in enumerate(values)])
749
+ card = {field: p[field] for field in CARD_FIELDS}
750
+ if p.get("routing_tags"):
751
+ card["routing_tags"] = p["routing_tags"]
752
+ if any(card.values()):
753
+ c.execute("INSERT INTO probes VALUES (?,?,?,?)",
754
+ (p["pattern_id"], "card", json.dumps(card, ensure_ascii=False, sort_keys=True), 0))
755
+ c.executemany("INSERT INTO aliases VALUES (?,?)", [(p["pattern_id"],x) for x in p["aliases"]])
756
+ c.executemany("INSERT INTO sources VALUES (?,?)", [(p["pattern_id"],x) for x in p["source_refs"]])
757
+ c.executemany("INSERT INTO occurrences VALUES (?,?,?)", [(p["pattern_id"],x,p["created_at"]) for x in p["finding_fingerprints"]])
758
+ refresh_materialized_views(c, p["pattern_id"])
759
+
760
+
761
+ def initialize(path: str | os.PathLike[str] = DEFAULT_LEDGER, *, seed: str | os.PathLike[str] | None = None) -> dict[str, Any]:
762
+ from .patterns import read
763
+ from .sync_ops import sync_state_hash, validate_pattern
764
+ logical, db = Path(path), database_path(path)
765
+ assert_no_symlink_components(logical)
766
+ assert_no_symlink_components(db)
767
+ if db.exists() or db.is_symlink():
768
+ with connect_ledger(db, readonly=True) as c:
769
+ validate_pattern(c, db)
770
+ return read(logical)
771
+ patterns, seed_hash = read_seed(Path(seed) if seed else seed_path(logical))
772
+ db.parent.mkdir(parents=True, exist_ok=True)
773
+ fd, name = tempfile.mkstemp(prefix=f".{db.name}.", suffix=".tmp", dir=db.parent)
774
+ os.close(fd)
775
+ temp = Path(name)
776
+ try:
777
+ with connect_ledger(temp, True) as c:
778
+ c.executescript(SCHEMA)
779
+ fts = init_fts(c)
780
+ c.executemany("INSERT INTO meta VALUES (?,?)", [
781
+ ("schema_version", str(SCHEMA_VERSION)),
782
+ ("seed_sha256", seed_hash),
783
+ ("seed_count", str(len(patterns))),
784
+ ("head_hash", ""),
785
+ ("state_hash", ""),
786
+ ("fts5", str(int(fts))),
787
+ ("archive_manifest", ""),
788
+ ("archive_root_hash", ""),
789
+ ("archive_last_seq", ""),
790
+ ("archive_last_hash", ""),
791
+ ("archive_dir", ""),
792
+ ])
793
+ for p in patterns.values():
794
+ insert_pattern(c, p)
795
+ _sync_table_digests(c)
796
+ sync_state_hash(c)
797
+ validate_pattern(c, temp)
798
+ os.replace(temp, db)
799
+ temp = Path()
800
+ finally:
801
+ if temp and temp.is_file():
802
+ temp.unlink()
803
+ return read(logical)
804
+
805
+
806
+ def get_schema_version(db: Path) -> int | None:
807
+ try:
808
+ with connect_ledger(db, readonly=True) as c:
809
+ row = c.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()
810
+ except (LessonLedgerError, sqlite3.Error):
811
+ return None
812
+ if row is None:
813
+ return None
814
+ try:
815
+ return int(str(row[0]))
816
+ except (TypeError, ValueError):
817
+ return None
818
+
819
+
820
+ def retire_migrate_backup(backup: Path) -> Path | None:
821
+ if backup.is_symlink() or not backup.exists():
822
+ return None
823
+ done = backup.with_name(f"{backup.name}.done-{int(time.time() * 1000)}")
824
+ os.replace(backup, done)
825
+ return done
826
+
827
+
828
+ def migrate(path: str | os.PathLike[str] = DEFAULT_LEDGER) -> dict[str, Any]:
829
+ """显式迁移并先生成同目录备份;失败时原库保持不变。"""
830
+ from .patterns import read
831
+ logical, db = Path(path), database_path(path)
832
+ is_regular_file(db, "SQLite 运行库")
833
+ backup = db.with_name(f"{db.name}.pre-migrate.bak")
834
+ version = get_schema_version(db)
835
+ if version == SCHEMA_VERSION:
836
+ retire_migrate_backup(backup)
837
+ return read(logical)
838
+ if backup.is_symlink():
839
+ raise LessonLedgerError(f"迁移备份已存在,请人工处理: {backup}")
840
+ if backup.exists():
841
+ backup.replace(db)
842
+ with connect_ledger(db, readonly=True) as source, connect_ledger(backup, True) as target:
843
+ source.backup(target)
844
+ os.chmod(backup, 0o600)
845
+ try:
846
+ with connect_ledger(db) as c:
847
+ ensure_schema(c, migrate=True)
848
+ sync_state_hash(c)
849
+ validate_pattern(c, db)
850
+ except BaseException:
851
+ try:
852
+ backup.replace(db)
853
+ except OSError as exc:
854
+ raise LessonLedgerError(f"迁移失败且回滚失败: {exc}") from exc
855
+ raise
856
+ retire_migrate_backup(backup)
857
+ return read(logical)
858
+
859
+
860
+ def get_meta_value(c: sqlite3.Connection, key: str) -> str:
861
+ row = c.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
862
+ return "" if row is None else str(row[0])
863
+
864
+
865
+ def archive_manifest(c: sqlite3.Connection) -> list[dict[str, Any]]:
866
+ raw = get_meta_value(c, "archive_manifest")
867
+ if not raw:
868
+ return []
869
+ try:
870
+ loaded = json.loads(raw)
871
+ return list(loaded) if isinstance(loaded, list) else []
872
+ except (TypeError, ValueError):
873
+ return []
874
+
875
+
876
+ def record_event(c: sqlite3.Connection, typ: str, payload: dict[str, Any]) -> None:
877
+ last = c.execute("SELECT seq,hash FROM events ORDER BY seq DESC LIMIT 1").fetchone()
878
+ archived_seq = get_meta_value(c, "archive_last_seq")
879
+ if last:
880
+ seq, prev = int(last[0]) + 1, last[1]
881
+ elif archived_seq:
882
+ seq, prev = int(archived_seq) + 1, get_meta_value(c, "archive_last_hash")
883
+ else:
884
+ seq, prev = 1, ""
885
+ # DES-02:原先这里经 ``sys.modules.get("lesson_ledger")`` 反向取 ``MAX_EVENTS``,
886
+ # 与顶层 Facade 构成软环;而该常量**本模块即是定义方**(第 24 行),
887
+ # Facade 只是 re-export。改为直接读本模块全局后,覆盖该上限应 patch
888
+ # ``ledger.schema.MAX_EVENTS``(真实定义方),语义完全等价。
889
+ if c.execute("SELECT COUNT(*) FROM events").fetchone()[0] >= MAX_EVENTS:
890
+ raise LessonLedgerError("账本事件超过上限;请先执行 lesson archive-events 显式归档")
891
+ event = {"seq": seq, "type": typ, "at": now_iso(), "payload": payload, "prev_hash": prev}
892
+
893
+ event["hash"] = hashlib.sha256(canonical_bytes(event)).hexdigest()
894
+ c.execute(
895
+ "INSERT INTO events VALUES (?,?,?,?,?,?)",
896
+ (seq, typ, event["at"], json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")), prev, event["hash"]),
897
+ )
898
+ c.execute("UPDATE meta SET value=? WHERE key='head_hash'", (event["hash"],))
899
+
900
+
901
+ AUDIT_ORDER_BY = {
902
+ "patterns": "pattern_id",
903
+ "probes": "pattern_id,kind,value,ordinal",
904
+ "aliases": "pattern_id,alias",
905
+ "sources": "pattern_id,source_ref",
906
+ "occurrences": "pattern_id,fingerprint",
907
+ "reviews": "polling_id,lifecycle_id,round",
908
+ "review_patterns": "polling_id,lifecycle_id,round,pattern_id",
909
+ "review_findings": "polling_id,lifecycle_id,round,fingerprint",
910
+ "feedback": "lifecycle_id,round,pattern_id,fingerprint",
911
+ "incidents": "incident_id",
912
+ "tool_usage": "lifecycle_id,round,tool_name,category,finding_fingerprint",
913
+ "evidence_receipts": "receipt_id",
914
+ "consumption_events": "event_id",
915
+ "tool_experience": "tool_name,category",
916
+ "sync_import_receipts": "snapshot_id",
917
+ "events": "seq",
918
+ }
919
+
920
+
921
+ def audit_snapshot(c: sqlite3.Connection) -> dict[str, list[dict[str, Any]]]:
922
+ """Return a deterministic digest input for every mutable business table."""
923
+ snapshot: dict[str, list[dict[str, Any]]] = {}
924
+ for table in AUDITED_TABLES:
925
+ order_by = AUDIT_ORDER_BY.get(table, "rowid")
926
+ rows = c.execute(f"SELECT * FROM {table} ORDER BY {order_by}").fetchall()
927
+ snapshot[table] = [dict(row) for row in rows]
928
+ return snapshot
929
+
930
+
931
+ def _table_snapshot_payload(c: sqlite3.Connection, table: str) -> tuple[str, str, int]:
932
+ """Return canonical rows, digest, and count for one audited table."""
933
+ order_by = AUDIT_ORDER_BY.get(table, "rowid")
934
+ rows = [
935
+ dict(row)
936
+ for row in c.execute(f"SELECT * FROM {table} ORDER BY {order_by}").fetchall()
937
+ ]
938
+ payload = canonical_bytes(rows)
939
+ return payload.decode("utf-8"), hashlib.sha256(payload).hexdigest(), len(rows)
940
+
941
+
942
+ def _table_digest_record(c: sqlite3.Connection, table: str) -> tuple[str, int]:
943
+ """Return the deterministic digest/count for one audited table."""
944
+ _payload, digest, count = _table_snapshot_payload(c, table)
945
+ return digest, count
946
+
947
+
948
+ def _sync_table_digests(
949
+ c: sqlite3.Connection,
950
+ tables: Iterable[str] | None = None,
951
+ ) -> dict[str, tuple[str, str, int]]:
952
+ """Persist per-table summaries without changing the legacy global digest."""
953
+ selected = AUDITED_TABLES if tables is None else tuple(dict.fromkeys(tables))
954
+ unknown = set(selected) - set(AUDITED_TABLES)
955
+ if unknown:
956
+ raise LessonLedgerError(f"未知审计表摘要: {sorted(unknown)}")
957
+ stamp = now_iso()
958
+ summaries: dict[str, tuple[str, str, int]] = {}
959
+ for table in selected:
960
+ payload, digest, count = _table_snapshot_payload(c, table)
961
+ summaries[table] = (payload, digest, count)
962
+ c.execute(
963
+ "INSERT INTO state_table_digests(table_name,row_digest,row_count,snapshot_json,updated_at) "
964
+ "VALUES (?,?,?,?,?) ON CONFLICT(table_name) DO UPDATE SET "
965
+ "row_digest=excluded.row_digest,row_count=excluded.row_count,"
966
+ "snapshot_json=excluded.snapshot_json,updated_at=excluded.updated_at",
967
+ (table, digest, count, payload, stamp),
968
+ )
969
+ return summaries
970
+
971
+
972
+ def _validate_table_digests(
973
+ c: sqlite3.Connection,
974
+ tables: Iterable[str] | None = None,
975
+ *,
976
+ cached_snapshots: Mapping[str, tuple[str, str, int]] | None = None,
977
+ ) -> None:
978
+ """Verify persisted table summaries; full validation also rejects stale extras."""
979
+ selected = AUDITED_TABLES if tables is None else tuple(dict.fromkeys(tables))
980
+ unknown = set(selected) - set(AUDITED_TABLES)
981
+ if unknown:
982
+ raise LessonLedgerError(f"未知审计表摘要: {sorted(unknown)}")
983
+ query = "SELECT table_name,row_digest,row_count,snapshot_json FROM state_table_digests"
984
+ params: tuple[str, ...] = ()
985
+ if tables is not None:
986
+ placeholders = ",".join("?" for _ in selected)
987
+ query += f" WHERE table_name IN ({placeholders})"
988
+ params = selected
989
+ stored = {
990
+ str(row[0]): (str(row[1]), int(row[2]), str(row[3]))
991
+ for row in c.execute(query, params)
992
+ }
993
+ if tables is None and set(stored) != set(AUDITED_TABLES):
994
+ raise LessonLedgerError("state_table_digests 表集合不完整")
995
+ for table in selected:
996
+ cached = cached_snapshots.get(table) if cached_snapshots is not None else None
997
+ if cached is None:
998
+ expected_payload, expected_digest, expected_count = _table_snapshot_payload(c, table)
999
+ else:
1000
+ expected_payload, expected_digest, expected_count = cached
1001
+ actual = stored.get(table)
1002
+ if actual is None or actual[:2] != (expected_digest, expected_count):
1003
+ raise LessonLedgerError(f"审计表摘要无效: {table}")
1004
+ if actual[2] != expected_payload:
1005
+ message = "审计表摘要无效" if tables is None else "审计表快照无效"
1006
+ raise LessonLedgerError(f"{message}: {table}")
1007
+
1008
+
1009
+ def state_digest(c: sqlite3.Connection) -> str:
1010
+ return hashlib.sha256(canonical_bytes(audit_snapshot(c))).hexdigest()
1011
+
1012
+
1013
+ def _state_digest_from_table_snapshots(c: sqlite3.Connection) -> str:
1014
+ """Rebuild the legacy global digest from persisted canonical table rows."""
1015
+ stored = {
1016
+ str(row[0]): (str(row[1]), int(row[2]), str(row[3]))
1017
+ for row in c.execute(
1018
+ "SELECT table_name,row_digest,row_count,snapshot_json FROM state_table_digests"
1019
+ )
1020
+ }
1021
+ if set(stored) != set(AUDITED_TABLES):
1022
+ raise LessonLedgerError("state_table_digests 表集合不完整")
1023
+ snapshot: dict[str, list[dict[str, Any]]] = {}
1024
+ for table in AUDITED_TABLES:
1025
+ try:
1026
+ digest, count, payload = stored[table]
1027
+ rows = json.loads(payload)
1028
+ except (TypeError, ValueError, json.JSONDecodeError) as exc:
1029
+ raise LessonLedgerError(f"审计表快照无效: {table}") from exc
1030
+ if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
1031
+ raise LessonLedgerError(f"审计表快照无效: {table}")
1032
+ if hashlib.sha256(canonical_bytes(rows)).hexdigest() != digest or len(rows) != count:
1033
+ raise LessonLedgerError(f"审计表快照无效: {table}")
1034
+ snapshot[table] = rows
1035
+ return hashlib.sha256(canonical_bytes(snapshot)).hexdigest()
1036
+
1037
+
1038
+ def sync_state_hash(
1039
+ c: sqlite3.Connection,
1040
+ dirty_tables: Iterable[str] | None = None,
1041
+ *,
1042
+ digest_cache: dict[str, tuple[str, str, int]] | None = None,
1043
+ ) -> str:
1044
+ if dirty_tables is not None:
1045
+ summaries = _sync_table_digests(c, dirty_tables)
1046
+ if digest_cache is not None:
1047
+ digest_cache.update(summaries)
1048
+ value = _state_digest_from_table_snapshots(c)
1049
+ else:
1050
+ value = state_digest(c)
1051
+ c.execute("UPDATE meta SET value=? WHERE key='state_hash'", (value,))
1052
+ return value
1053
+
1054
+
1055
+ class _TransactionSummary:
1056
+ """记录当前写事务触碰的审计表。
1057
+
1058
+ 这里只用于安全地识别「没有业务表变更」的事务;有任一审计表写入时仍
1059
+ 走原有全量摘要算法。这样不会改变旧账本的 ``state_hash`` 定义,也不
1060
+ 把事件链校验交给增量缓存。
1061
+ """
1062
+
1063
+ def __init__(self) -> None:
1064
+ self.dirty_tables: set[str] = set()
1065
+
1066
+ def authorize(
1067
+ self,
1068
+ action_code: int,
1069
+ table: str | None,
1070
+ _column: str | None,
1071
+ _database: str | None,
1072
+ _source: str | None,
1073
+ ) -> int:
1074
+ if action_code in (
1075
+ sqlite3.SQLITE_INSERT,
1076
+ sqlite3.SQLITE_UPDATE,
1077
+ sqlite3.SQLITE_DELETE,
1078
+ ) and table in AUDITED_TABLES:
1079
+ self.dirty_tables.add(table)
1080
+ return sqlite3.SQLITE_OK
1081
+
1082
+
1083
+ def validate_pattern(
1084
+ c: sqlite3.Connection,
1085
+ db: Path,
1086
+ *,
1087
+ expected_state_hash: str | None = None,
1088
+ dirty_tables: Iterable[str] | None = None,
1089
+ cached_snapshots: Mapping[str, tuple[str, str, int]] | None = None,
1090
+ ) -> None:
1091
+ if c.execute("PRAGMA integrity_check").fetchone()[0] != "ok":
1092
+ raise LessonLedgerError(f"SQLite integrity_check 失败: {db}")
1093
+ schema = c.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()
1094
+ if schema is None:
1095
+ raise LessonLedgerError("SQLite schema_version 缺失;无法确认账本世代,请从备份恢复或显式重建")
1096
+ if schema[0] != str(SCHEMA_VERSION):
1097
+ if schema[0].isdigit() and 2 <= int(schema[0]) < SCHEMA_VERSION:
1098
+ raise LessonLedgerError(
1099
+ f"SQLite schema_version={schema[0]},请显式执行 lesson migrate "
1100
+ f"(python3 lesson_ledger.py migrate --ledger {db})后再重试"
1101
+ )
1102
+ raise LessonLedgerError("SQLite schema_version 缺失或不受支持")
1103
+ indexes = {str(row[1]) for row in c.execute("PRAGMA index_list('incidents')")}
1104
+ if "idx_incidents_finding_fingerprint" not in indexes:
1105
+ raise LessonLedgerError("incident finding_fingerprint 索引缺失,请执行 lesson migrate")
1106
+ archived_seq = get_meta_value(c, "archive_last_seq")
1107
+ prev = get_meta_value(c, "archive_last_hash") if archived_seq else ""
1108
+ expected_seq = int(archived_seq) + 1 if archived_seq else 1
1109
+ for r in c.execute("SELECT * FROM events ORDER BY seq"):
1110
+ try:
1111
+ payload = json.loads(r[3])
1112
+ except (TypeError, json.JSONDecodeError) as exc:
1113
+ raise LessonLedgerError("events payload 不是有效 JSON") from exc
1114
+ event = {"seq": r[0], "type": r[1], "at": r[2], "payload": payload, "prev_hash": r[4], "hash": r[5]}
1115
+ if event["seq"] != expected_seq:
1116
+ raise LessonLedgerError("events seq 不连续")
1117
+ if event["prev_hash"] != prev or hashlib.sha256(canonical_bytes({k: v for k, v in event.items() if k != "hash"})).hexdigest() != event["hash"]:
1118
+ raise LessonLedgerError("events hash-chain 无效")
1119
+ prev = event["hash"]
1120
+ expected_seq += 1
1121
+ head_row = c.execute("SELECT value FROM meta WHERE key='head_hash'").fetchone()
1122
+ if head_row is None:
1123
+ raise LessonLedgerError("SQLite head_hash 缺失")
1124
+ head = head_row[0]
1125
+ if head != prev:
1126
+ raise LessonLedgerError("head_hash 无效")
1127
+ state_hash = c.execute("SELECT value FROM meta WHERE key='state_hash'").fetchone()
1128
+ expected = expected_state_hash if expected_state_hash is not None else state_digest(c)
1129
+ if state_hash is None or state_hash[0] != expected:
1130
+ raise LessonLedgerError("state_hash 无效")
1131
+ _validate_table_digests(c, dirty_tables, cached_snapshots=cached_snapshots)
1132
+
1133
+
1134
+ def ledger_transaction(path: str | os.PathLike[str], fn: Callable[[sqlite3.Connection], Any]) -> Any:
1135
+ db = database_path(path)
1136
+ if not db.exists():
1137
+ initialize(path)
1138
+ with connect_ledger(db) as c:
1139
+ ensure_schema(c)
1140
+ c.execute("BEGIN IMMEDIATE")
1141
+ summary = _TransactionSummary()
1142
+ c.set_authorizer(summary.authorize)
1143
+ try:
1144
+ res = fn(c)
1145
+ # A read-only/no-op transaction cannot change the state digest. Keep
1146
+ # the old digest and still run integrity plus event-chain validation;
1147
+ # any audited-table DML takes the unchanged full-digest path.
1148
+ if not summary.dirty_tables:
1149
+ state_hash = get_meta_value(c, "state_hash")
1150
+ else:
1151
+ # ponytail: external SQL cannot identify its dirty tables; scan the
1152
+ # untouched snapshots before composing a new aggregate. Keep the
1153
+ # faster per-table commit path for dirty tables, and revisit with
1154
+ # a durable SQLite change marker if write throughput matters.
1155
+ untouched = tuple(
1156
+ table for table in AUDITED_TABLES
1157
+ if table not in summary.dirty_tables
1158
+ )
1159
+ _validate_table_digests(c, untouched)
1160
+ dirty_snapshots: dict[str, tuple[str, str, int]] = {}
1161
+ state_hash = sync_state_hash(
1162
+ c, summary.dirty_tables, digest_cache=dirty_snapshots,
1163
+ )
1164
+ validate_pattern(
1165
+ c,
1166
+ db,
1167
+ expected_state_hash=state_hash,
1168
+ # A no-op transaction still verifies every persisted table
1169
+ # digest, so metadata tampering cannot hide behind the fast
1170
+ # path. A dirty transaction verifies the tables it changed;
1171
+ # ordinary read/validate_deep remains the full fail-closed scan.
1172
+ dirty_tables=summary.dirty_tables or None,
1173
+ cached_snapshots=dirty_snapshots if summary.dirty_tables else None,
1174
+ )
1175
+ c.execute("COMMIT")
1176
+ if (
1177
+ os.environ.get("BUGX_CLOUD_AUTOSYNC_WORKER") != "1"
1178
+ and os.environ.get("BUGX_CLOUD_SYNC_ACTIVE") != "1"
1179
+ ):
1180
+ try:
1181
+ from core.cloud_sync.auto_sync import schedule_ledger_sync
1182
+ schedule_ledger_sync(path)
1183
+ except Exception:
1184
+ # Cloud sync is best-effort after the local commit; it must
1185
+ # never turn a durable local lesson into a failed write.
1186
+ pass
1187
+ return res
1188
+ except BaseException:
1189
+ c.execute("ROLLBACK")
1190
+ raise
1191
+ finally:
1192
+ c.set_authorizer(None)