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,1868 @@
1
+ #!/usr/bin/env python3
2
+ """core/attack_graph_store.py - LivingAttackGraph 的会话级持久化与事件写入契约 (DOC-125)。
3
+
4
+ DOC-125 把 :mod:`attack_graph` 定义成"审计期间真实演化的活图谱",但库里只有结构与
5
+ 算法,没有任何生产者:图谱从不被构建、演化、落盘或读取(核验报告 C125-1)。本模块
6
+ 就是那个**生产者与唯一存储契约**:
7
+
8
+ - 位置:``bugx_paths.require(root).polling_root`` —— **Session(polling)层**,
9
+ 不是 Round 级的 ``state_root``。图谱的价值在于跨轮累积(已发现的端点、被反驳的
10
+ 假设、回溯深度),放在 Round 层会让每一轮都从零开始。
11
+ - 写入:一律经 :func:`coverage_evidence.attach_attack_graph_snapshot` 原子落盘,
12
+ 并发用与证据存储同一套 ``_exclusive_lock(path.with_name(path.name + ".lock"))``
13
+ 约定,符号链接由 ``assert_no_symlink_components`` 与 ``O_NOFOLLOW`` 双重防护。
14
+ - 演化:一切状态变化都通过 :func:`record_event` 走事件类型表,事件同时进入
15
+ ``StreamingEventBus``(进程内即刻广播)和 ``graph.events``(落盘日志),
16
+ 因此"谁在什么时候把图谱改成这样"是可审计的。
17
+
18
+ 失败语义(关键契约)::class:`AttackGraphStoreError` **故意不继承 ``ValueError``**。
19
+ ``launch_phases/post_phase.py`` 的收尾 try/except 捕获 ``(OSError, ValueError, ...)``
20
+ 并把它转成"运行计时结算失败"的中断路径;图谱故障必须是**降级**(挖矿业继续),
21
+ 绝不能被那个 except 顺手吞成一次 abort。因此调用方要么显式捕获本类型,要么在最外层
22
+ 用 ``except Exception`` 降级——两种都不会误判成结算失败。
23
+
24
+ 消费者(worker 提示注入、任务调度、MCP 面)只需依赖本模块的公开面,不要直接读快照
25
+ 文件路径,也不要自己拼 ``attack-graph-snapshot.json``。
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import json
31
+ import re
32
+ import time
33
+ from contextlib import contextmanager
34
+ from pathlib import Path
35
+ from typing import Any, Callable, Iterable, Iterator, Mapping
36
+
37
+ from core.autonomous_cve import attack_graph as _ag
38
+ import core.bugx_paths as bugx_paths
39
+ from core.coverage import coverage_evidence
40
+ from core.autonomous_cve.attack_graph import LivingAttackGraph, ReflexiveBacktrackingEngine
41
+
42
+ #: 快照文件名由 ``coverage_evidence.attach_attack_graph_snapshot`` 固定。
43
+ SNAPSHOT_NAME = "attack-graph-snapshot.json"
44
+
45
+ #: 图谱节点上用于"哪个覆盖单元推进了它"的归属字段(调度亲和性依赖这两个键)。
46
+ UNIT_ATTR = "unit_id"
47
+ ADVANCED_BY_ATTR = "advanced_by"
48
+
49
+
50
+ class AttackGraphStoreError(Exception):
51
+ """攻击图谱存储层的失败。
52
+
53
+ 显式继承 ``Exception`` 而非 ``ValueError``:见模块文档串的"失败语义"。
54
+ """
55
+
56
+
57
+ # --------------------------------------------------------------------------
58
+ # 事件类型表(唯一权威;消费者按常量引用,不要写字面量)
59
+ # --------------------------------------------------------------------------
60
+
61
+ EVENT_ENDPOINT_DISCOVERED = "endpoint_discovered"
62
+ EVENT_ENDPOINTS_READY = "endpoints_ready"
63
+ EVENT_SINK_FOUND = "sink_found"
64
+ EVENT_HYPOTHESIS_VERIFIED = "hypothesis_verified"
65
+ EVENT_HYPOTHESIS_REJECTED = "hypothesis_rejected"
66
+ EVENT_ROLLBACK = "rollback"
67
+ # 以下为四大深度优化机制运转所必需的补充事件:
68
+ EVENT_HYPOTHESIS_PROPOSED = "hypothesis_proposed" # 假设入图,供 DAG 求值排期
69
+ EVENT_ROLE_OBSERVED = "role_observed" # 身份矩阵;跨租户判定的前提
70
+ EVENT_UNIT_STAMPED = "unit_stamped" # 单元归属(亲和性/断点续跑)
71
+ EVENT_UNIT_COVERED = "unit_covered" # 单元覆盖态推进 + tested_stages
72
+ EVENT_EVIDENCE_CHECKPOINTED = "evidence_checkpointed" # Life 已检查点证据吸收
73
+ EVENT_GRAPH_SEEDED = "graph_seeded" # pre 阶段冷启动/播种
74
+ EVENT_GRAPH_ABSORBED = "graph_absorbed" # post 阶段整轮吸收汇总
75
+
76
+ ALL_EVENTS = (
77
+ EVENT_ENDPOINT_DISCOVERED,
78
+ EVENT_ENDPOINTS_READY,
79
+ EVENT_SINK_FOUND,
80
+ EVENT_HYPOTHESIS_VERIFIED,
81
+ EVENT_HYPOTHESIS_REJECTED,
82
+ EVENT_ROLLBACK,
83
+ EVENT_HYPOTHESIS_PROPOSED,
84
+ EVENT_ROLE_OBSERVED,
85
+ EVENT_UNIT_STAMPED,
86
+ EVENT_UNIT_COVERED,
87
+ EVENT_EVIDENCE_CHECKPOINTED,
88
+ EVENT_GRAPH_SEEDED,
89
+ EVENT_GRAPH_ABSORBED,
90
+ )
91
+
92
+
93
+ def _as_bool(value: Any, default: bool) -> bool:
94
+ if isinstance(value, bool):
95
+ return value
96
+ if value is None:
97
+ return default
98
+ if isinstance(value, str):
99
+ text = value.strip().lower()
100
+ if text in {"1", "true", "yes", "y", "required", "auth", "protected"}:
101
+ return True
102
+ if text in {"0", "false", "no", "n", "public", "anonymous"}:
103
+ return False
104
+ return bool(value)
105
+
106
+
107
+ def _text(value: Any) -> str:
108
+ return str(value).strip() if value is not None else ""
109
+
110
+
111
+ def _texts(value: Any) -> list[str]:
112
+ if value is None:
113
+ return []
114
+ if isinstance(value, str):
115
+ return [value] if value.strip() else []
116
+ if isinstance(value, Iterable):
117
+ return [text for text in (_text(item) for item in value) if text]
118
+ return []
119
+
120
+
121
+ def _route_id_of(payload: Mapping[str, Any]) -> str:
122
+ """端点/路由节点 id:``route:<path>``(CLI 面为 ``cli:<name>``)。
123
+
124
+ 以 *路径* 而不是"文件:行"为 key,是为了让同一个端点在多轮、多 worker 提交下
125
+ 收敛成同一个节点——否则图谱会被重复端点灌满,越权链求解失去意义。
126
+ """
127
+ explicit = _text(payload.get("route_id") or payload.get("id"))
128
+ if explicit:
129
+ return explicit if ":" in explicit else f"route:{explicit}"
130
+ path = _text(payload.get("path") or payload.get("url") or payload.get("endpoint"))
131
+ if path.startswith(("http://", "https://")):
132
+ path = "/" + path.split("://", 1)[1].split("/", 1)[-1]
133
+ if not path and _text(payload.get("name")).startswith("endpoint:"):
134
+ parts = _text(payload.get("name")).split(":", 2)
135
+ path = parts[2] if len(parts) == 3 else ""
136
+ name = _text(payload.get("name"))
137
+ if path:
138
+ if _text(payload.get("method")).upper() == "CLI" or name.startswith("cli:"):
139
+ return f"cli:{path}"
140
+ return f"route:{path}" if path.startswith("/") else f"route:/{path}"
141
+ if not name:
142
+ return ""
143
+ return name if ":" in name else f"route:{name}"
144
+
145
+
146
+ def _sink_id_of(payload: Mapping[str, Any]) -> str:
147
+ explicit = _text(payload.get("sink_id"))
148
+ if explicit:
149
+ return explicit if explicit.startswith("sink:") else f"sink:{explicit}"
150
+ kind = _text(payload.get("kind") or payload.get("sink") or "unknown")
151
+ location = _text(
152
+ payload.get("location") or payload.get("name")
153
+ or payload.get("target") or payload.get("source_file")
154
+ )
155
+ line = payload.get("line")
156
+ if location:
157
+ tail = f":{line}" if isinstance(line, int) else ""
158
+ return f"sink:{location}{tail}"
159
+ return f"sink:{kind}:{len(str(line))}"
160
+
161
+
162
+ def _hypothesis_id_of(payload: Mapping[str, Any]) -> str:
163
+ explicit = _text(payload.get("hypothesis_id") or payload.get("hypo_id"))
164
+ if explicit:
165
+ return explicit if explicit.startswith("hypo:") else f"hypo:{explicit}"
166
+ target = _route_id_of(payload) or _text(payload.get("target"))
167
+ kind = _text(payload.get("type") or payload.get("vulnerability_type") or "unknown")
168
+ finding = _text(payload.get("finding_id") or payload.get("fingerprint"))
169
+ if finding:
170
+ return f"hypo:{finding}"
171
+ return f"hypo:{kind}:{target}" if target else f"hypo:{kind}"
172
+
173
+
174
+ # --------------------------------------------------------------------------
175
+ # 路径与并发
176
+ # --------------------------------------------------------------------------
177
+
178
+ def graph_dir(project_root: str | Path) -> Path:
179
+ """图谱所在目录 = Session(polling)层根目录。
180
+
181
+ 放在 ``polling_root`` 而不是 ``state_root``:``state_root`` 随 Round 切换,
182
+ 图谱必须随 Session 存活,否则第二 Round 看不到第一 Round 的攻击面。
183
+ """
184
+ root = Path(project_root).expanduser()
185
+ try:
186
+ scope = bugx_paths.require(root)
187
+ except bugx_paths.LayoutError as exc:
188
+ raise AttackGraphStoreError(f"攻击图谱需要已初始化的项目布局: {exc}") from exc
189
+ except OSError as exc:
190
+ raise AttackGraphStoreError(f"攻击图谱布局不可读: {exc}") from exc
191
+ directory = scope.polling_root
192
+ bugx_paths.assert_no_symlink_components(directory, error_cls=AttackGraphStoreError)
193
+ return directory
194
+
195
+
196
+ def snapshot_path(project_root: str | Path) -> Path:
197
+ """持久化快照文件路径(供只读消费者展示;写入请走 :func:`save_graph`)。"""
198
+ return graph_dir(project_root) / SNAPSHOT_NAME
199
+
200
+
201
+ def _lock_path(root: Path) -> Path:
202
+ snapshot = root / SNAPSHOT_NAME
203
+ return snapshot.with_name(snapshot.name + ".lock")
204
+
205
+
206
+ @contextmanager
207
+ def _store_lock(directory: Path) -> Iterator[None]:
208
+ """复用证据存储的进程内 + 跨进程独占锁约定。
209
+
210
+ 注意:``fcntl.flock`` 对同一进程内**第二个 fd** 也会阻塞,所以持锁期间只能调用
211
+ ``_*_locked`` 内部函数,绝不可重入公共 :func:`save_graph`。
212
+ """
213
+ directory.mkdir(parents=True, exist_ok=True)
214
+ with coverage_evidence._exclusive_lock(_lock_path(directory)): # noqa: SLF001
215
+ yield
216
+
217
+
218
+ def _schema_validation_mode() -> dict[str, Any]:
219
+ """把 C125-13 的降级事实写进 ``meta``,使其可被审计而不是只 warn 一次。"""
220
+ available = _ag.jsonschema is not None
221
+ schema_present = _ag.SCHEMA_PATH.is_file()
222
+ return {
223
+ "mode": "jsonschema" if (available and schema_present) else "builtin_degraded",
224
+ "strict_json_schema": bool(available and schema_present),
225
+ "jsonschema_available": available,
226
+ "schema_file_present": schema_present,
227
+ "schema_path": str(_ag.SCHEMA_PATH),
228
+ }
229
+
230
+
231
+ def _new_graph(root: Path) -> LivingAttackGraph:
232
+ graph = LivingAttackGraph()
233
+ graph.meta.update({
234
+ "project_root": str(root),
235
+ "session_layer": "polling_root",
236
+ "seeded_at": time.time(),
237
+ "units": {},
238
+ "event_counts": {},
239
+ "schema_validation": _schema_validation_mode(),
240
+ })
241
+ return graph
242
+
243
+
244
+ # --------------------------------------------------------------------------
245
+ # 读 / 写
246
+ # --------------------------------------------------------------------------
247
+
248
+ def load_graph(project_root: str | Path) -> LivingAttackGraph | None:
249
+ """读取当前 Session 的图谱;**缺失或损坏一律返回 None,绝不抛异常**。
250
+
251
+ "损坏"包括:JSON 解析失败、顶层形状不合法、节点字段缺失导致反序列化抛错。
252
+ 消费者据此把"无图谱"当成正常的冷启动分支,而不是让整条流水线因一个坏文件中断。
253
+ """
254
+ try:
255
+ directory = graph_dir(project_root)
256
+ except (AttackGraphStoreError, bugx_paths.LayoutError, OSError, ValueError):
257
+ return None
258
+ try:
259
+ payload = coverage_evidence.load_attack_graph_snapshot(directory)
260
+ except (OSError, ValueError, TypeError):
261
+ return None
262
+ if not isinstance(payload, Mapping):
263
+ return None
264
+ try:
265
+ graph = LivingAttackGraph.from_dict(payload)
266
+ except Exception:
267
+ # from_dict 面对人为篡改/半写文件会抛 KeyError/TypeError/AttributeError 等,
268
+ # 这里必须兜住:契约是"永不 raise"。
269
+ return None
270
+ if not isinstance(graph.meta, dict):
271
+ graph.meta = {}
272
+ return graph
273
+
274
+
275
+ def _write_graph_locked(directory: Path, graph: LivingAttackGraph) -> Path:
276
+ graph.meta["updated_at"] = time.time()
277
+ graph.meta["schema_validation"] = _schema_validation_mode()
278
+ try:
279
+ graph.validate()
280
+ except Exception as exc:
281
+ # 结构不合法就拒绝落盘:宁可留旧快照,也不要污染消费者的图谱。
282
+ raise AttackGraphStoreError(f"攻击图谱结构校验未通过,拒绝写入: {exc}") from exc
283
+ try:
284
+ bugx_paths.assert_no_symlink_components(directory, error_cls=AttackGraphStoreError)
285
+ return coverage_evidence.attach_attack_graph_snapshot(directory, graph)
286
+ except AttackGraphStoreError:
287
+ raise
288
+ except (OSError, ValueError, TypeError) as exc:
289
+ raise AttackGraphStoreError(f"攻击图谱快照写入失败: {exc}") from exc
290
+
291
+
292
+ def save_graph(project_root: str | Path, graph: LivingAttackGraph) -> Path:
293
+ """原子、并发安全地持久化图谱;返回快照路径。"""
294
+ if not isinstance(graph, LivingAttackGraph):
295
+ raise AttackGraphStoreError("save_graph 只接受 LivingAttackGraph 实例")
296
+ directory = graph_dir(project_root)
297
+ with _store_lock(directory):
298
+ return _write_graph_locked(directory, graph)
299
+
300
+
301
+ # --------------------------------------------------------------------------
302
+ # 单元归属(调度亲和性的数据来源)
303
+ # --------------------------------------------------------------------------
304
+
305
+ _NODE_KINDS = ("routes", "sinks", "hypotheses", "roles", "parameters")
306
+
307
+
308
+ def stamp_unit(
309
+ graph: LivingAttackGraph,
310
+ unit_id: str,
311
+ *,
312
+ routes: Iterable[str] | None = None,
313
+ sinks: Iterable[str] | None = None,
314
+ hypotheses: Iterable[str] | None = None,
315
+ roles: Iterable[str] | None = None,
316
+ parameters: Iterable[str] | None = None,
317
+ advanced_by: Any = None,
318
+ round_no: int | None = None,
319
+ stage_id: str | None = None,
320
+ tested_stages: Iterable[str] | None = None,
321
+ **attrs: Any,
322
+ ) -> dict[str, Any]:
323
+ """把一次推进归因到覆盖单元:既写节点属性,也写 ``meta["units"][unit_id]``。
324
+
325
+ 两个层次都要写,因为消费者读法不同:
326
+ - 调度器(亲和性/断点续跑)按单元聚合 → 读 ``meta["units"]``;
327
+ - 图谱切片与越权链按节点取值 → 读节点上的 ``unit_id`` / ``advanced_by``。
328
+ """
329
+ unit = _text(unit_id)
330
+ if not unit:
331
+ raise AttackGraphStoreError("stamp_unit 需要非空 unit_id")
332
+ if not isinstance(graph.meta, dict):
333
+ graph.meta = {}
334
+ units = graph.meta.setdefault("units", {})
335
+ if not isinstance(units, dict):
336
+ units = {}
337
+ graph.meta["units"] = units
338
+ record = units.get(unit)
339
+ if not isinstance(record, dict):
340
+ record = {"unit_id": unit, "nodes": {}, "advanced_by": []}
341
+ units[unit] = record
342
+ record["updated_at"] = time.time()
343
+
344
+ given = {
345
+ "routes": _texts(routes),
346
+ "sinks": _texts(sinks),
347
+ "hypotheses": _texts(hypotheses),
348
+ "roles": _texts(roles),
349
+ "parameters": _texts(parameters),
350
+ }
351
+ index = {
352
+ "routes": graph.routes,
353
+ "sinks": graph.sinks,
354
+ "hypotheses": graph.hypotheses,
355
+ "roles": graph.roles,
356
+ "parameters": graph.parameters,
357
+ }
358
+ nodes = record.setdefault("nodes", {})
359
+ if not isinstance(nodes, dict):
360
+ nodes = {}
361
+ record["nodes"] = nodes
362
+ people = sorted(set(_texts(record.get("advanced_by")) + _texts(advanced_by)))
363
+ for kind, ids in given.items():
364
+ merged = sorted(set(_texts(nodes.get(kind)) + ids))
365
+ if merged:
366
+ nodes[kind] = merged
367
+ store = index[kind]
368
+ for node_id in ids:
369
+ node = store.get(node_id)
370
+ if not isinstance(node, dict):
371
+ continue # 允许引用尚未入图的 id,但不因此失败
372
+ node[UNIT_ATTR] = unit
373
+ if people:
374
+ # 亲和性判定的两个键必须同时落在节点上:只留 unit_id 的话,
375
+ # "这个端点是哪个 worker 推进的"仍然只能反查 meta。
376
+ node[ADVANCED_BY_ATTR] = people[0] if len(people) == 1 else people
377
+ if stage_id:
378
+ node["last_stage_id"] = stage_id
379
+ for key, value in attrs.items():
380
+ node[key] = value
381
+ if kind == "routes" and tested_stages:
382
+ existing = set(_texts(node.get("tested_stages")))
383
+ node["tested_stages"] = sorted(existing | set(_texts(tested_stages)))
384
+
385
+ if people:
386
+ record["advanced_by"] = people
387
+ for key, value in attrs.items():
388
+ record[key] = value
389
+ if round_no is not None:
390
+ record["last_round"] = round_no
391
+ record["node_total"] = sum(len(_texts(value)) for value in nodes.values())
392
+ return record
393
+
394
+
395
+ # --------------------------------------------------------------------------
396
+ # 事件处理器
397
+ # --------------------------------------------------------------------------
398
+
399
+ def _merge_node(graph: LivingAttackGraph, collection: str, node_id: str, **attrs: Any) -> dict[str, Any]:
400
+ """把 ``attrs`` 并入已存在节点(保留既有键),或新建节点。"""
401
+ # ``kind`` is a valid node attribute (notably for sinks). Do not use it
402
+ # as the Python parameter name: ``_merge_node(..., **{"kind": ...})``
403
+ # would otherwise collide with the collection argument before the
404
+ # function can merge the existing node.
405
+ store = getattr(graph, collection)
406
+ existing = store.get(node_id)
407
+ if isinstance(existing, dict):
408
+ merged = {**existing, **attrs}
409
+ merged["id"] = node_id
410
+ store[node_id] = merged
411
+ return merged
412
+ raise KeyError(node_id)
413
+
414
+
415
+ def _on_endpoint(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
416
+ route_id = _route_id_of(payload)
417
+ if not route_id:
418
+ raise AttackGraphStoreError("endpoint_discovered 需要 route_id/path/name 之一")
419
+ observed = "auth_required" in payload and payload.get("auth_required") is not None
420
+ auth_required = _as_bool(payload.get("auth_required"), False)
421
+ attrs: dict[str, Any] = {
422
+ "method": (_text(payload.get("method")) or "GET").upper(),
423
+ "auth_required": auth_required,
424
+ "auth_required_source": "observed" if observed else "public_unauthenticated",
425
+ "exposure": "protected" if auth_required else "public_unauthenticated",
426
+ "path": _text(payload.get("path") or payload.get("url") or route_id.split(":", 1)[-1]),
427
+ "tested_stages": [],
428
+ }
429
+ for key in ("source_file", "line", "framework", "name", "stage_id"):
430
+ if payload.get(key) is not None:
431
+ attrs[key] = payload[key]
432
+ if route_id in graph.routes:
433
+ _merge_node(graph, "routes", route_id, **attrs)
434
+ node = graph.routes[route_id]
435
+ created = False
436
+ else:
437
+ node = graph.add_route(route_id, attrs["method"], auth_required, **{
438
+ k: v for k, v in attrs.items() if k not in ("method", "auth_required")
439
+ })
440
+ created = True
441
+ unit = _text(payload.get(UNIT_ATTR) or payload.get("unit_id"))
442
+ if unit:
443
+ stamp_unit(graph, unit, routes=[route_id], advanced_by=payload.get(ADVANCED_BY_ATTR),
444
+ round_no=ctx.get("round_no"))
445
+ for role_id in _texts(payload.get("legit_roles")):
446
+ graph.add_edge(role_id, route_id, "HAS_LEGITIMATE_ACCESS")
447
+ return {"route_id": route_id, "created": created, "auth_required": auth_required}
448
+
449
+
450
+ def _on_endpoints_ready(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
451
+ surfaces = payload.get("endpoints") or payload.get("surfaces") or []
452
+ if not isinstance(surfaces, list):
453
+ surfaces = []
454
+ ready: list[str] = []
455
+ for item in surfaces:
456
+ row = dict(item) if isinstance(item, Mapping) else {}
457
+ row.setdefault("unit_id", _text(payload.get("unit_id")))
458
+ row.setdefault(ADVANCED_BY_ATTR, payload.get(ADVANCED_BY_ATTR))
459
+ try:
460
+ result = _on_endpoint(graph, row, ctx)
461
+ except AttackGraphStoreError:
462
+ continue # 单条畸形面不影响其余端点入图
463
+ ready.append(result["route_id"])
464
+ count = payload.get("count")
465
+ graph.meta["endpoints_ready"] = True
466
+ graph.meta["endpoints_ready_at"] = time.time()
467
+ graph.meta["endpoints_ready_count"] = len(graph.routes)
468
+ if isinstance(count, int) and not isinstance(count, bool):
469
+ graph.meta["surface_reported_count"] = count
470
+ unit = _text(payload.get("unit_id"))
471
+ if unit:
472
+ stamp_unit(graph, unit, routes=ready, advanced_by=payload.get(ADVANCED_BY_ATTR),
473
+ round_no=ctx.get("round_no"))
474
+ return {"ready_routes": len(ready), "route_total": len(graph.routes)}
475
+
476
+
477
+ def _on_sink(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
478
+ sink_id = _sink_id_of(payload)
479
+ kind = _text(payload.get("kind") or payload.get("sink") or "unknown")
480
+ attrs: dict[str, Any] = {"kind": kind}
481
+ for key in ("source_file", "line", "location", "severity", "name", "description"):
482
+ if payload.get(key) is not None:
483
+ attrs[key] = payload[key]
484
+ if sink_id in graph.sinks:
485
+ _merge_node(graph, "sinks", sink_id, **attrs)
486
+ created = False
487
+ else:
488
+ graph.add_sink(sink_id, kind, **{k: v for k, v in attrs.items() if k != "kind"})
489
+ created = True
490
+ route_id = _text(payload.get("route_id")) or _route_id_of(payload)
491
+ if route_id and route_id in graph.routes:
492
+ graph.add_edge(route_id, sink_id, "REACHES_SINK")
493
+ elif route_id:
494
+ graph.add_edge(route_id, sink_id, "REACHES_SINK")
495
+ param_id = _text(payload.get("param_id"))
496
+ if param_id:
497
+ graph.add_edge(param_id, sink_id, "TAINTS")
498
+ unit = _text(payload.get(UNIT_ATTR) or payload.get("unit_id"))
499
+ if unit:
500
+ stamp_unit(graph, unit, sinks=[sink_id], advanced_by=payload.get(ADVANCED_BY_ATTR),
501
+ round_no=ctx.get("round_no"))
502
+ if payload.get("speculative"):
503
+ graph.sinks[sink_id]["speculative"] = True
504
+ return {"sink_id": sink_id, "created": created, "kind": kind}
505
+
506
+
507
+ def _on_hypothesis_proposed(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
508
+ hyp_id = _hypothesis_id_of(payload)
509
+ target = _text(payload.get("target")) or _route_id_of(payload)
510
+ kind = _text(payload.get("type") or payload.get("vulnerability_type") or "unknown")
511
+ status = _text(payload.get("status")) or "proposed"
512
+ extra = {
513
+ key: value
514
+ for key, value in payload.items()
515
+ if key in {"title", "root_cause", "severity", "confidence", "finding_id",
516
+ "description", "status_code", "route_id", "sink_id", "stage_id",
517
+ "reproduction", "source_file", "line", "unit_id", "confirmed_by_ai"}
518
+ and value is not None
519
+ }
520
+ # DOC-241 假说融合与去重:AI 确认的精准假说平滑替代/升级粗粒度静态初筛假说 (消除双轨冗余)
521
+ if extra.get("confirmed_by_ai"):
522
+ src_file = str(payload.get("source_file") or "").replace("\\", "/")
523
+ src_line = int(payload.get("line") or 0)
524
+ p_sink = str(payload.get("sink_id") or "")
525
+ p_type = str(payload.get("type") or payload.get("vulnerability_type") or "")
526
+ superseded_ids = []
527
+ for exist_id, exist_hypo in graph.hypotheses.items():
528
+ if exist_id == hyp_id:
529
+ continue
530
+ e_src = str(exist_hypo.get("source_file") or "").replace("\\", "/")
531
+ e_line = int(exist_hypo.get("line") or 0)
532
+ e_sink = str(exist_hypo.get("sink_id") or "")
533
+ e_type = str(exist_hypo.get("type") or exist_hypo.get("vulnerability_type") or "")
534
+ if not e_src:
535
+ raw_ref = e_sink if e_sink.startswith("sink:") else str(exist_hypo.get("target") or "")
536
+ if raw_ref.startswith("sink:"):
537
+ parts = raw_ref[5:].rsplit(":", 1)
538
+ e_src = parts[0].replace("\\", "/")
539
+ if len(parts) > 1 and parts[1].isdigit():
540
+ e_line = int(parts[1])
541
+ elif exist_hypo.get("unit_id") and "::" in str(exist_hypo.get("unit_id")):
542
+ u_parts = str(exist_hypo["unit_id"]).split("::")[0].split(":")[-1]
543
+ if "/" in u_parts or "." in u_parts:
544
+ e_src = u_parts.replace("\\", "/")
545
+
546
+ if e_src and (e_src == src_file or e_src.endswith(src_file) or src_file.endswith(e_src)):
547
+ line_match = src_line and e_line and abs(src_line - e_line) <= 3
548
+ sink_match = p_sink and e_sink and (p_sink in e_sink or e_sink in p_sink)
549
+ if line_match or sink_match:
550
+ if not exist_hypo.get("confirmed_by_ai"):
551
+ superseded_ids.append(exist_id)
552
+ elif p_type and e_type and (p_type in e_type or e_type in p_type):
553
+ superseded_ids.append(exist_id)
554
+ for s_id in superseded_ids:
555
+ graph.hypotheses.pop(s_id, None)
556
+ graph.edges = [e for e in graph.edges if e.get("from") != s_id and e.get("to") != s_id and e.get("hypothesis_id") != s_id]
557
+
558
+ if hyp_id in graph.hypotheses:
559
+ _merge_node(graph, "hypotheses", hyp_id, type=kind, target=target, **extra)
560
+ created = False
561
+ else:
562
+ graph.add_hypothesis(hyp_id, kind, target, status, **extra)
563
+ created = True
564
+ if target:
565
+ graph.add_edge(hyp_id, target, "HYPOTHESIZES", hypothesis_id=hyp_id)
566
+ sink_id = _text(payload.get("sink_id"))
567
+ if sink_id:
568
+ graph.add_edge(hyp_id, sink_id, "HYPOTHESIZES_SINK", hypothesis_id=hyp_id)
569
+ unit = _text(payload.get(UNIT_ATTR) or payload.get("unit_id"))
570
+ if unit:
571
+ stamp_unit(graph, unit, hypotheses=[hyp_id], advanced_by=payload.get(ADVANCED_BY_ATTR),
572
+ round_no=ctx.get("round_no"))
573
+ return {"hypothesis_id": hyp_id, "created": created, "status": graph.hypotheses[hyp_id]["status"]}
574
+
575
+
576
+ def _on_hypothesis_verified(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
577
+ detail = _on_hypothesis_proposed(graph, {**payload, "status": payload.get("status") or "testing"}, ctx)
578
+ hyp_id = detail["hypothesis_id"]
579
+ graph.update_hypothesis_status(hyp_id, "verified", _text(payload.get("reason")) or "证据实锤")
580
+ node = graph.hypotheses[hyp_id]
581
+ node["verified_at"] = time.time()
582
+ if payload.get("evidence_path") is not None:
583
+ node["evidence_path"] = _text(payload.get("evidence_path"))
584
+ if payload.get("artifact_sha256") is not None:
585
+ node["artifact_sha256"] = _text(payload.get("artifact_sha256"))
586
+ relation = _text(payload.get("relation")) or "EXPLOITED_ACCESS"
587
+ target = _text(payload.get("target")) or _route_id_of(payload) or node.get("target", "")
588
+ # 实锤的端点/身份就是既成事实:它们可能只在 finding 文本里出现过(worker 直接
589
+ # 提交结论),此时必须补进图谱,否则越权链与消费者切片都会缺一截。
590
+ if target and target not in graph.routes and target.startswith("route:"):
591
+ graph.add_route(target, _text(payload.get("method")) or "GET", True,
592
+ auth_required_source="inferred_from_verified_finding",
593
+ **{k: v for k, v in
594
+ {UNIT_ATTR: _text(payload.get(UNIT_ATTR) or payload.get("unit_id")),
595
+ ADVANCED_BY_ATTR: payload.get(ADVANCED_BY_ATTR)}.items() if v})
596
+ role_id = _text(payload.get("role_id"))
597
+ if role_id and role_id not in graph.roles:
598
+ graph.add_role(role_id, _text(payload.get("role_type")) or "unknown",
599
+ source="inferred_from_verified_finding")
600
+ if role_id and target:
601
+ graph.add_edge(role_id, target, relation, hypothesis_id=hyp_id)
602
+ elif target and target in graph.sinks:
603
+ graph.add_edge(node.get("target", target), target, relation, hypothesis_id=hyp_id)
604
+ node.pop("speculative", None)
605
+ graph.meta["last_verified_hypothesis"] = hyp_id
606
+ counts = graph.meta.setdefault("verified_count", 0)
607
+ graph.meta["verified_count"] = (counts if isinstance(counts, int) else 0) + 1
608
+ return {"hypothesis_id": hyp_id, "status": "verified", "illegal_edges": len(graph.get_illegal_access_edges())}
609
+
610
+
611
+ def _on_hypothesis_rejected(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
612
+ """反驳假设 → 快照 → 推测拓扑入图 → ``record_attempt`` 回溯 → 回滚。
613
+
614
+ 语义:被明确拒绝的假设不应把它在探测期间声称的端点/汇点永久留在图里误导调度;
615
+ 所以先打快照,把这些**推测节点**加进去(真实发生过的事),驱动回溯判定,再把
616
+ 拓扑回滚,只留下假设节点本身 + 它的最终裁决 + 可跨 Round 存活的回溯历史。
617
+ 实锤路径(``hypothesis_verified``)不走这里,其拓扑永久保留。
618
+ """
619
+ hyp_id = _hypothesis_id_of(payload)
620
+ target = _text(payload.get("target")) or _route_id_of(payload)
621
+ kind = _text(payload.get("type") or payload.get("vulnerability_type") or "unknown")
622
+ # 1. 假设节点先入图(快照之前):回滚后它必须仍然存在并承载裁决。
623
+ _on_hypothesis_proposed(
624
+ graph, {**payload, "target": target, "type": kind, "status": "testing"}, ctx
625
+ )
626
+ # 2. 快照:此刻拓扑里还没有本次推测节点。
627
+ snapshot_id = graph.create_snapshot(tag=f"pre-reflex:{hyp_id}")
628
+ speculative_routes: list[str] = []
629
+ speculative_sinks: list[str] = []
630
+ decision: dict[str, Any] = {}
631
+ attempts = 0
632
+ fix: Any = None
633
+ final_status = ""
634
+ terminal = False
635
+ rolled_back = False
636
+ compensation_failed = False
637
+ pending_error: BaseException | None = None
638
+
639
+ try:
640
+ # 3. 推测拓扑入图(worker 在失败尝试中声称的端点/汇点)。
641
+ speculative_routes = _texts(payload.get("speculative_routes"))
642
+ speculative_sinks = _texts(payload.get("speculative_sinks"))
643
+ for row in payload.get("speculative") or []:
644
+ if isinstance(row, str):
645
+ # 允许只给 id:sink: 前缀归汇点,其余按端点处理。
646
+ if row.startswith("sink:"):
647
+ speculative_sinks.append(row)
648
+ else:
649
+ speculative_routes.append(row)
650
+ continue
651
+ if not isinstance(row, Mapping):
652
+ continue
653
+ try:
654
+ if row.get("kind"):
655
+ result = _on_sink(graph, {**row, "speculative": True}, ctx)
656
+ speculative_sinks.append(result.get("sink_id", ""))
657
+ else:
658
+ result = _on_endpoint(graph, row, ctx)
659
+ node = graph.routes.get(result.get("route_id"))
660
+ if isinstance(node, dict):
661
+ node["speculative"] = True
662
+ speculative_routes.append(result.get("route_id", ""))
663
+ except AttackGraphStoreError:
664
+ continue
665
+ for route_id in speculative_routes:
666
+ if route_id not in graph.routes:
667
+ graph.add_route(route_id, "GET", True, speculative=True, unit_id=_text(payload.get("unit_id")))
668
+ for sink_id in speculative_sinks:
669
+ if sink_id not in graph.sinks:
670
+ graph.add_sink(sink_id, _text(payload.get("kind")) or "unknown",
671
+ speculative=True, unit_id=_text(payload.get("unit_id")))
672
+ # 4. 反思回溯:历史直接别名在 graph.reflex 上,因此天然跨 Round 存活。
673
+ engine = ReflexiveBacktrackingEngine(graph)
674
+ history_before = len(engine.backtrack_history.get(hyp_id, []))
675
+ decision = engine.record_attempt(
676
+ hyp_id,
677
+ status_code=int(payload.get("status_code") or 0),
678
+ response_body=str(payload.get("response_body") or payload.get("body_snippet") or ""),
679
+ is_exploit_successful=bool(payload.get("is_exploit_successful", False)),
680
+ has_negative_control=bool(payload.get("has_negative_control", False)),
681
+ request_context=payload.get("request_context") if isinstance(payload.get("request_context"), Mapping) else None,
682
+ )
683
+ attempts = len(engine.backtrack_history.get(hyp_id, [])) - history_before
684
+ # 5. 自动修包产物**只作为图谱属性/reflex 记录**,绝不回写证据文件。
685
+ # 节点级属性留到回滚之后再写,否则会被自己刚恢复的快照抹掉。
686
+ fix = decision.get("heuristic_fix")
687
+ if isinstance(fix, Mapping):
688
+ suggestions = graph.reflex.setdefault("auto_fix_suggestions", [])
689
+ suggestions.append({"hypothesis_id": hyp_id, **dict(fix), "recorded_at": time.time()})
690
+ del suggestions[:-_ag.MAX_ROLLBACK_LOG]
691
+ # 有可尝试的补丁头 → 记录就地重放计划,交给有网络能力的消费者执行。
692
+ headers = fix.get("patch_headers")
693
+ if isinstance(headers, Mapping) and headers:
694
+ pending = graph.reflex.setdefault("replay_pending", [])
695
+ pending.append({
696
+ "hypothesis_id": hyp_id,
697
+ "patch_headers": dict(headers),
698
+ "unit_id": _text(payload.get("unit_id")),
699
+ # A replay plan is only useful when a later network-capable
700
+ # caller can prove it is still bound to the same target.
701
+ "target_fingerprint": _text(payload.get("target_fingerprint")) or None,
702
+ "queued_at": time.time(),
703
+ "attempts": attempts,
704
+ })
705
+ del pending[:-_ag.MAX_ROLLBACK_LOG]
706
+ # 6. 终结性拒绝的裁决数据。``terminal`` 由结算门禁裁定,而不是只信引擎的
707
+ # HTTP 启发式;final_status 必须等回滚之后才写回节点(见 finally)。
708
+ final_status = _text(decision.get("status"))
709
+ terminal = decision.get("action") in {"close_hypothesis", "abort_exhausted"} or _as_bool(
710
+ payload.get("terminal"), False
711
+ )
712
+ if terminal and final_status not in {"refuted", "not_applicable"}:
713
+ final_status = "refuted"
714
+ except BaseException as exc:
715
+ # 事务中途的任何失败都强制补偿:推测拓扑绝不能跨异常留存。
716
+ pending_error = exc
717
+ terminal = False
718
+ finally:
719
+ # 事务补偿:只要事务本应回滚(终态拒绝)或中途失败,就无条件尝试回滚。
720
+ # rollback_to_snapshot 幂等/可重入——向同一快照重复回滚是 no-op 且返回 True,
721
+ # 因此此处执行是安全的;终态裁决一律在回滚之后再写。
722
+ if terminal or pending_error is not None:
723
+ try:
724
+ rolled_back = graph.rollback_to_snapshot(snapshot_id)
725
+ except Exception as exc:
726
+ # fail-closed:补偿失败时绝不静默留下"已完成拒绝"的假象。
727
+ # 把假设显式标记为未完成,并保留失败原因与快照锚。
728
+ rolled_back = False
729
+ compensation_failed = True
730
+ marker = {
731
+ "status": "rollback_failed",
732
+ "status_reason": (
733
+ f"推测拓扑回滚补偿失败,假设未完成: {exc}"
734
+ ),
735
+ "speculative_cleanup_failed": True,
736
+ "reflex_snapshot_id": snapshot_id,
737
+ }
738
+ survivor = graph.hypotheses.get(hyp_id)
739
+ if isinstance(survivor, dict):
740
+ survivor.update(marker)
741
+ else:
742
+ add_attrs = {k: v for k, v in marker.items() if k != "status"}
743
+ graph.add_hypothesis(hyp_id, kind, target, "rollback_failed", **add_attrs)
744
+ if not compensation_failed and terminal and rolled_back:
745
+ # 回滚把假设状态带回 snapshot 时刻的 testing,
746
+ # 所以终态必须在回滚之后再写一次。
747
+ node = graph.hypotheses.get(hyp_id)
748
+ if node is None:
749
+ graph.add_hypothesis(
750
+ hyp_id, kind, target, final_status or "refuted",
751
+ status_reason="假设被反驳,推测拓扑已回滚",
752
+ )
753
+ else:
754
+ graph.update_hypothesis_status(
755
+ hyp_id, final_status or "refuted",
756
+ _text(payload.get("reason")) or "假设被反驳,推测拓扑已回滚",
757
+ )
758
+ survivor = graph.hypotheses.get(hyp_id)
759
+ if isinstance(survivor, dict):
760
+ survivor["reflex_backtrack_depth"] = attempts
761
+ survivor["reflex_snapshot_id"] = snapshot_id
762
+ rollbacks = graph.reflex.setdefault("rollbacks", [])
763
+ rollbacks.append({
764
+ "snapshot_id": snapshot_id,
765
+ "hypothesis_id": hyp_id,
766
+ "reason": _text(decision.get("action")) or "terminal_rejection",
767
+ "rolled_back": rolled_back,
768
+ "compensation_failed": compensation_failed,
769
+ "routes_dropped": max(0, len(speculative_routes)),
770
+ "sinks_dropped": max(0, len(speculative_sinks)),
771
+ "at": time.time(),
772
+ })
773
+ del rollbacks[:-_ag.MAX_ROLLBACK_LOG]
774
+
775
+ if pending_error is not None:
776
+ raise pending_error
777
+ if compensation_failed:
778
+ raise AttackGraphStoreError(
779
+ f"推测拓扑回滚补偿失败,假设 {hyp_id} 已标记未完成 (snapshot={snapshot_id})"
780
+ )
781
+ survivor = graph.hypotheses.get(hyp_id)
782
+ if isinstance(survivor, dict) and isinstance(fix, Mapping):
783
+ survivor["auto_fix_action"] = _text(fix.get("action"))
784
+ unit = _text(payload.get(UNIT_ATTR) or payload.get("unit_id"))
785
+ if unit:
786
+ stamp_unit(graph, unit, hypotheses=[hyp_id], advanced_by=payload.get(ADVANCED_BY_ATTR),
787
+ round_no=ctx.get("round_no"))
788
+ counts = graph.meta.get("rejected_count")
789
+ graph.meta["rejected_count"] = (counts if isinstance(counts, int) else 0) + 1
790
+ return {
791
+ "hypothesis_id": hyp_id,
792
+ "status": graph.hypotheses.get(hyp_id, {}).get("status"),
793
+ "action": decision.get("action"),
794
+ "blocked_reason": decision.get("blocked_reason"),
795
+ "backtrack_depth": attempts,
796
+ "terminal": terminal,
797
+ "rolled_back": rolled_back,
798
+ "compensation_failed": compensation_failed,
799
+ "snapshot_id": snapshot_id,
800
+ "history_total": len(engine.backtrack_history.get(hyp_id, [])),
801
+ }
802
+
803
+
804
+ def _on_rollback(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
805
+ snapshot_id = _text(payload.get("snapshot_id"))
806
+ if not snapshot_id:
807
+ snapshots = graph.list_snapshots()
808
+ if not snapshots:
809
+ raise AttackGraphStoreError("rollback 需要 snapshot_id,且当前图谱没有可用快照")
810
+ snapshot_id = snapshots[-1]["snapshot_id"]
811
+ restored = graph.rollback_to_snapshot(snapshot_id)
812
+ if not restored:
813
+ raise AttackGraphStoreError(f"快照不存在,无法回滚: {snapshot_id}")
814
+ rollbacks = graph.reflex.setdefault("rollbacks", [])
815
+ rollbacks.append({
816
+ "snapshot_id": snapshot_id,
817
+ "reason": _text(payload.get("reason")) or "explicit",
818
+ "rolled_back": True,
819
+ "at": time.time(),
820
+ })
821
+ del rollbacks[:-_ag.MAX_ROLLBACK_LOG]
822
+ return {"snapshot_id": snapshot_id, "restored": True}
823
+
824
+
825
+ def _on_role(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
826
+ role_id = _text(payload.get("role_id") or payload.get("id")) or "role:anonymous"
827
+ role_type = _text(payload.get("type") or payload.get("role_type") or "unknown")
828
+ attrs = {
829
+ key: value
830
+ for key, value in payload.items()
831
+ if key in {"tenant_id", "privilege", "credential_source", "worker_id", "description"}
832
+ and value is not None
833
+ }
834
+ if role_id in graph.roles:
835
+ _merge_node(graph, "roles", role_id, type=role_type, **attrs)
836
+ else:
837
+ graph.add_role(role_id, role_type, **attrs)
838
+ unit = _text(payload.get(UNIT_ATTR) or payload.get("unit_id"))
839
+ if unit:
840
+ stamp_unit(graph, unit, roles=[role_id], advanced_by=payload.get(ADVANCED_BY_ATTR),
841
+ round_no=ctx.get("round_no"))
842
+ return {"role_id": role_id, "role_total": len(graph.roles)}
843
+
844
+
845
+ def _on_unit_stamped(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
846
+ unit = _text(payload.get("unit_id")) or _text(payload.get("id"))
847
+ if not unit:
848
+ raise AttackGraphStoreError("unit_stamped 需要 unit_id")
849
+ extra = {
850
+ key: value
851
+ for key, value in payload.items()
852
+ if key in {"phase", "parent", "name", "path", "risk", "severity", "tool", "source"}
853
+ and value is not None
854
+ }
855
+ record = stamp_unit(
856
+ graph, unit,
857
+ routes=_texts(payload.get("routes")),
858
+ sinks=_texts(payload.get("sinks")),
859
+ hypotheses=_texts(payload.get("hypotheses")),
860
+ advanced_by=payload.get("worker_id") or payload.get(ADVANCED_BY_ATTR),
861
+ round_no=payload.get("round_no") if isinstance(payload.get("round_no"), int) else ctx.get("round_no"),
862
+ stage_id=_text(payload.get("stage_id")) or None,
863
+ tested_stages=_texts(payload.get("tested_stages")),
864
+ **extra,
865
+ )
866
+ return {"unit_id": unit, "nodes": record.get("node_total", 0)}
867
+
868
+
869
+ def _on_unit_covered(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
870
+ unit = _text(payload.get("unit_id"))
871
+ if not unit:
872
+ raise AttackGraphStoreError("unit_covered 需要 unit_id")
873
+ status = _text(payload.get("status")) or "covered"
874
+ known: list[str] = []
875
+ units = graph.meta.get("units")
876
+ if isinstance(units, dict):
877
+ entry = units.get(unit)
878
+ nodes = entry.get("nodes") if isinstance(entry, Mapping) else None
879
+ if isinstance(nodes, Mapping):
880
+ known = _texts(nodes.get("routes"))
881
+ route_ids = _texts(payload.get("routes")) or known
882
+ stage = _text(payload.get("stage_id"))
883
+ touched = 0
884
+ for route_id in route_ids:
885
+ node = graph.routes.get(route_id)
886
+ if not isinstance(node, dict):
887
+ continue
888
+ node["coverage_status"] = status
889
+ if stage:
890
+ node["tested_stages"] = sorted(set(_texts(node.get("tested_stages")) + [stage]))
891
+ touched += 1
892
+ record = stamp_unit(
893
+ graph, unit,
894
+ routes=route_ids,
895
+ advanced_by=payload.get("worker_id"),
896
+ round_no=payload.get("round_no") if isinstance(payload.get("round_no"), int) else ctx.get("round_no"),
897
+ stage_id=stage or None,
898
+ tested_stages=[stage] if stage else None,
899
+ coverage_status=status,
900
+ )
901
+ record["covered"] = True
902
+ return {"unit_id": unit, "routes_touched": touched, "status": status}
903
+
904
+
905
+ def _on_evidence_checkpointed(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
906
+ unit = _text(payload.get("unit_id"))
907
+ if not unit:
908
+ raise AttackGraphStoreError("evidence_checkpointed 需要 unit_id")
909
+ record = stamp_unit(
910
+ graph, unit,
911
+ routes=_texts(payload.get("routes")),
912
+ sinks=_texts(payload.get("sink_ids")),
913
+ hypotheses=_texts(payload.get("hypothesis_ids")),
914
+ advanced_by=payload.get("worker_id"),
915
+ round_no=payload.get("round_no") if isinstance(payload.get("round_no"), int) else ctx.get("round_no"),
916
+ evidence_status=_text(payload.get("status")) or "unknown",
917
+ artifact_path=_text(payload.get("artifact_path")),
918
+ target_fingerprint=_text(payload.get("target_fingerprint")),
919
+ )
920
+ return {"unit_id": unit, "evidence_status": record.get("evidence_status")}
921
+
922
+
923
+ def _on_graph_seeded(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
924
+ """pre 阶段播种汇总事件:只在 ``meta`` 上打水位,节点由具体事件负责。"""
925
+ summary = payload.get("summary") if isinstance(payload.get("summary"), Mapping) else payload
926
+ graph.meta["seed_summary"] = {
927
+ key: value for key, value in dict(summary or {}).items()
928
+ if isinstance(value, (int, float, str, bool))
929
+ }
930
+ graph.meta["seeded_round"] = ctx.get("round_no")
931
+ return {"seeded_round": ctx.get("round_no"), "unit_total": len(graph.meta.get("units") or {})}
932
+
933
+
934
+ def _on_graph_absorbed(graph: LivingAttackGraph, payload: Mapping[str, Any], ctx: dict) -> dict:
935
+ """post 阶段整轮吸收汇总:留一份逐轮水位,供消费者判断图谱是否在真实演化。"""
936
+ history = graph.meta.setdefault("absorb_history", [])
937
+ if not isinstance(history, list):
938
+ history = []
939
+ graph.meta["absorb_history"] = history
940
+ history.append({
941
+ "round": ctx.get("round_no"),
942
+ "at": time.time(),
943
+ **{
944
+ key: value for key, value in payload.items()
945
+ if isinstance(value, (int, float, str, bool))
946
+ },
947
+ })
948
+ del history[-200:]
949
+ graph.meta["absorb_count"] = len(history)
950
+ graph.meta["verified_count"] = sum(1 for h in history if h.get("verified"))
951
+ return {"round": ctx.get("round_no"), "absorb_total": len(history)}
952
+
953
+
954
+ EVENT_HANDLERS: dict[str, Callable[[LivingAttackGraph, Mapping[str, Any], dict], dict[str, Any]]] = {
955
+ EVENT_ENDPOINT_DISCOVERED: _on_endpoint,
956
+ EVENT_ENDPOINTS_READY: _on_endpoints_ready,
957
+ EVENT_SINK_FOUND: _on_sink,
958
+ EVENT_HYPOTHESIS_PROPOSED: _on_hypothesis_proposed,
959
+ EVENT_HYPOTHESIS_VERIFIED: _on_hypothesis_verified,
960
+ EVENT_HYPOTHESIS_REJECTED: _on_hypothesis_rejected,
961
+ EVENT_ROLLBACK: _on_rollback,
962
+ EVENT_ROLE_OBSERVED: _on_role,
963
+ EVENT_UNIT_STAMPED: _on_unit_stamped,
964
+ EVENT_UNIT_COVERED: _on_unit_covered,
965
+ EVENT_EVIDENCE_CHECKPOINTED: _on_evidence_checkpointed,
966
+ EVENT_GRAPH_SEEDED: _on_graph_seeded,
967
+ EVENT_GRAPH_ABSORBED: _on_graph_absorbed,
968
+ }
969
+
970
+
971
+ # --------------------------------------------------------------------------
972
+ # 事件写入主入口
973
+ # --------------------------------------------------------------------------
974
+
975
+ def _journal(
976
+ graph: LivingAttackGraph, event_type: str, body: Mapping[str, Any],
977
+ result: Mapping[str, Any], ctx: Mapping[str, Any],
978
+ ) -> dict[str, Any]:
979
+ record: dict[str, Any] = {
980
+ "seq": len(graph.events) + 1,
981
+ "event_type": event_type,
982
+ "timestamp": time.time(),
983
+ # 批量端点列表只进图谱节点,不进日志:否则 events 上限会被一次
984
+ # endpoints_ready 全部吃掉,后面的假设裁决一条都留不下。
985
+ "payload": {k: v for k, v in body.items() if k not in {"endpoints", "surfaces"}},
986
+ "result": dict(result),
987
+ }
988
+ if body.get("unit_id") is not None:
989
+ record["unit_id"] = _text(body.get("unit_id"))
990
+ if isinstance(ctx.get("round_no"), int):
991
+ record["round"] = ctx["round_no"]
992
+ graph.events.append(record)
993
+ graph.events = graph.events[-_ag.MAX_EVENT_JOURNAL:]
994
+ counts = graph.meta.setdefault("event_counts", {})
995
+ if isinstance(counts, dict):
996
+ counts[event_type] = counts.get(event_type, 0) + 1
997
+ graph.meta["events_recorded"] = len(graph.events)
998
+ if isinstance(ctx.get("round_no"), int):
999
+ graph.meta["last_round"] = ctx["round_no"]
1000
+ return record
1001
+
1002
+
1003
+ def record_events(
1004
+ project_root: str | Path,
1005
+ operations: Iterable[tuple[str, Mapping[str, Any] | None] | Mapping[str, Any]],
1006
+ ) -> list[dict[str, Any]]:
1007
+ """批量事件写入:一次 load → N 次变更 → **一次** 原子落盘。
1008
+
1009
+ 必须存在批量入口,否则 ``absorb_findings`` 之类的整轮吸收会退化成"每条事件重写
1010
+ 一次全图",几百个端点就是几百次快照 fsync——图谱生产会在 pre/post 里变成流水线
1011
+ 最慢的一环。
1012
+ """
1013
+ prepared: list[tuple[str, dict[str, Any], Callable]] = []
1014
+ for item in operations or []:
1015
+ if isinstance(item, Mapping):
1016
+ event_type, raw_payload = _text(item.get("event_type")), item
1017
+ else:
1018
+ event_type, raw_payload = _text(item[0]), item[1]
1019
+ handler = EVENT_HANDLERS.get(event_type)
1020
+ if handler is None:
1021
+ raise AttackGraphStoreError(
1022
+ f"未知的攻击图谱事件类型: {event_type!r};已注册: {sorted(EVENT_HANDLERS)}"
1023
+ )
1024
+ body = dict(raw_payload or {})
1025
+ prepared.append((event_type, body, handler))
1026
+ if not prepared:
1027
+ return []
1028
+ directory = graph_dir(project_root)
1029
+ with _store_lock(directory):
1030
+ graph = load_graph(project_root)
1031
+ cold_start = graph is None
1032
+ if cold_start:
1033
+ graph = _new_graph(Path(project_root).expanduser())
1034
+ graph.meta["cold_start"] = cold_start
1035
+ records: list[dict[str, Any]] = []
1036
+ for event_type, body, handler in prepared:
1037
+ ctx = {
1038
+ "cold_start": cold_start,
1039
+ "round_no": body.get("round_no") if isinstance(body.get("round_no"), int)
1040
+ else graph.meta.get("last_round"),
1041
+ }
1042
+ # 总线先行:DOC-125 的"资产发现即刻可被订阅者消费"语义,不等落盘。
1043
+ graph.event_bus.publish(event_type, body)
1044
+ result = handler(graph, body, ctx) or {}
1045
+ records.append(_journal(graph, event_type, body, result, ctx))
1046
+ _write_graph_locked(directory, graph)
1047
+ return records
1048
+
1049
+
1050
+ def record_event(
1051
+ project_root: str | Path,
1052
+ event_type: str,
1053
+ payload: Mapping[str, Any] | None,
1054
+ ) -> dict[str, Any]:
1055
+ """落盘一次图谱演化:load(或冷启动)→ 发布总线 → 变更图谱 → save → 返回事件记录。
1056
+
1057
+ 未注册的 ``event_type`` 一律 :class:`AttackGraphStoreError`(拼错事件名必须响,
1058
+ 而不是静默产生一个"看起来成功"的空事件)。
1059
+ """
1060
+ records = record_events(project_root, [(event_type, payload)])
1061
+ if not records:
1062
+ raise AttackGraphStoreError(f"事件未被记录: {event_type!r}")
1063
+ return records[0]
1064
+
1065
+
1066
+ # --------------------------------------------------------------------------
1067
+ # 流水线胶水:pre 播种 / post 吸收
1068
+ # --------------------------------------------------------------------------
1069
+
1070
+ def seed_from_units(
1071
+ project_root: str | Path,
1072
+ units: Iterable[Any],
1073
+ *,
1074
+ round_no: int | None = None,
1075
+ source: str = "coverage-manifest",
1076
+ ) -> dict[str, Any]:
1077
+ """pre 阶段播种:把可调度的覆盖单元登记进图谱(幂等,冷启动也可用)。"""
1078
+ operations: list[tuple[str, dict[str, Any]]] = []
1079
+ skipped = 0
1080
+ for item in units or []:
1081
+ if isinstance(item, Mapping):
1082
+ unit_id = _text(item.get("unit_id") or item.get("id"))
1083
+ attrs = {
1084
+ key: value
1085
+ for key, value in item.items()
1086
+ if key in {"phase", "parent", "name", "path", "risk", "tool", "status"}
1087
+ and value is not None
1088
+ }
1089
+ else:
1090
+ unit_id = _text(item)
1091
+ attrs = {}
1092
+ if not unit_id:
1093
+ skipped += 1
1094
+ continue
1095
+ operations.append((EVENT_UNIT_STAMPED, {
1096
+ "unit_id": unit_id, "round_no": round_no, "source": source, **attrs,
1097
+ }))
1098
+ seeded = len(operations)
1099
+ summary = {
1100
+ "seeded_units": seeded,
1101
+ "skipped_units": skipped,
1102
+ "round_no": round_no,
1103
+ "surface_ready": False,
1104
+ }
1105
+ operations.append((EVENT_GRAPH_SEEDED, {
1106
+ "round_no": round_no, "summary": summary, "source": source,
1107
+ }))
1108
+ record_events(project_root, operations)
1109
+ return summary
1110
+
1111
+
1112
+ def absorb_surface(
1113
+ project_root: str | Path,
1114
+ surfaces: Iterable[Mapping[str, Any]],
1115
+ *,
1116
+ unit_id: str | None = None,
1117
+ round_no: int | None = None,
1118
+ ) -> dict[str, Any]:
1119
+ """把 :func:`module_coverage.extract_feature_surface` 的切面灌成端点节点。
1120
+
1121
+ 逐条 ``endpoint_discovered`` + 一次 ``endpoints_ready``:前者让调度器可以增量
1122
+ 排期,后者是"本轮面已完整"的栅栏信号。已在图里的端点不再重复记日志——pre 每个
1123
+ Round 都会跑,否则事件日志会被同一批静态端点反复灌满,把真正的假设裁决挤出上限。
1124
+ """
1125
+ rows = [dict(item) for item in surfaces or [] if isinstance(item, Mapping)]
1126
+ known = set()
1127
+ existing = load_graph(project_root)
1128
+ if existing is not None:
1129
+ known = set(existing.routes)
1130
+ operations: list[tuple[str, dict[str, Any]]] = []
1131
+ for row in rows:
1132
+ payload = {
1133
+ "name": row.get("name"),
1134
+ "method": row.get("method"),
1135
+ "path": row.get("path"),
1136
+ "source_file": row.get("source_file"),
1137
+ "line": row.get("line"),
1138
+ "framework": row.get("framework"),
1139
+ "round_no": round_no,
1140
+ }
1141
+ if unit_id:
1142
+ payload["unit_id"] = unit_id
1143
+ if _route_id_of(payload) in known:
1144
+ continue
1145
+ operations.append((EVENT_ENDPOINT_DISCOVERED, payload))
1146
+ operations.append((EVENT_ENDPOINTS_READY, {
1147
+ "endpoints": [], "count": len(rows), "unit_id": unit_id, "round_no": round_no,
1148
+ }))
1149
+ record_events(project_root, operations)
1150
+ return {"endpoints_emitted": len(operations) - 1, "surface_total": len(rows)}
1151
+
1152
+
1153
+ def absorb_sinks(
1154
+ project_root: str | Path,
1155
+ sinks: Iterable[Mapping[str, Any]],
1156
+ *,
1157
+ round_no: int | None = None,
1158
+ ) -> dict[str, Any]:
1159
+ """把静态分析(SAST/CodeAnalyzer)发现的敏感 Sinks 灌成汇点节点。
1160
+
1161
+ 如果提供 unit_id 或 route_id,则建立相应的关联边。
1162
+ 已在图里的汇点合并属性,不重复发送相同日志。
1163
+ """
1164
+ rows = [dict(item) for item in sinks or [] if isinstance(item, Mapping)]
1165
+ known = set()
1166
+ existing = load_graph(project_root)
1167
+ if existing is not None:
1168
+ known = set(existing.sinks)
1169
+ operations: list[tuple[str, dict[str, Any]]] = []
1170
+ for row in rows:
1171
+ payload = {
1172
+ "kind": _text(row.get("kind") or row.get("sink_type") or "unknown"),
1173
+ "sink": _text(row.get("sink") or row.get("name") or row.get("rule_id")),
1174
+ "location": _text(row.get("location") or row.get("source_file") or row.get("file")),
1175
+ "source_file": _text(row.get("source_file") or row.get("file")),
1176
+ "line": row.get("line") if isinstance(row.get("line"), int) else None,
1177
+ "severity": _text(row.get("severity")) or "high",
1178
+ "round_no": round_no,
1179
+ "unit_id": _text(row.get("unit_id")) or None,
1180
+ "route_id": _text(row.get("route_id")) or None,
1181
+ }
1182
+ sink_id = _sink_id_of(payload)
1183
+ if sink_id in known:
1184
+ continue
1185
+ operations.append((EVENT_SINK_FOUND, payload))
1186
+ known.add(sink_id)
1187
+ if operations:
1188
+ record_events(project_root, operations)
1189
+ return {"sinks_emitted": len(operations), "sinks_total": len(rows)}
1190
+
1191
+
1192
+ def _finding_is_verified(finding: Mapping[str, Any]) -> bool:
1193
+ confirmation = finding.get("confirmation")
1194
+ state = _text(confirmation.get("state")) if isinstance(confirmation, Mapping) else ""
1195
+ if state == "confirmed":
1196
+ return True
1197
+ if state == "rejected":
1198
+ return False
1199
+ status = _text(finding.get("status") or finding.get("state") or finding.get("verdict"))
1200
+ if status in {"confirmed", "verified", "reproduced", "real"}:
1201
+ return True
1202
+ if status in {"rejected", "refuted", "false_positive", "invalid"}:
1203
+ return False
1204
+ # 未确认且没有明确拒绝:按"待验证"处理,既不实锤也不反驳。
1205
+ return False
1206
+
1207
+
1208
+ def _finding_is_rejected(finding: Mapping[str, Any]) -> bool:
1209
+ confirmation = finding.get("confirmation")
1210
+ state = _text(confirmation.get("state")) if isinstance(confirmation, Mapping) else ""
1211
+ if state == "rejected":
1212
+ return True
1213
+ return _text(finding.get("status") or finding.get("state") or finding.get("verdict")) in {
1214
+ "rejected", "refuted", "false_positive", "invalid",
1215
+ }
1216
+
1217
+
1218
+ # 只登记**真正的危险汇聚点**(污点最终被消费的位置)。IDOR / 越权 / 凭证提升属于访问
1219
+ # 控制缺陷,没有 sink;把它们塞进汇点表会让 ``find_entrypoints_for_sink`` 的反向污点
1220
+ # 推演凭空产出假链路,并给 ``evaluate_runnable_tasks`` 打上假的 priority=100。
1221
+ _SINK_HINTS = {
1222
+ "sql": "sql", "sqli": "sql", "injection": "injection", "inject": "injection",
1223
+ "rce": "cmd", "command inject": "cmd", "cmd inject": "cmd", "exec": "cmd",
1224
+ "ssti": "template", "xss": "html", "deserialization": "deserialize",
1225
+ "file upload": "file", "path traversal": "file", "arbitrary file": "file",
1226
+ "ssrf": "network", "xxe": "xml", "ldap": "ldap", "xpath": "xpath",
1227
+ }
1228
+
1229
+
1230
+ def _sink_kind_of(finding: Mapping[str, Any]) -> str:
1231
+ blob = " ".join(
1232
+ _text(finding.get(key))
1233
+ for key in ("vulnerability_type", "type", "category", "root_cause", "title", "trigger_condition")
1234
+ ).lower()
1235
+ for hint, kind in _SINK_HINTS.items():
1236
+ if hint in blob:
1237
+ return kind
1238
+ return ""
1239
+
1240
+
1241
+ def absorb_findings(
1242
+ project_root: str | Path,
1243
+ findings: Iterable[Mapping[str, Any]],
1244
+ *,
1245
+ round_no: int | None = None,
1246
+ worker_id: str | None = None,
1247
+ ) -> dict[str, Any]:
1248
+ """post 阶段吸收结算后的 findings:实锤 → verified,拒绝 → 反思回溯 + 回滚。
1249
+
1250
+ 待确认(candidate)的 finding 只登记为假设,不裁决——把"没验证过"伪装成
1251
+ "已反驳"会污染回溯历史与 DPO 语料。
1252
+ """
1253
+ verified = 0
1254
+ rejected = 0
1255
+ proposed = 0
1256
+ sinks = 0
1257
+ operations: list[tuple[str, dict[str, Any]]] = []
1258
+ existing = load_graph(project_root)
1259
+ known_routes = set(existing.routes) if existing is not None else set()
1260
+ for finding in findings or []:
1261
+ if not isinstance(finding, Mapping):
1262
+ continue
1263
+ unit_id = _text(finding.get("unit_id") or finding.get("coverage_unit")) or None
1264
+ payload: dict[str, Any] = {
1265
+ "finding_id": _text(finding.get("id") or finding.get("fingerprint")),
1266
+ "target": _text(finding.get("target") or finding.get("endpoint") or finding.get("route_id")),
1267
+ "type": _text(finding.get("vulnerability_type") or finding.get("category")) or "business",
1268
+ "title": _text(finding.get("title")) or None,
1269
+ "root_cause": _text(finding.get("root_cause")) or None,
1270
+ "severity": _text(finding.get("severity")) or None,
1271
+ "confidence": finding.get("confidence") if isinstance(finding.get("confidence"), (int, float)) else None,
1272
+ "unit_id": unit_id,
1273
+ "advanced_by": _text(finding.get("worker_id")) or (worker_id or None),
1274
+ "round_no": round_no,
1275
+ "status_code": finding.get("status_code") if isinstance(finding.get("status_code"), int) else None,
1276
+ "response_body": _text(finding.get("response_body") or finding.get("reproduction"))[:2000],
1277
+ }
1278
+ evidence = finding.get("evidence")
1279
+ if isinstance(evidence, list) and evidence and isinstance(evidence[0], Mapping):
1280
+ payload["source_file"] = _text(evidence[0].get("path")) or None
1281
+ payload["line"] = evidence[0].get("line") if isinstance(evidence[0].get("line"), int) else None
1282
+ if not payload["target"]:
1283
+ payload["target"] = _text(evidence[0].get("url") or evidence[0].get("endpoint"))
1284
+ kind = _sink_kind_of(finding)
1285
+ sink_row = {
1286
+ "kind": kind,
1287
+ "location": payload.get("source_file") or payload.get("finding_id") or kind,
1288
+ "line": payload.get("line"),
1289
+ "source_file": payload.get("source_file"),
1290
+ "severity": payload.get("severity"),
1291
+ "unit_id": unit_id,
1292
+ "advanced_by": payload.get("advanced_by"),
1293
+ "round_no": round_no,
1294
+ }
1295
+ if _finding_is_verified(finding):
1296
+ outcome = "verified"
1297
+ elif _finding_is_rejected(finding):
1298
+ outcome = "rejected"
1299
+ else:
1300
+ outcome = "proposed"
1301
+ if kind and outcome != "rejected":
1302
+ # 实锤/待验证的汇点作为独立事件入图;被反驳的交给下面的 speculative,
1303
+ # 由回溯环在回滚时一起撤销——否则图里会留着一条"死假设"的汇点误导调度。
1304
+ operations.append((EVENT_SINK_FOUND, dict(sink_row)))
1305
+ sinks += 1
1306
+ if outcome == "verified":
1307
+ operations.append((EVENT_HYPOTHESIS_VERIFIED, dict(payload)))
1308
+ verified += 1
1309
+ elif outcome == "rejected":
1310
+ speculative = [dict(sink_row, speculative=True)] if kind else []
1311
+ target = _text(payload.get("target"))
1312
+ target_route = _route_id_of({"route_id": target}) if target else ""
1313
+ if target_route and target_route not in known_routes:
1314
+ speculative.append({"route_id": target, "method": "GET"})
1315
+ operations.append((EVENT_HYPOTHESIS_REJECTED, {
1316
+ **payload, "terminal": True, "speculative": speculative,
1317
+ }))
1318
+ rejected += 1
1319
+ else:
1320
+ operations.append((EVENT_HYPOTHESIS_PROPOSED, {**payload, "status": "proposed"}))
1321
+ proposed += 1
1322
+ record_events(project_root, operations)
1323
+ return {
1324
+ "verified": verified,
1325
+ "rejected": rejected,
1326
+ "proposed": proposed,
1327
+ "sinks": sinks,
1328
+ "finding_total": verified + rejected + proposed,
1329
+ }
1330
+
1331
+
1332
+ def absorb_evidence(
1333
+ project_root: str | Path,
1334
+ records: Iterable[Mapping[str, Any]],
1335
+ *,
1336
+ round_no: int | None = None,
1337
+ stage_id: str | None = None,
1338
+ ) -> dict[str, Any]:
1339
+ """吸收 Life 已检查点的覆盖证据:把单元→端点链路补全,供 DAG 求值消费。"""
1340
+ operations: list[tuple[str, dict[str, Any]]] = []
1341
+ for record in records or []:
1342
+ if not isinstance(record, Mapping):
1343
+ continue
1344
+ unit_id = _text(record.get("unit_id"))
1345
+ if not unit_id:
1346
+ continue
1347
+ worker = _text(record.get("worker_id")) or None
1348
+ operations.append((EVENT_EVIDENCE_CHECKPOINTED, {
1349
+ "unit_id": unit_id,
1350
+ "worker_id": worker,
1351
+ "status": _text(record.get("status")) or None,
1352
+ "artifact_path": _text(record.get("artifact_path")) or None,
1353
+ "target_fingerprint": _text(record.get("target_fingerprint")) or None,
1354
+ "round_no": round_no,
1355
+ }))
1356
+ operations.append((EVENT_UNIT_COVERED, {
1357
+ "unit_id": unit_id,
1358
+ "status": _text(record.get("status")) or "covered",
1359
+ "stage_id": stage_id,
1360
+ "worker_id": worker,
1361
+ "round_no": round_no,
1362
+ }))
1363
+ absorbed = len(operations) // 2
1364
+ record_events(project_root, operations)
1365
+ return {"units_absorbed": absorbed}
1366
+
1367
+
1368
+ def finalize_round(
1369
+ project_root: str | Path,
1370
+ summary: Mapping[str, Any],
1371
+ *,
1372
+ round_no: int | None = None,
1373
+ ) -> dict[str, Any]:
1374
+ """把本轮吸收结果作为一条汇总事件写进日志(观测与断点续跑用)。"""
1375
+ return record_event(project_root, EVENT_GRAPH_ABSORBED, {
1376
+ "round_no": round_no, **dict(summary),
1377
+ })
1378
+
1379
+
1380
+ # --------------------------------------------------------------------------
1381
+ # 反射回溯 / 就地重放的可达入口
1382
+ # --------------------------------------------------------------------------
1383
+
1384
+ def reflex_state(project_root: str | Path) -> dict[str, Any]:
1385
+ """回溯状态快照:历史、回滚审计、待重放计划与自动修包建议。"""
1386
+ graph = load_graph(project_root)
1387
+ if graph is None:
1388
+ return {"present": False}
1389
+ history = graph.reflex.get("backtrack_history") if isinstance(graph.reflex, Mapping) else {}
1390
+ return {
1391
+ "present": True,
1392
+ "backtrack_history": {
1393
+ hyp_id: len(records) for hyp_id, records in (history or {}).items()
1394
+ if isinstance(records, list)
1395
+ },
1396
+ "rollbacks": list(graph.reflex.get("rollbacks") or [])[-20:],
1397
+ "replay_pending": list(graph.reflex.get("replay_pending") or []),
1398
+ "auto_fix_suggestions": len(graph.reflex.get("auto_fix_suggestions") or []),
1399
+ "snapshots": graph.list_snapshots(),
1400
+ "schema_validation": dict(graph.meta.get("schema_validation") or {}),
1401
+ }
1402
+
1403
+
1404
+ def replay_reflex_fix(
1405
+ project_root: str | Path,
1406
+ hypothesis_id: str,
1407
+ sender_fn: Callable[[dict[str, Any]], Mapping[str, Any]],
1408
+ *,
1409
+ patch_headers: Mapping[str, Any] | None = None,
1410
+ target_fingerprint: str | None = None,
1411
+ ) -> dict[str, Any]:
1412
+ """执行一次就地免 LLM 快速重放(优化项 10),并把结果记进图谱。
1413
+
1414
+ 本模块自己**不发包**:``sender_fn`` 由持有沙箱网络栈的调用方(worker / MCP 面)
1415
+ 注入。post 路径只负责离线地产出 ``reflex["replay_pending"]`` 计划。调用方还必须
1416
+ 在 callback 上设置由当前 Supervisor/沙箱产生的 ``target_fingerprint``;缺失或不匹配
1417
+ 时 fail-closed,并保留待重放计划供正确目标重试。
1418
+ """
1419
+ if not callable(sender_fn):
1420
+ raise AttackGraphStoreError("replay_reflex_fix 需要可调用的 sender_fn")
1421
+ root = graph_dir(project_root)
1422
+ with _store_lock(root):
1423
+ graph = load_graph(project_root)
1424
+ if graph is None:
1425
+ raise AttackGraphStoreError("图谱尚未建立,无法执行就地重放")
1426
+ hyp_id = _text(hypothesis_id)
1427
+ headers = dict(patch_headers or {})
1428
+ pending_item: Mapping[str, Any] | None = None
1429
+ for item in reversed(list(graph.reflex.get("replay_pending") or [])):
1430
+ if isinstance(item, Mapping) and _text(item.get("hypothesis_id")) == hyp_id:
1431
+ pending_item = item
1432
+ if not headers:
1433
+ headers = dict(item.get("patch_headers") or {})
1434
+ break
1435
+ requested_target = _text(target_fingerprint)
1436
+ plan_target = _text(pending_item.get("target_fingerprint")) if pending_item else ""
1437
+ expected_target = plan_target or ("" if pending_item is not None else requested_target)
1438
+ binding_error = ""
1439
+ if pending_item is not None and requested_target and requested_target != plan_target:
1440
+ binding_error = "调用方 target_fingerprint 与待重放计划不匹配"
1441
+ try:
1442
+ bound_target = _text(getattr(sender_fn, "target_fingerprint", ""))
1443
+ except Exception:
1444
+ bound_target = ""
1445
+ if binding_error:
1446
+ outcome = {
1447
+ "fast_replay_attempted": False,
1448
+ "success": False,
1449
+ "action": "blocked_target_binding",
1450
+ "error": binding_error,
1451
+ }
1452
+ elif not expected_target:
1453
+ outcome = {
1454
+ "fast_replay_attempted": False,
1455
+ "success": False,
1456
+ "action": "blocked_target_binding",
1457
+ "error": "重放计划缺少 target_fingerprint",
1458
+ }
1459
+ elif bound_target != expected_target:
1460
+ outcome = {
1461
+ "fast_replay_attempted": False,
1462
+ "success": False,
1463
+ "action": "blocked_target_binding",
1464
+ "error": "sender_fn 的 target_fingerprint 与重放目标不匹配",
1465
+ }
1466
+ else:
1467
+ engine = ReflexiveBacktrackingEngine(graph)
1468
+ outcome = engine.execute_in_situ_fast_replay(
1469
+ hyp_id,
1470
+ headers,
1471
+ sender_fn,
1472
+ target_fingerprint=expected_target,
1473
+ )
1474
+ node = graph.hypotheses.get(hyp_id)
1475
+ if isinstance(node, dict):
1476
+ node["fast_replay"] = {
1477
+ key: value for key, value in dict(outcome).items() if key != "advice"
1478
+ }
1479
+ node["fast_replay"]["at"] = time.time()
1480
+ pending = graph.reflex.setdefault("replay_pending", [])
1481
+ if outcome.get("action") != "blocked_target_binding":
1482
+ graph.reflex["replay_pending"] = [
1483
+ item for item in pending
1484
+ if not (isinstance(item, Mapping) and _text(item.get("hypothesis_id")) == hyp_id)
1485
+ ]
1486
+ record = {
1487
+ "seq": len(graph.events) + 1,
1488
+ "event_type": "fast_replay",
1489
+ "timestamp": time.time(),
1490
+ "payload": {
1491
+ "hypothesis_id": hyp_id,
1492
+ "patch_headers": headers,
1493
+ "target_fingerprint": expected_target or None,
1494
+ },
1495
+ "result": dict(outcome),
1496
+ }
1497
+ graph.events.append(record)
1498
+ graph.events = graph.events[-_ag.MAX_EVENT_JOURNAL:]
1499
+ _write_graph_locked(root, graph)
1500
+ return {**dict(outcome), "event": record}
1501
+
1502
+
1503
+ def runnable_tasks(
1504
+ project_root: str | Path,
1505
+ completed_stages: Iterable[str] | None = None,
1506
+ ) -> list[dict[str, Any]]:
1507
+ """按图谱当前拓扑求值流式 DAG 可执行任务(优化项 1)。"""
1508
+ graph = load_graph(project_root)
1509
+ if graph is None:
1510
+ return []
1511
+ return _ag.evaluate_runnable_tasks(graph, set(_texts(completed_stages)))
1512
+
1513
+
1514
+ def stats(project_root: str | Path) -> dict[str, Any]:
1515
+ """图谱可观测概况(供 ``bugx skill status`` / MCP 面展示)。"""
1516
+ graph = load_graph(project_root)
1517
+ if graph is None:
1518
+ return {"present": False, "snapshot": str(snapshot_path(project_root))}
1519
+ illegal = graph.get_illegal_access_edges()
1520
+ return {
1521
+ "present": True,
1522
+ "snapshot": str(snapshot_path(project_root)),
1523
+ "version": graph.version,
1524
+ "nodes": {
1525
+ "roles": len(graph.roles),
1526
+ "routes": len(graph.routes),
1527
+ "parameters": len(graph.parameters),
1528
+ "sinks": len(graph.sinks),
1529
+ "hypotheses": len(graph.hypotheses),
1530
+ },
1531
+ "edges": len(graph.edges),
1532
+ "illegal_access_edges": len(illegal),
1533
+ "events": len(graph.events),
1534
+ "last_event": graph.events[-1]["event_type"] if graph.events else None,
1535
+ "units": len(graph.meta.get("units") or {}),
1536
+ "last_round": graph.meta.get("last_round"),
1537
+ "endpoints_ready": bool(graph.meta.get("endpoints_ready")),
1538
+ "schema_validation": dict(graph.meta.get("schema_validation") or {}),
1539
+ "backtrack_hypotheses": len(graph.reflex.get("backtrack_history") or {}),
1540
+ "rollbacks": len(graph.reflex.get("rollbacks") or []),
1541
+ }
1542
+
1543
+
1544
+ def _extract_text_from_jsonl_stream(lines: list[str]) -> str | None:
1545
+ """从多行 JSON Lines (NDJSON) 事件流中智能聚合 AI Agent 输出的正文文本。
1546
+
1547
+ 支持 Cline (run_result / agent_event), OpenCode (text part streaming), Codex 等。
1548
+ """
1549
+ # 策略 A: 检查是否存在运行终结结果 (Cline run_result / done, Codex final)
1550
+ for line in reversed(lines):
1551
+ try:
1552
+ obj = json.loads(line)
1553
+ if isinstance(obj, dict):
1554
+ # Cline run_result
1555
+ if obj.get("type") == "run_result" and isinstance(obj.get("text"), str):
1556
+ return obj["text"]
1557
+ # Cline agent_event done
1558
+ if obj.get("type") == "agent_event":
1559
+ ev = obj.get("event")
1560
+ if isinstance(ev, dict) and ev.get("type") == "done" and isinstance(ev.get("text"), str):
1561
+ return ev["text"]
1562
+ # Codex or other run result
1563
+ if "result" in obj and isinstance(obj["result"], str):
1564
+ return obj["result"]
1565
+ except Exception:
1566
+ continue
1567
+
1568
+ # 策略 B: 汇聚 OpenCode 或流式增量文本 (opencode text parts)
1569
+ opencode_parts: list[str] = []
1570
+ has_opencode = False
1571
+ for line in lines:
1572
+ try:
1573
+ obj = json.loads(line)
1574
+ if isinstance(obj, dict) and obj.get("type") == "text":
1575
+ part = obj.get("part")
1576
+ if isinstance(part, dict) and isinstance(part.get("text"), str):
1577
+ opencode_parts.append(part["text"])
1578
+ has_opencode = True
1579
+ except Exception:
1580
+ continue
1581
+ if has_opencode and opencode_parts:
1582
+ return "".join(opencode_parts)
1583
+
1584
+ # 策略 C: Codex item/message stream
1585
+ codex_parts: list[str] = []
1586
+ has_codex = False
1587
+ for line in lines:
1588
+ try:
1589
+ obj = json.loads(line)
1590
+ if isinstance(obj, dict) and obj.get("type") in ("message", "item.created", "item.updated"):
1591
+ item = obj.get("item") if "item" in obj else obj
1592
+ if isinstance(item, dict):
1593
+ content = item.get("content")
1594
+ if isinstance(content, list):
1595
+ for c in content:
1596
+ if isinstance(c, dict) and c.get("type") == "text" and isinstance(c.get("text"), str):
1597
+ codex_parts.append(c["text"])
1598
+ has_codex = True
1599
+ elif isinstance(content, str):
1600
+ codex_parts.append(content)
1601
+ has_codex = True
1602
+ except Exception:
1603
+ continue
1604
+ if has_codex and codex_parts:
1605
+ return "".join(codex_parts)
1606
+
1607
+ return None
1608
+
1609
+
1610
+ def _repair_and_load_json(s: str) -> dict | list | None:
1611
+ """词法栈括号自愈与尾随逗号消除器。"""
1612
+ # 针对模型漏掉最外层大括号的情况(如开头就是 "key": ...)
1613
+ if ":" in s and not s.lstrip().startswith("{") and not s.lstrip().startswith("["):
1614
+ wrapped = "{\n" + s.strip().rstrip("}") + "\n}"
1615
+ cleaned = re.sub(r",\s*([\]\}])", r"\1", wrapped)
1616
+ try:
1617
+ val = json.loads(cleaned)
1618
+ if isinstance(val, (dict, list)):
1619
+ return val
1620
+ except Exception:
1621
+ pass
1622
+
1623
+ start_idx = -1
1624
+ open_char = ""
1625
+ for idx, char in enumerate(s):
1626
+ if char in "{[":
1627
+ start_idx = idx
1628
+ open_char = char
1629
+ break
1630
+ if start_idx == -1:
1631
+ return None
1632
+
1633
+ candidate_raw = s[start_idx:]
1634
+ close_char = "}" if open_char == "{" else "]"
1635
+ last_idx = candidate_raw.rfind(close_char)
1636
+ if last_idx != -1:
1637
+ balanced_candidate = candidate_raw[: last_idx + 1]
1638
+ try:
1639
+ val = json.loads(balanced_candidate)
1640
+ if isinstance(val, (dict, list)):
1641
+ return val
1642
+ except Exception:
1643
+ cleaned = re.sub(r",\s*([\]\}])", r"\1", balanced_candidate)
1644
+ try:
1645
+ val = json.loads(cleaned)
1646
+ if isinstance(val, (dict, list)):
1647
+ return val
1648
+ except Exception:
1649
+ pass
1650
+
1651
+ stack = []
1652
+ in_string = False
1653
+ escape = False
1654
+ for char in candidate_raw:
1655
+ if escape:
1656
+ escape = False
1657
+ continue
1658
+ if char == "\\":
1659
+ escape = True
1660
+ continue
1661
+ if char == '"':
1662
+ in_string = not in_string
1663
+ continue
1664
+ if not in_string:
1665
+ if char in "{[":
1666
+ stack.append("}" if char == "{" else "]")
1667
+ elif char in "}]":
1668
+ if stack and stack[-1] == char:
1669
+ stack.pop()
1670
+
1671
+ candidate = candidate_raw + "".join(reversed(stack)) if stack else candidate_raw
1672
+ cleaned = re.sub(r",\s*([\]\}])", r"\1", candidate)
1673
+ try:
1674
+ val = json.loads(cleaned)
1675
+ if isinstance(val, (dict, list)):
1676
+ return val
1677
+ except Exception:
1678
+ pass
1679
+ return None
1680
+
1681
+
1682
+ def _parse_single_json(raw: str) -> dict | list | None:
1683
+ """从单体文本(可能含 Markdown 围栏或前后自然语言)中提取并修复 JSON。"""
1684
+ if not isinstance(raw, str) or not raw.strip():
1685
+ return None
1686
+ s = raw.strip()
1687
+ try:
1688
+ val = json.loads(s)
1689
+ if isinstance(val, (dict, list)):
1690
+ return val
1691
+ except Exception:
1692
+ pass
1693
+
1694
+ code_blocks = re.findall(r"```(?:json)?\s*([\s\S]*?)\s*```", s)
1695
+ for block in code_blocks:
1696
+ b_clean = block.strip()
1697
+ try:
1698
+ val = json.loads(b_clean)
1699
+ if isinstance(val, (dict, list)):
1700
+ return val
1701
+ except Exception:
1702
+ repaired = _repair_and_load_json(b_clean)
1703
+ if repaired is not None:
1704
+ return repaired
1705
+
1706
+ return _repair_and_load_json(s)
1707
+
1708
+
1709
+ def _unwrap_event_object(obj: dict) -> dict | list | None:
1710
+ """若对象为 CLI 外层事件包装(如 run_result / agent_event / item.created),解包提取内部 JSON。"""
1711
+ if not isinstance(obj, dict):
1712
+ return None
1713
+ # Cline run_result
1714
+ if obj.get("type") == "run_result" and isinstance(obj.get("text"), str):
1715
+ return _parse_single_json(obj["text"])
1716
+ # Cline agent_event done
1717
+ if obj.get("type") == "agent_event":
1718
+ ev = obj.get("event")
1719
+ if isinstance(ev, dict) and isinstance(ev.get("text"), str):
1720
+ return _parse_single_json(ev["text"])
1721
+ # Codex item / message
1722
+ if obj.get("type") in ("message", "item.created", "item.updated"):
1723
+ item = obj.get("item") if "item" in obj else obj
1724
+ if isinstance(item, dict):
1725
+ content = item.get("content")
1726
+ if isinstance(content, list):
1727
+ for c in content:
1728
+ if isinstance(c, dict) and isinstance(c.get("text"), str):
1729
+ res = _parse_single_json(c["text"])
1730
+ if res is not None:
1731
+ return res
1732
+ elif isinstance(content, str):
1733
+ return _parse_single_json(content)
1734
+ # OpenCode text part
1735
+ if obj.get("type") == "text" and isinstance(obj.get("part"), dict):
1736
+ t = obj["part"].get("text")
1737
+ if isinstance(t, str):
1738
+ return _parse_single_json(t)
1739
+ # result string
1740
+ if "result" in obj and isinstance(obj["result"], str):
1741
+ return _parse_single_json(obj["result"])
1742
+ return None
1743
+
1744
+
1745
+ def extract_resilient_json(text: str) -> dict | list | None:
1746
+ """终局加固补丁 21:容错级准结构化 JSON 自愈提取器 (Resilient Normalization Extractor)。
1747
+
1748
+ 支持主流 AI CLI 的 JSON Lines (NDJSON) 事件流提取(Cline, OpenCode, Codex),
1749
+ 自动剥离 Markdown 围栏,消除尾随逗号,并通过词法栈自动闭合未匹配括号。
1750
+ """
1751
+ if not isinstance(text, str) or not text.strip():
1752
+ return None
1753
+ raw = text.strip()
1754
+
1755
+ # 1. 优先尝试作为直接的完整 JSON 或由 _parse_single_json 处理
1756
+ direct = _parse_single_json(raw)
1757
+ if direct is not None:
1758
+ if isinstance(direct, dict):
1759
+ unwrapped = _unwrap_event_object(direct)
1760
+ if unwrapped is not None:
1761
+ return unwrapped
1762
+ return direct
1763
+
1764
+ # 2. 检测并处理 JSON Lines (NDJSON) 事件流(如 cline --json, opencode run --format json)
1765
+ lines = [line.strip() for line in raw.splitlines() if line.strip()]
1766
+ if len(lines) > 1:
1767
+ # 尝试从行式流中提取模型生成的文本内容
1768
+ extracted_text = _extract_text_from_jsonl_stream(lines)
1769
+ if extracted_text:
1770
+ parsed = _parse_single_json(extracted_text)
1771
+ if parsed is not None:
1772
+ return parsed
1773
+
1774
+ # 若提取的文本未直接解析成功,检查各行自身是否为业务目标 JSON
1775
+ for line in reversed(lines):
1776
+ line_parsed = _parse_single_json(line)
1777
+ if isinstance(line_parsed, (dict, list)):
1778
+ if isinstance(line_parsed, dict) and any(
1779
+ k in line_parsed for k in ("semantic_review", "hypotheses", "excluded_fixtures", "real_forms")
1780
+ ):
1781
+ return line_parsed
1782
+
1783
+ return None
1784
+
1785
+
1786
+ def verify_hypothesis_anchor(
1787
+ project_root: str | Path,
1788
+ source_file: str,
1789
+ line: int,
1790
+ *,
1791
+ window: int = 5,
1792
+ ) -> bool:
1793
+ """终局加固补丁 11:滑窗语义模糊锚定门禁 (Fuzzy Window Anchor Gate)。
1794
+
1795
+ 以模型给出的行号为中心,在 [line - window, line + window] 范围内
1796
+ 静态验证物理文件与代码行存在性,防止大模型行号微小漂移导致有效漏洞假设被误杀。
1797
+ """
1798
+ if not source_file:
1799
+ return False
1800
+ root = Path(project_root).resolve()
1801
+ target = (root / source_file).resolve()
1802
+ try:
1803
+ target.relative_to(root)
1804
+ except ValueError:
1805
+ return False
1806
+ if not target.is_file():
1807
+ return False
1808
+
1809
+ try:
1810
+ lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
1811
+ except Exception:
1812
+ return False
1813
+
1814
+ total_lines = len(lines)
1815
+ if total_lines == 0:
1816
+ return False
1817
+
1818
+ # 若行号 <= 0,默认看文件头
1819
+ center = max(1, min(line, total_lines))
1820
+ start = max(1, center - window)
1821
+ end = min(total_lines, center + window)
1822
+
1823
+ # 窗口内存在非空白代码行即视为锚定成功
1824
+ for idx in range(start - 1, end):
1825
+ line_content = lines[idx].strip()
1826
+ if line_content and not line_content.startswith("#") and not line_content.startswith("//"):
1827
+ return True
1828
+ return False
1829
+
1830
+
1831
+ __all__ = [
1832
+ "ADVANCED_BY_ATTR",
1833
+ "ALL_EVENTS",
1834
+ "AttackGraphStoreError",
1835
+ "EVENT_ENDPOINTS_READY",
1836
+ "EVENT_ENDPOINT_DISCOVERED",
1837
+ "EVENT_EVIDENCE_CHECKPOINTED",
1838
+ "EVENT_GRAPH_ABSORBED",
1839
+ "EVENT_GRAPH_SEEDED",
1840
+ "EVENT_HYPOTHESIS_PROPOSED",
1841
+ "EVENT_HYPOTHESIS_REJECTED",
1842
+ "EVENT_HYPOTHESIS_VERIFIED",
1843
+ "EVENT_ROLE_OBSERVED",
1844
+ "EVENT_ROLLBACK",
1845
+ "EVENT_SINK_FOUND",
1846
+ "EVENT_UNIT_COVERED",
1847
+ "EVENT_UNIT_STAMPED",
1848
+ "SNAPSHOT_NAME",
1849
+ "UNIT_ATTR",
1850
+ "absorb_evidence",
1851
+ "absorb_findings",
1852
+ "absorb_sinks",
1853
+ "absorb_surface",
1854
+ "extract_resilient_json",
1855
+ "finalize_round",
1856
+ "graph_dir",
1857
+ "load_graph",
1858
+ "record_event",
1859
+ "record_events",
1860
+ "reflex_state",
1861
+ "replay_reflex_fix",
1862
+ "save_graph",
1863
+ "seed_from_units",
1864
+ "snapshot_path",
1865
+ "stamp_unit",
1866
+ "stats",
1867
+ "verify_hypothesis_anchor",
1868
+ ]