bugx-cli 0.0.0-stage → 0.1.1

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 (788) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +284 -2
  3. package/core/CATALOG.json +141 -0
  4. package/core/README.md +254 -0
  5. package/core/adapters/README.md +35 -0
  6. package/core/adapters/android-interaction.json +81 -0
  7. package/core/adapters/android.json +24 -0
  8. package/core/adapters/desktop-macos.json +20 -0
  9. package/core/adapters/ios-interaction.json +34 -0
  10. package/core/adapters/ios.json +23 -0
  11. package/core/adapters/memory-macos.json +24 -0
  12. package/core/agent/README.md +51 -0
  13. package/core/agent/__init__.py +146 -0
  14. package/core/agent/agent_artifacts.py +766 -0
  15. package/core/agent/agent_eval.py +1155 -0
  16. package/core/agent/agent_execution.py +718 -0
  17. package/core/agent/agent_orchestrator.py +1351 -0
  18. package/core/agent/agent_targets.py +877 -0
  19. package/core/agent/agent_workspace.py +770 -0
  20. package/core/agent/feature_baseline.py +150 -0
  21. package/core/assets/README.md +24 -0
  22. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  23. package/core/assets/axe-core/LICENSE.txt +362 -0
  24. package/core/assets/axe-core/UPSTREAM.md +10 -0
  25. package/core/assets/axe-core/axe.min.js +12 -0
  26. package/core/assets/bugx-avatar-1024.png +0 -0
  27. package/core/assets/bugx-avatar-512.png +0 -0
  28. package/core/assets/bugx-avatar-tight.svg +23 -0
  29. package/core/assets/bugx-avatar.svg +28 -0
  30. package/core/assets/bugx-hero-cn.png +0 -0
  31. package/core/assets/bugx-hero-en.png +0 -0
  32. package/core/assets/bugx-hero-en.svg +74 -0
  33. package/core/assets/bugx-hero-zh.svg +74 -0
  34. package/core/assets/codex.png +0 -0
  35. package/core/assets/dsh.png +0 -0
  36. package/core/assets/project-layout.md +42 -0
  37. package/core/assets/webui-chatgpt.jpg +0 -0
  38. package/core/assets/webui-session.jpg +0 -0
  39. package/core/assets/webui-skills.jpg +0 -0
  40. package/core/assets/webui-studio.jpg +0 -0
  41. package/core/assets/webui-zcode.jpg +0 -0
  42. package/core/assets/zcode.png +0 -0
  43. package/core/audit_packs/README.md +37 -0
  44. package/core/audit_packs/data-audit/manifest.json +94 -0
  45. package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  46. package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  47. package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  48. package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  49. package/core/audit_packs/desktop-audit/manifest.json +123 -0
  50. package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  51. package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  52. package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  53. package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  54. package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  55. package/core/audit_packs/memory-testing.md +227 -0
  56. package/core/audit_packs/mobile-audit/manifest.json +155 -0
  57. package/core/audit_packs/mobile-audit/modules/android.md +19 -0
  58. package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  59. package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  60. package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  61. package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  62. package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  63. package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  64. package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  65. package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  66. package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  67. package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  68. package/core/audit_packs/native-audit/manifest.json +127 -0
  69. package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  70. package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  71. package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  72. package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  73. package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  74. package/core/audit_packs/platform-testing.md +174 -0
  75. package/core/audit_packs/web-audit/manifest.json +191 -0
  76. package/core/audit_packs/web-audit/modules/graphql.md +5 -0
  77. package/core/audit_packs/web-audit/modules/h5.md +18 -0
  78. package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  79. package/core/audit_packs/web-audit/modules/oauth.md +4 -0
  80. package/core/audit_packs/web-audit/modules/upload.md +4 -0
  81. package/core/audit_packs/web-audit/modules/websocket.md +4 -0
  82. package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  83. package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  84. package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  85. package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  86. package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  87. package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  88. package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  89. package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  90. package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  91. package/core/autonomous_cve/INTERFACE.md +61 -0
  92. package/core/autonomous_cve/README.md +58 -0
  93. package/core/autonomous_cve/SPEC.md +25 -0
  94. package/core/autonomous_cve/__init__.py +109 -0
  95. package/core/autonomous_cve/attack_graph.py +1096 -0
  96. package/core/autonomous_cve/attack_graph_store.py +1868 -0
  97. package/core/autonomous_cve/audit_campaign.py +1232 -0
  98. package/core/autonomous_cve/behavior_graph.py +465 -0
  99. package/core/autonomous_cve/ghsa_advisories.py +174 -0
  100. package/core/autonomous_cve/models.py +93 -0
  101. package/core/autonomous_cve/mutator.py +87 -0
  102. package/core/autonomous_cve/patcher.py +126 -0
  103. package/core/autonomous_cve/scout.py +278 -0
  104. package/core/autonomous_cve/synthesizer.py +207 -0
  105. package/core/autonomous_cve/verifier.py +103 -0
  106. package/core/bugx.md +1299 -0
  107. package/core/bugx_paths.py +1881 -0
  108. package/core/cli-help.txt +66 -0
  109. package/core/cloud_sync/INTERFACE.md +32 -0
  110. package/core/cloud_sync/README.md +62 -0
  111. package/core/cloud_sync/SPEC.md +25 -0
  112. package/core/cloud_sync/__init__.py +23 -0
  113. package/core/cloud_sync/auto_sync.py +398 -0
  114. package/core/cloud_sync/cloud_client.py +1218 -0
  115. package/core/cloud_sync/cloud_onboard.py +743 -0
  116. package/core/cloud_sync/cloud_schema.py +648 -0
  117. package/core/cloud_sync/consent.py +81 -0
  118. package/core/cloud_sync/device_identity.py +307 -0
  119. package/core/cloud_sync/endpoint_router.py +415 -0
  120. package/core/cloud_sync/flywheel_client.py +769 -0
  121. package/core/cloud_sync/network_transport.py +296 -0
  122. package/core/cloud_sync/onboard_wizard.py +493 -0
  123. package/core/cloud_sync/sensitive_filter.py +285 -0
  124. package/core/cloud_sync/sync_pull.py +695 -0
  125. package/core/cloud_sync/sync_push.py +723 -0
  126. package/core/contracts/AGENT_GUIDE.md +359 -0
  127. package/core/contracts/README.md +34 -0
  128. package/core/contracts/bugx-blackbox.md +541 -0
  129. package/core/contracts/bugx-opencode.md +469 -0
  130. package/core/contracts/bugx-quick.md +44 -0
  131. package/core/contracts/bugx-runtime-contract.md +353 -0
  132. package/core/contracts/bugx-worker.md +470 -0
  133. package/core/contracts/engine_gap_contracts.py +473 -0
  134. package/core/coverage/README.md +70 -0
  135. package/core/coverage/__init__.py +106 -0
  136. package/core/coverage/coverage_ai_review.py +185 -0
  137. package/core/coverage/coverage_backfill.py +54 -0
  138. package/core/coverage/coverage_bootstrap.py +713 -0
  139. package/core/coverage/coverage_business.py +36 -0
  140. package/core/coverage/coverage_cli.py +715 -0
  141. package/core/coverage/coverage_discovery.py +1429 -0
  142. package/core/coverage/coverage_evidence.py +1024 -0
  143. package/core/coverage/coverage_forensics.py +124 -0
  144. package/core/coverage/coverage_gate.py +277 -0
  145. package/core/coverage/coverage_intelligence.py +734 -0
  146. package/core/coverage/coverage_manifest.py +396 -0
  147. package/core/coverage/coverage_platform.py +77 -0
  148. package/core/coverage/coverage_validate.py +241 -0
  149. package/core/coverage/module_coverage.py +157 -0
  150. package/core/dev_harness/INTERFACE.md +20 -0
  151. package/core/dev_harness/README.md +21 -0
  152. package/core/dev_harness/SPEC.md +25 -0
  153. package/core/dev_harness/__init__.py +5 -0
  154. package/core/dev_harness/interaction_preset.py +408 -0
  155. package/core/engine-integrity.json +2797 -0
  156. package/core/fuzzing/README.md +49 -0
  157. package/core/fuzzing/__init__.py +82 -0
  158. package/core/fuzzing/concurrency_fuzzer.py +435 -0
  159. package/core/fuzzing/differential_oracle.py +1164 -0
  160. package/core/fuzzing/fuzz_input.py +1291 -0
  161. package/core/fuzzing/stateful_fuzzer.py +404 -0
  162. package/core/governance/README.md +61 -0
  163. package/core/governance/__init__.py +130 -0
  164. package/core/governance/capacity_planner.py +124 -0
  165. package/core/governance/dependency_lock.py +317 -0
  166. package/core/governance/goal_governor.py +754 -0
  167. package/core/governance/guide_budget.py +458 -0
  168. package/core/governance/lockdown.sh +50 -0
  169. package/core/governance/readonly_enforcer.py +154 -0
  170. package/core/governance/runtime_tool_gate.py +373 -0
  171. package/core/governance/secret_redactor.py +784 -0
  172. package/core/governance/token_budget.py +38 -0
  173. package/core/host_acp/INTERFACE.md +36 -0
  174. package/core/host_acp/README.md +51 -0
  175. package/core/host_acp/SPEC.md +25 -0
  176. package/core/host_acp/__init__.py +121 -0
  177. package/core/host_acp/base.py +111 -0
  178. package/core/host_acp/claude.py +99 -0
  179. package/core/host_acp/cline.py +298 -0
  180. package/core/host_acp/codex.py +300 -0
  181. package/core/host_acp/dsh.py +106 -0
  182. package/core/host_acp/opencode.py +209 -0
  183. package/core/host_acp/pi.py +94 -0
  184. package/core/host_acp/zcode.py +99 -0
  185. package/core/host_runtime/INTERFACE.md +24 -0
  186. package/core/host_runtime/README.md +62 -0
  187. package/core/host_runtime/SPEC.md +25 -0
  188. package/core/host_runtime/__init__.py +21 -0
  189. package/core/host_runtime/adapters.py +412 -0
  190. package/core/host_runtime/autonomous_runner.py +1152 -0
  191. package/core/host_runtime/cline.py +448 -0
  192. package/core/host_runtime/common.py +103 -0
  193. package/core/host_runtime/free_models.py +786 -0
  194. package/core/host_runtime/host_bootstrap.py +389 -0
  195. package/core/host_runtime/host_evaluators.py +761 -0
  196. package/core/host_runtime/host_probe.py +41 -0
  197. package/core/host_runtime/host_provider_arbitrator.py +831 -0
  198. package/core/host_runtime/host_registry.py +662 -0
  199. package/core/host_runtime/host_usage.py +127 -0
  200. package/core/host_runtime/mcp_process_tracker.py +509 -0
  201. package/core/host_runtime/mcp_registry_gate.py +379 -0
  202. package/core/host_runtime/pi.py +102 -0
  203. package/core/host_runtime/provider_facts.py +66 -0
  204. package/core/hosts/INTERFACE.md +51 -0
  205. package/core/hosts/README.md +67 -0
  206. package/core/hosts/SPEC.md +25 -0
  207. package/core/hosts/__init__.py +140 -0
  208. package/core/hosts/_base_usage.py +152 -0
  209. package/core/hosts/_codex_usage.py +297 -0
  210. package/core/hosts/_dsh_usage.py +184 -0
  211. package/core/hosts/_mcp_toml.py +365 -0
  212. package/core/hosts/_zcode_usage.py +269 -0
  213. package/core/hosts/base.py +479 -0
  214. package/core/hosts/claude.py +212 -0
  215. package/core/hosts/cline.py +229 -0
  216. package/core/hosts/codex.py +1006 -0
  217. package/core/hosts/dsh.py +526 -0
  218. package/core/hosts/opencode.py +358 -0
  219. package/core/hosts/pi.py +308 -0
  220. package/core/hosts/zcode.py +219 -0
  221. package/core/i18n.py +252 -0
  222. package/core/infra/README.md +41 -0
  223. package/core/infra/__init__.py +17 -0
  224. package/core/infra/build_info.py +105 -0
  225. package/core/infra/client_metadata.py +185 -0
  226. package/core/infra/json_utils.py +22 -0
  227. package/core/infra/python_runtime.py +540 -0
  228. package/core/infra/safe_xml.py +221 -0
  229. package/core/launch_bugx.py +118 -0
  230. package/core/launch_phases/INTERFACE.md +31 -0
  231. package/core/launch_phases/README.md +106 -0
  232. package/core/launch_phases/SPEC.md +25 -0
  233. package/core/launch_phases/__init__.py +29 -0
  234. package/core/launch_phases/candidate_revalidation.py +484 -0
  235. package/core/launch_phases/common.py +1060 -0
  236. package/core/launch_phases/finding_confirm_phase.py +391 -0
  237. package/core/launch_phases/finding_settlement.py +1432 -0
  238. package/core/launch_phases/findings_adjudication.py +666 -0
  239. package/core/launch_phases/findings_snapshot.py +357 -0
  240. package/core/launch_phases/judge_phase.py +848 -0
  241. package/core/launch_phases/lesson_context.py +536 -0
  242. package/core/launch_phases/lifecycle_reporter.py +627 -0
  243. package/core/launch_phases/orchestrator_controls.py +686 -0
  244. package/core/launch_phases/post_commit.py +567 -0
  245. package/core/launch_phases/post_coverage_sync.py +598 -0
  246. package/core/launch_phases/post_dry_run.py +817 -0
  247. package/core/launch_phases/post_observability.py +367 -0
  248. package/core/launch_phases/post_phase.py +1223 -0
  249. package/core/launch_phases/post_receipt.py +373 -0
  250. package/core/launch_phases/post_round_lifecycle.py +786 -0
  251. package/core/launch_phases/pre_phase.py +1029 -0
  252. package/core/launch_phases/pre_recon_scout.py +879 -0
  253. package/core/launch_phases/pre_state_builder.py +1133 -0
  254. package/core/launch_phases/report_sharing.py +414 -0
  255. package/core/launch_phases/round_orchestrator.py +1116 -0
  256. package/core/launch_phases/session_runtime.py +1670 -0
  257. package/core/launch_phases/startup_gates.py +1050 -0
  258. package/core/launch_phases/startup_interaction.py +1003 -0
  259. package/core/launch_phases/startup_version_gate.py +879 -0
  260. package/core/launch_phases/supervisor_bridge.py +1253 -0
  261. package/core/launch_phases/supervisor_coverage.py +423 -0
  262. package/core/launch_phases/supervisor_degraded.py +1211 -0
  263. package/core/launch_phases/worker_barriers.py +424 -0
  264. package/core/launch_phases/worker_orchestrator.py +1246 -0
  265. package/core/launch_phases/worker_prior.py +749 -0
  266. package/core/ledger/INTERFACE.md +35 -0
  267. package/core/ledger/README.md +160 -0
  268. package/core/ledger/SPEC.md +25 -0
  269. package/core/ledger/__init__.py +67 -0
  270. package/core/ledger/_facade.py +227 -0
  271. package/core/ledger/archive_ops.py +630 -0
  272. package/core/ledger/auto_materialization.py +459 -0
  273. package/core/ledger/bug-log.md +22 -0
  274. package/core/ledger/cli.py +275 -0
  275. package/core/ledger/export_ops.py +554 -0
  276. package/core/ledger/finding_confirmation.py +1316 -0
  277. package/core/ledger/finding_io.py +299 -0
  278. package/core/ledger/finding_lifecycle.py +730 -0
  279. package/core/ledger/finding_verification.py +405 -0
  280. package/core/ledger/incidents.py +1005 -0
  281. package/core/ledger/lesson-replay-cases.json +20 -0
  282. package/core/ledger/lesson_ledger.py +241 -0
  283. package/core/ledger/lesson_replay.py +272 -0
  284. package/core/ledger/life_ledger.py +668 -0
  285. package/core/ledger/mistake-book.md +130 -0
  286. package/core/ledger/patterns.py +684 -0
  287. package/core/ledger/receipt_contract.py +269 -0
  288. package/core/ledger/schema.py +1192 -0
  289. package/core/ledger/sync_ops.py +940 -0
  290. package/core/ledger/tool_experience.py +683 -0
  291. package/core/ledger/verify_life.py +1597 -0
  292. package/core/lesson-ledger.json +275 -0
  293. package/core/locales/README.md +19 -0
  294. package/core/locales/en-US.json +462 -0
  295. package/core/locales/zh-CN.json +462 -0
  296. package/core/mcp_handlers/INTERFACE.md +75 -0
  297. package/core/mcp_handlers/README.md +62 -0
  298. package/core/mcp_handlers/SPEC.md +25 -0
  299. package/core/mcp_handlers/__init__.py +128 -0
  300. package/core/mcp_handlers/base.py +717 -0
  301. package/core/mcp_handlers/channel_lifecycle.py +751 -0
  302. package/core/mcp_handlers/graph_handlers.py +222 -0
  303. package/core/mcp_handlers/knowledge_handlers.py +536 -0
  304. package/core/mcp_handlers/mining_handlers.py +586 -0
  305. package/core/mcp_handlers/resource_prompt_table.py +116 -0
  306. package/core/mcp_handlers/retrieval_handlers.py +249 -0
  307. package/core/mcp_handlers/rpc_server.py +470 -0
  308. package/core/mcp_handlers/supervisor_handlers.py +1461 -0
  309. package/core/mcp_handlers/telemetry_handlers.py +227 -0
  310. package/core/mcp_handlers/tool_table.py +1030 -0
  311. package/core/mcp_runtime_support/README.md +21 -0
  312. package/core/mcp_runtime_support/__init__.py +1 -0
  313. package/core/mcp_runtime_support/common.py +363 -0
  314. package/core/mcp_runtime_support/environment.py +567 -0
  315. package/core/mcp_runtime_support/verifier.py +758 -0
  316. package/core/metadata.txt +4 -0
  317. package/core/planning/README.md +157 -0
  318. package/core/planning/__init__.py +242 -0
  319. package/core/planning/capability_plan.py +187 -0
  320. package/core/planning/capability_planner.py +195 -0
  321. package/core/planning/domain_archetype.py +542 -0
  322. package/core/planning/domain_router.py +269 -0
  323. package/core/planning/dynamic_flow_analyzer.py +533 -0
  324. package/core/planning/impact_pruner.py +435 -0
  325. package/core/planning/intent_adjudicator.py +175 -0
  326. package/core/planning/judge_pipeline.py +1246 -0
  327. package/core/planning/logic_analysis.py +419 -0
  328. package/core/planning/prompt_harness.py +1704 -0
  329. package/core/planning/source_inspector.py +267 -0
  330. package/core/planning/spec_harvester.py +449 -0
  331. package/core/planning/target_sandbox_manager.py +573 -0
  332. package/core/planning/test_capability_verifier.py +1364 -0
  333. package/core/planning/tools-kb.md +38 -0
  334. package/core/planning/unit_kind.py +122 -0
  335. package/core/probes/INTERFACE.md +83 -0
  336. package/core/probes/README.md +51 -0
  337. package/core/probes/SPEC.md +36 -0
  338. package/core/probes/__init__.py +76 -0
  339. package/core/probes/android_probe.py +552 -0
  340. package/core/probes/base.py +147 -0
  341. package/core/probes/codebase_memory_probe.py +647 -0
  342. package/core/probes/desktop_probe.py +342 -0
  343. package/core/probes/differential_probe.py +434 -0
  344. package/core/probes/efficiency_probe.py +232 -0
  345. package/core/probes/ios_binary_probe.py +472 -0
  346. package/core/probes/memory_probe.py +392 -0
  347. package/core/probes/miniprogram_probe.py +385 -0
  348. package/core/probes/mobile_probe.py +466 -0
  349. package/core/probes/native_probe.py +302 -0
  350. package/core/probes/openwiki_probe.py +263 -0
  351. package/core/probes/pattern_probe.py +453 -0
  352. package/core/probes/platform_probe.py +424 -0
  353. package/core/probes/probe_registry.py +1770 -0
  354. package/core/probes/sast_fixture_corpus.py +340 -0
  355. package/core/probes/sast_probe.py +1510 -0
  356. package/core/probes/sast_rules.py +1481 -0
  357. package/core/probes/sca_scanner.py +779 -0
  358. package/core/probes/ui_accessibility.py +149 -0
  359. package/core/probes/ui_audit.py +513 -0
  360. package/core/probes/ui_contract.py +273 -0
  361. package/core/probes/ui_evidence.py +212 -0
  362. package/core/probes/ui_measurements.py +314 -0
  363. package/core/probes/ui_repair.py +250 -0
  364. package/core/probes/ui_review.py +133 -0
  365. package/core/probes/ui_storybook.py +107 -0
  366. package/core/probes/ui_tokens.py +185 -0
  367. package/core/probes/ui_visual_diff.py +131 -0
  368. package/core/probes/web_probe.py +714 -0
  369. package/core/project_profiler/INTERFACE.md +62 -0
  370. package/core/project_profiler/README.md +53 -0
  371. package/core/project_profiler/SPEC.md +28 -0
  372. package/core/project_profiler/__init__.py +201 -0
  373. package/core/project_profiler/arbitrator.py +316 -0
  374. package/core/project_profiler/constants.py +247 -0
  375. package/core/project_profiler/detector.py +399 -0
  376. package/core/project_profiler/extractors.py +836 -0
  377. package/core/project_profiler/fingerprint.py +116 -0
  378. package/core/project_profiler/storage.py +258 -0
  379. package/core/project_profiler/strategy.py +301 -0
  380. package/core/prompts/README.md +35 -0
  381. package/core/prompts/codex_dialog_dispatch.md +9 -0
  382. package/core/prompts/command_routing_en.md +42 -0
  383. package/core/prompts/command_routing_zh.md +42 -0
  384. package/core/prompts/l0_router.md +47 -0
  385. package/core/prompts/rules/anti_patterns.md +16 -0
  386. package/core/prompts/rules/concurrency_rules.md +14 -0
  387. package/core/prompts/rules/memory_leak_rules.md +13 -0
  388. package/core/prompts/rules/prompt_injection_defense.md +13 -0
  389. package/core/prompts/stages/stage_explore.md +31 -0
  390. package/core/prompts/stages/stage_gate.md +43 -0
  391. package/core/prompts/stages/stage_mutate.md +42 -0
  392. package/core/prompts/stages/stage_repair.md +85 -0
  393. package/core/repair/README.md +74 -0
  394. package/core/repair/__init__.py +169 -0
  395. package/core/repair/fix_watchlist.py +391 -0
  396. package/core/repair/l7_dynamic.py +418 -0
  397. package/core/repair/l7_repair_loop.py +462 -0
  398. package/core/repair/l7_selfcheck.py +862 -0
  399. package/core/repair/minimize_repro.py +466 -0
  400. package/core/repair/patch_synthesizer.py +617 -0
  401. package/core/repair/regression_pack.py +379 -0
  402. package/core/repair/rsi_fixer.py +910 -0
  403. package/core/repair/rsi_loop.py +311 -0
  404. package/core/repair/rsi_repair.py +348 -0
  405. package/core/repair/rsi_rounds.py +212 -0
  406. package/core/repair/rsi_scope.py +281 -0
  407. package/core/repair/self_heal.py +604 -0
  408. package/core/repair/test_generator.py +1108 -0
  409. package/core/repair/test_quality_auditor.py +410 -0
  410. package/core/repair/test_strategy.py +511 -0
  411. package/core/report_engine/INTERFACE.md +59 -0
  412. package/core/report_engine/README.md +69 -0
  413. package/core/report_engine/SPEC.md +28 -0
  414. package/core/report_engine/__init__.py +47 -0
  415. package/core/report_engine/attestation.py +228 -0
  416. package/core/report_engine/authority.py +255 -0
  417. package/core/report_engine/finding_report.py +418 -0
  418. package/core/report_engine/formal_report_builder.py +924 -0
  419. package/core/report_engine/html_renderers.py +696 -0
  420. package/core/report_engine/models.py +759 -0
  421. package/core/report_engine/pdf_exporter.py +231 -0
  422. package/core/report_engine/projects_assets.py +730 -0
  423. package/core/report_engine/report_client.py +743 -0
  424. package/core/report_engine/report_data_builder.py +388 -0
  425. package/core/report_engine/report_share.py +459 -0
  426. package/core/report_engine/sast_bridge.py +116 -0
  427. package/core/report_engine/server.py +832 -0
  428. package/core/report_engine/visual_report_builder.py +796 -0
  429. package/core/report_engine/web-conformance.md +168 -0
  430. package/core/report_engine/web_conformance.py +428 -0
  431. package/core/report_engine/workbench_assets.py +484 -0
  432. package/core/retrieval/INTERFACE.md +20 -0
  433. package/core/retrieval/README.md +161 -0
  434. package/core/retrieval/SPEC.md +25 -0
  435. package/core/retrieval/__init__.py +3 -0
  436. package/core/retrieval/code_analyzer.py +1720 -0
  437. package/core/retrieval/codebase_memory_bridge.py +337 -0
  438. package/core/retrieval/context_assembler.py +240 -0
  439. package/core/retrieval/corpus_fetch.py +369 -0
  440. package/core/retrieval/graph_ego.py +597 -0
  441. package/core/retrieval/knowledge_auto.py +662 -0
  442. package/core/retrieval/knowledge_sources.py +168 -0
  443. package/core/retrieval/knowledge_sync.py +1003 -0
  444. package/core/retrieval/memory_store.py +480 -0
  445. package/core/retrieval/query_planner.py +1020 -0
  446. package/core/retrieval/rrf_engine.py +137 -0
  447. package/core/retrieval/slice_extractor.py +1209 -0
  448. package/core/retrieval/slice_normalizer.py +373 -0
  449. package/core/retrieval/slice_spec.py +357 -0
  450. package/core/retrieval/symbol_index.py +1151 -0
  451. package/core/retrieval/universal_code_matcher.py +622 -0
  452. package/core/retrieval/xerj_bridge.py +476 -0
  453. package/core/retrieval/xerj_supervisor.py +362 -0
  454. package/core/rules/README.md +33 -0
  455. package/core/rules/ios/PROVENANCE.json +30 -0
  456. package/core/rules/ios/crypto.yaml +36 -0
  457. package/core/rules/ios/network.yaml +20 -0
  458. package/core/rules/ios/resilience.yaml +47 -0
  459. package/core/rules/ios/storage.yaml +48 -0
  460. package/core/rules/mastg/LICENSE +173 -0
  461. package/core/rules/mastg/PROVENANCE.json +270 -0
  462. package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  463. package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  464. package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  465. package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  466. package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  467. package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  468. package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  469. package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  470. package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  471. package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  472. package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  473. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  474. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  475. package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  476. package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  477. package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  478. package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  479. package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  480. package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  481. package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  482. package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  483. package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  484. package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  485. package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  486. package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  487. package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  488. package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  489. package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  490. package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  491. package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  492. package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  493. package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  494. package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  495. package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  496. package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  497. package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  498. package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  499. package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  500. package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  501. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  502. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  503. package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  504. package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  505. package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  506. package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  507. package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  508. package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  509. package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  510. package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  511. package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  512. package/core/rules/miniprogram/PROVENANCE.json +26 -0
  513. package/core/rules/miniprogram/network.yaml +37 -0
  514. package/core/rules/miniprogram/platform.yaml +36 -0
  515. package/core/rules/miniprogram/storage.yaml +48 -0
  516. package/core/rules/mobsfscan-swift/LICENSE +165 -0
  517. package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  518. package/core/rules/mobsfscan-swift/auth.yaml +59 -0
  519. package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  520. package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  521. package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  522. package/core/rules/mobsfscan-swift/logging.yaml +23 -0
  523. package/core/rules/mobsfscan-swift/network.yaml +55 -0
  524. package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  525. package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  526. package/core/rules/mobsfscan-swift/storage.yaml +29 -0
  527. package/core/rules/mobsfscan-swift/webview.yaml +32 -0
  528. package/core/runtime/README.md +198 -0
  529. package/core/runtime/__init__.py +3 -0
  530. package/core/runtime/bugx_logging.py +1464 -0
  531. package/core/runtime/daemon_runner.py +623 -0
  532. package/core/runtime/fixture_solidify.py +444 -0
  533. package/core/runtime/global_telemetry.py +549 -0
  534. package/core/runtime/incident_eval.py +148 -0
  535. package/core/runtime/interaction.py +605 -0
  536. package/core/runtime/interaction_store.py +435 -0
  537. package/core/runtime/interactive_menu.py +95 -0
  538. package/core/runtime/log_analytics.py +922 -0
  539. package/core/runtime/mining_quality_framework.py +1387 -0
  540. package/core/runtime/model_runner.py +732 -0
  541. package/core/runtime/platform_adapter.py +579 -0
  542. package/core/runtime/prep_validate.py +478 -0
  543. package/core/runtime/project_graph.py +827 -0
  544. package/core/runtime/project_init.py +481 -0
  545. package/core/runtime/project_profile.py +224 -0
  546. package/core/runtime/project_settings.py +964 -0
  547. package/core/runtime/provider_window.py +97 -0
  548. package/core/runtime/resume_ticket.py +115 -0
  549. package/core/runtime/scenario_eval.py +856 -0
  550. package/core/runtime/seed_drill.py +549 -0
  551. package/core/runtime/self_audit.py +550 -0
  552. package/core/runtime/session_profile.py +205 -0
  553. package/core/runtime/setup_ui_env.py +229 -0
  554. package/core/runtime/startup_environment.py +859 -0
  555. package/core/runtime/sync_store.py +1421 -0
  556. package/core/runtime/tool_install_targets.py +18 -0
  557. package/core/schemas/README.md +35 -0
  558. package/core/schemas/agent-graph.schema.json +368 -0
  559. package/core/schemas/attack-graph.schema.json +88 -0
  560. package/core/schemas/evidence-bundle.schema.json +33 -0
  561. package/core/schemas/skill-pack.schema.json +230 -0
  562. package/core/schemas/worker-checkpoint.schema.json +119 -0
  563. package/core/secure_atomic.py +289 -0
  564. package/core/seed_corpus/README.md +55 -0
  565. package/core/seed_corpus/c.txt +29 -0
  566. package/core/seed_corpus/cpp.txt +32 -0
  567. package/core/seed_corpus/css.txt +70 -0
  568. package/core/seed_corpus/go.txt +46 -0
  569. package/core/seed_corpus/java.txt +30 -0
  570. package/core/seed_corpus/javascript.txt +55 -0
  571. package/core/seed_corpus/kotlin.txt +28 -0
  572. package/core/seed_corpus/python.txt +71 -0
  573. package/core/seed_corpus/rust.txt +53 -0
  574. package/core/seed_corpus/swift.txt +29 -0
  575. package/core/seed_corpus/typescript.txt +29 -0
  576. package/core/skills/README.md +53 -0
  577. package/core/skills/__init__.py +189 -0
  578. package/core/skills/bugx_docs_mcp_server.py +418 -0
  579. package/core/skills/bugx_mcp_server.py +1161 -0
  580. package/core/skills/mcp_runtime.py +968 -0
  581. package/core/skills/mcp_session_proof.py +605 -0
  582. package/core/skills/mobile_ui_inspector.py +405 -0
  583. package/core/skills/skill_pack.py +1214 -0
  584. package/core/skills/skill_synthesizer.py +1153 -0
  585. package/core/skills/tools_kb.py +313 -0
  586. package/core/supervisor/INTERFACE.md +121 -0
  587. package/core/supervisor/README.md +209 -0
  588. package/core/supervisor/SPEC.md +25 -0
  589. package/core/supervisor/__init__.py +175 -0
  590. package/core/supervisor/audit_supervisor.py +1015 -0
  591. package/core/supervisor/budget_governor.py +1254 -0
  592. package/core/supervisor/checkpoint_handler.py +368 -0
  593. package/core/supervisor/checkpoint_pipeline.py +1564 -0
  594. package/core/supervisor/checkpoint_sync.py +653 -0
  595. package/core/supervisor/claim_events.py +74 -0
  596. package/core/supervisor/claim_sync.py +590 -0
  597. package/core/supervisor/cli.py +812 -0
  598. package/core/supervisor/context_sync.py +55 -0
  599. package/core/supervisor/coverage_sync.py +115 -0
  600. package/core/supervisor/finding_commit.py +470 -0
  601. package/core/supervisor/finding_sync.py +688 -0
  602. package/core/supervisor/finding_workflow.py +676 -0
  603. package/core/supervisor/finish_policy.py +224 -0
  604. package/core/supervisor/finish_sync.py +185 -0
  605. package/core/supervisor/graph_sync.py +669 -0
  606. package/core/supervisor/lease_manager.py +788 -0
  607. package/core/supervisor/lifecycle_blocks.py +129 -0
  608. package/core/supervisor/next_round_sync.py +126 -0
  609. package/core/supervisor/observability.py +140 -0
  610. package/core/supervisor/recovery_sync.py +165 -0
  611. package/core/supervisor/rejection_remedies.py +355 -0
  612. package/core/supervisor/round_governor.py +306 -0
  613. package/core/supervisor/serial_authorization.py +544 -0
  614. package/core/supervisor/start_sync.py +87 -0
  615. package/core/supervisor/state_store.py +249 -0
  616. package/core/supervisor/supervisor_host.py +511 -0
  617. package/core/supervisor/supervisor_models.py +1143 -0
  618. package/core/supervisor/systemic_failure.py +104 -0
  619. package/core/supervisor/task_scheduler.py +1640 -0
  620. package/core/supervisor/worker_checkpoint.py +230 -0
  621. package/core/supervisor/worker_execution.py +265 -0
  622. package/core/supervisor/worker_handoff.py +192 -0
  623. package/core/supervisor/worker_lifecycle.py +396 -0
  624. package/core/supervisor/worker_runtime.py +1005 -0
  625. package/core/supervisor/worker_sync.py +89 -0
  626. package/core/supervisor_types/README.md +36 -0
  627. package/core/supervisor_types/__init__.py +0 -0
  628. package/core/supervisor_types/exceptions.py +52 -0
  629. package/core/supervisor_types/graph_models.py +357 -0
  630. package/core/supervisor_types/path_containment.py +151 -0
  631. package/core/supervisor_types/target_fingerprint.py +310 -0
  632. package/core/supervisor_types/worker_claim.py +411 -0
  633. package/core/webui/INTERFACE.md +50 -0
  634. package/core/webui/README.md +57 -0
  635. package/core/webui/SPEC.md +26 -0
  636. package/core/webui/__init__.py +11 -0
  637. package/core/webui/adapters/__init__.py +27 -0
  638. package/core/webui/adapters/base.py +87 -0
  639. package/core/webui/adapters/bugx.py +102 -0
  640. package/core/webui/adapters/claude.py +222 -0
  641. package/core/webui/adapters/cline.py +407 -0
  642. package/core/webui/adapters/codex.py +260 -0
  643. package/core/webui/adapters/dsh.py +177 -0
  644. package/core/webui/adapters/opencode.py +218 -0
  645. package/core/webui/adapters/pi.py +272 -0
  646. package/core/webui/adapters/registry.py +100 -0
  647. package/core/webui/adapters/zcode.py +312 -0
  648. package/core/webui/api_routes_post.py +668 -0
  649. package/core/webui/dispatcher.py +1376 -0
  650. package/core/webui/docs_session_service.py +473 -0
  651. package/core/webui/handler.py +674 -0
  652. package/core/webui/ide_cloud_service.py +526 -0
  653. package/core/webui/mcp_inspector.py +1747 -0
  654. package/core/webui/static/00-base.css +1060 -0
  655. package/core/webui/static/01-monitoring.css +802 -0
  656. package/core/webui/static/02-header-actions.css +321 -0
  657. package/core/webui/static/03-trigger-popover.css +697 -0
  658. package/core/webui/static/04-composer.css +628 -0
  659. package/core/webui/static/05-skills-center.css +878 -0
  660. package/core/webui/static/06-mcp-center.css +623 -0
  661. package/core/webui/static/07-skill-detail.css +265 -0
  662. package/core/webui/static/08-files-management.css +167 -0
  663. package/core/webui/static/09-files-center.css +386 -0
  664. package/core/webui/static/10-icons.css +105 -0
  665. package/core/webui/static/11-project-options.css +185 -0
  666. package/core/webui/static/12-profile-tab.css +383 -0
  667. package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  668. package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  669. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  670. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  671. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  672. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  673. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  674. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  675. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  676. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  677. package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  678. package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  679. package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  680. package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  681. package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  682. package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  683. package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  684. package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  685. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  686. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  687. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  688. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  689. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  690. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  691. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  692. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  693. package/core/webui/static/design-tokens.css +113 -0
  694. package/core/webui/static/favicon.png +0 -0
  695. package/core/webui/static/icon-192.png +0 -0
  696. package/core/webui/static/index.html +55 -0
  697. package/core/webui/static/manifest.webmanifest +19 -0
  698. package/core/webui/static/project-settings.js +9602 -0
  699. package/core/webui/static/sw.js +8 -0
  700. package/core/webui/workspace_service.py +218 -0
  701. package/docs/07_distribution/01_README_NPM.md +285 -0
  702. package/ecosystem/README.md +129 -0
  703. package/ecosystem/integrations/README.md +38 -0
  704. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
  705. package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
  706. package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
  707. package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
  708. package/ecosystem/integrations/dsh/mcp/index.js +219 -0
  709. package/ecosystem/integrations/dsh/mcp/package.json +28 -0
  710. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
  711. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
  712. package/ecosystem/integrations/dsh/ui/client.js +87 -0
  713. package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
  714. package/ecosystem/integrations/dsh/ui/index.js +7 -0
  715. package/ecosystem/integrations/dsh/ui/package.json +27 -0
  716. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
  717. package/ecosystem/integrations/opencode/mcp-lock.json +3075 -0
  718. package/ecosystem/integrations/opencode/opencode.json +129 -0
  719. package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
  720. package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
  721. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
  722. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
  723. package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
  724. package/ecosystem/integrations/qoder/connector-meta.json +21 -0
  725. package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
  726. package/ecosystem/integrations/workbuddy/icon.png +0 -0
  727. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
  728. package/ecosystem/plugins/README.md +37 -0
  729. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
  730. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
  731. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
  732. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
  733. package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
  734. package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
  735. package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
  736. package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
  737. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
  738. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  739. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
  740. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  741. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  742. package/interfaces/bin/bugx.js +117 -0
  743. package/interfaces/cli/bugx_cli/__init__.py +6 -0
  744. package/interfaces/cli/bugx_cli/cli.py +1685 -0
  745. package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
  746. package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
  747. package/interfaces/cli/bugx_cli/commands/agent.py +4210 -0
  748. package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
  749. package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
  750. package/interfaces/cli/bugx_cli/commands/cloud.py +1371 -0
  751. package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
  752. package/interfaces/cli/bugx_cli/commands/doctor.py +1590 -0
  753. package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
  754. package/interfaces/cli/bugx_cli/commands/interaction.py +248 -0
  755. package/interfaces/cli/bugx_cli/commands/knowledge.py +619 -0
  756. package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
  757. package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
  758. package/interfaces/cli/bugx_cli/commands/plugin.py +2749 -0
  759. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
  760. package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
  761. package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
  762. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +729 -0
  763. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
  764. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
  765. package/interfaces/cli/bugx_cli/commands/project.py +670 -0
  766. package/interfaces/cli/bugx_cli/commands/report.py +256 -0
  767. package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
  768. package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
  769. package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
  770. package/interfaces/cli/bugx_cli/common.py +906 -0
  771. package/interfaces/cli/bugx_cli/host_adapters.py +1892 -0
  772. package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
  773. package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
  774. package/interfaces/cli/bugx_cli/hosts/registry.py +573 -0
  775. package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
  776. package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
  777. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +851 -0
  778. package/interfaces/cli/bugx_cli/infra/engine_installer.py +1945 -0
  779. package/interfaces/cli/bugx_cli/infra/host_sync.py +548 -0
  780. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +826 -0
  781. package/interfaces/cli/bugx_cli/infra/security.py +339 -0
  782. package/package.json +99 -4
  783. package/pyproject.toml +258 -0
  784. package/scripts/ensure-python.mjs +97 -0
  785. package/scripts/isolate-npm-readme.mjs +40 -0
  786. package/scripts/runtime.lock.json +31 -0
  787. package/scripts/sync-version.mjs +26 -0
  788. package/scripts/test-npm-wrapper.mjs +265 -0
@@ -0,0 +1,1096 @@
1
+ #!/usr/bin/env python3
2
+ """core/attack_graph.py - BugX 统一动态攻击面图谱 (Living Attack Graph) (DOC-125)。
3
+
4
+ 提供:
5
+ - 动态攻击面图谱节点 (roles, routes, parameters, sinks, hypotheses) 与边 (edges) 维护
6
+ - JSON Schema 严格校验 (attack-graph.schema.json)
7
+ - 非法访问边 (Illegal Access Edge) 结构化检索与审计证明
8
+ - 针对阶段 Harness 的有界上下文切片抽取 (Attack Graph Slicing, ≤200T)
9
+ - 假设驱动的反思回溯状态推进 (Reflexive Backtracking)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import copy
15
+ import hashlib
16
+ import json
17
+ import time
18
+ import warnings
19
+ from pathlib import Path
20
+ from typing import Any, Mapping, Iterable
21
+
22
+ try:
23
+ import jsonschema
24
+ except ImportError:
25
+ jsonschema = None # type: ignore[assignment]
26
+
27
+ SCHEMA_PATH = Path(__file__).resolve().parents[1] / "schemas" / "attack-graph.schema.json"
28
+
29
+ ILLEGAL_ACCESS_RELATIONS = {
30
+ "EXPLOITED_ACCESS",
31
+ "UNAUTHORIZED_CROSS_TENANT",
32
+ "IDOR_ACCESS",
33
+ "PRIVILEGE_ESCALATION",
34
+ "UNAUTHENTICATED_ACCESS",
35
+ }
36
+
37
+ # 与 attack-graph.schema.json 的 required / additionalProperties 约束一一对应,
38
+ # 用于 jsonschema 缺失(可选依赖,见 pyproject.toml)时的内置轻量校验。
39
+ _NODE_REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {
40
+ "roles": ("id", "type"),
41
+ "routes": ("id", "method", "auth_required"),
42
+ "parameters": ("id", "name"),
43
+ "sinks": ("id", "kind"),
44
+ "hypotheses": ("id", "type", "target", "status"),
45
+ }
46
+ _TOP_LEVEL_KEYS = frozenset({
47
+ "version", "nodes", "edges", "meta", "events", "reflex",
48
+ })
49
+ # DOC-125 闭环:``meta`` / ``events`` / ``reflex`` 是后来追加的**可选**顶层持久化
50
+ # 字段(事件日志、反思回溯历史、快照)。历史快照里没有它们也必须能读回来,
51
+ # 因此「允许的键」与「必需的键」必须分开,否则旧快照会被内置校验判为损坏。
52
+ _REQUIRED_TOP_LEVEL_KEYS = frozenset({"version", "nodes", "edges"})
53
+ _OPTIONAL_TOP_LEVEL_KEYS = frozenset({"meta", "events", "reflex"})
54
+ # 事件日志与回溯记录的硬上限:图谱每轮都要整体原子重写,无界增长会把
55
+ # Session 级快照变成 MB 级热点文件。
56
+ MAX_EVENT_JOURNAL = 500
57
+ MAX_ROLLBACK_LOG = 50
58
+ MAX_PERSISTED_SNAPSHOTS = 5
59
+
60
+
61
+ def _validate_structure_builtin(payload: Mapping[str, Any]) -> None:
62
+ """内置轻量结构校验(jsonschema 不可用时的 fail-closed 替代)。
63
+
64
+ 只覆盖 Schema 中真正带约束的部分:顶层 required / additionalProperties、
65
+ 节点与边的 required 字段及其基本类型。校验失败一律抛 ``ValueError``,
66
+ 使 ``validate()`` 在缺少可选依赖时仍然「失败即拒绝」,而不是静默放行。
67
+ """
68
+ if not isinstance(payload, Mapping):
69
+ raise ValueError("攻击图谱必须是 JSON 对象")
70
+ unknown = set(payload) - _TOP_LEVEL_KEYS
71
+ if unknown:
72
+ raise ValueError(f"攻击图谱存在 Schema 未允许的顶层字段: {sorted(unknown)}")
73
+ missing = _REQUIRED_TOP_LEVEL_KEYS - set(payload)
74
+ if missing:
75
+ raise ValueError(f"攻击图谱缺少必需顶层字段: {sorted(missing)}")
76
+ if not isinstance(payload.get("version"), str):
77
+ raise ValueError("攻击图谱 version 必须是字符串")
78
+ # 可选持久化字段:存在就必须是正确形状(缺失等价于「无历史」,不报错)。
79
+ if "meta" in payload and not isinstance(payload["meta"], Mapping):
80
+ raise ValueError("攻击图谱 meta 必须是对象")
81
+ if "events" in payload and not isinstance(payload["events"], list):
82
+ raise ValueError("攻击图谱 events 必须是数组")
83
+ if "reflex" in payload and not isinstance(payload["reflex"], Mapping):
84
+ raise ValueError("攻击图谱 reflex 必须是对象")
85
+ nodes = payload.get("nodes")
86
+ if not isinstance(nodes, Mapping):
87
+ raise ValueError("攻击图谱 nodes 必须是对象")
88
+ for key, required in _NODE_REQUIRED_FIELDS.items():
89
+ entries = nodes.get(key)
90
+ if entries is None:
91
+ continue
92
+ if not isinstance(entries, list):
93
+ raise ValueError(f"攻击图谱 nodes.{key} 必须是数组")
94
+ for entry in entries:
95
+ if not isinstance(entry, Mapping):
96
+ raise ValueError(f"攻击图谱 nodes.{key} 的元素必须是对象")
97
+ absent = [field for field in required if field not in entry]
98
+ if absent:
99
+ raise ValueError(
100
+ f"攻击图谱 nodes.{key} 元素缺少必需字段: {absent}"
101
+ )
102
+ edges = payload.get("edges")
103
+ if not isinstance(edges, list):
104
+ raise ValueError("攻击图谱 edges 必须是数组")
105
+ for edge in edges:
106
+ if not isinstance(edge, Mapping):
107
+ raise ValueError("攻击图谱 edges 的元素必须是对象")
108
+ absent = [field for field in ("from", "to", "relation") if field not in edge]
109
+ if absent:
110
+ raise ValueError(f"攻击图谱 edges 元素缺少必需字段: {absent}")
111
+
112
+
113
+ class StreamingEventBus:
114
+ """DOC-125 优化项 1: 内存级真流式事件总线 (In-Memory Streaming Event Bus)。
115
+
116
+ 支持事件订阅与即刻发布,实现资产发现与漏洞验证零批次延迟流水线推进 (Pipelining)。
117
+ """
118
+
119
+ def __init__(self) -> None:
120
+ self._listeners: dict[str, list[Any]] = {}
121
+ self.event_history: list[dict[str, Any]] = []
122
+
123
+ def subscribe(self, event_type: str, callback: Any) -> None:
124
+ """注册事件监听器。"""
125
+ self._listeners.setdefault(event_type, []).append(callback)
126
+
127
+ def publish(self, event_type: str, payload: Mapping[str, Any]) -> list[Any]:
128
+ """发布事件并即刻调用所有已注册监听器。"""
129
+ event_record = {
130
+ "event_type": event_type,
131
+ "payload": dict(payload),
132
+ "timestamp": time.time(),
133
+ }
134
+ self.event_history.append(event_record)
135
+ if len(self.event_history) > MAX_EVENT_JOURNAL:
136
+ del self.event_history[:-MAX_EVENT_JOURNAL]
137
+ results = []
138
+ for listener in self._listeners.get(event_type, []):
139
+ try:
140
+ res = listener(dict(payload))
141
+ results.append(res)
142
+ except Exception as exc:
143
+ results.append({"error": str(exc)})
144
+ return results
145
+
146
+ def clear(self) -> None:
147
+ """清理所有监听器与历史。"""
148
+ self._listeners.clear()
149
+ self.event_history.clear()
150
+
151
+
152
+ class LivingAttackGraph:
153
+ """BugX 统一动态攻击面图谱。"""
154
+
155
+ def __init__(self, version: str = "1.0.0") -> None:
156
+ self.version = version
157
+ self.roles: dict[str, dict[str, Any]] = {}
158
+ self.routes: dict[str, dict[str, Any]] = {}
159
+ self.parameters: dict[str, dict[str, Any]] = {}
160
+ self.sinks: dict[str, dict[str, Any]] = {}
161
+ self.hypotheses: dict[str, dict[str, Any]] = {}
162
+ self.edges: list[dict[str, Any]] = []
163
+ self.event_bus = StreamingEventBus()
164
+ self._snapshots: dict[str, dict[str, Any]] = {}
165
+ # --- DOC-125 持久化状态(随 to_dict/from_dict 往返,跨 Round 存活)---
166
+ # meta:图谱级观测数据(schema 降级事实、单元归属、计数器、轮次水位)。
167
+ self.meta: dict[str, Any] = {}
168
+ # events:StreamingEventBus 的落盘事件日志(总线本身是内存态,不持久)。
169
+ self.events: list[dict[str, Any]] = []
170
+ # reflex:回溯历史 + 回滚审计 + 待重放计划;快照拓扑另存 _snapshots。
171
+ self.reflex: dict[str, Any] = {
172
+ "backtrack_history": {},
173
+ "rollbacks": [],
174
+ "replay_pending": [],
175
+ "auto_fix_suggestions": [],
176
+ }
177
+ # 路径遍历搜索记忆化缓存 (DOC-137 2.0 / D137-03)
178
+ self._paths_cache: dict[tuple[str, str | None, int], list[list[dict[str, Any]]]] = {}
179
+
180
+ def validate(self) -> None:
181
+ """执行 Schema 校验(DES-10:校验不可用时显式降级,绝不静默放行)。
182
+
183
+ ``jsonschema`` 是可选依赖,未安装时旧实现直接 ``return``,导致 DOC-125
184
+ 的 schema 契约在生产环境从不被校验(死代码)。现在:
185
+
186
+ - 依赖与 schema 文件齐备时,走完整 JSON Schema 严格校验;
187
+ - 否则发出 ``RuntimeWarning`` 显式降级,并回落到内置轻量结构校验,
188
+ 对违反 Schema 必需字段的结构**失败即拒绝**(抛 ``ValueError``)。
189
+
190
+ 选择「告警 + 内置 fail-closed」而非直接抛错,是因为直接抛错会把可选
191
+ 依赖的缺失变成每一次合法图谱写入的硬失败(含本仓库无 jsonschema 的
192
+ 测试环境);而内置校验已覆盖 Schema 的 required 约束,信任边界仍然
193
+ 被守住,同时不会把可选依赖变成事实上的强依赖。
194
+ """
195
+ payload = self.to_dict()
196
+ if jsonschema is None or not SCHEMA_PATH.is_file():
197
+ reason = (
198
+ "未安装 jsonschema 依赖"
199
+ if jsonschema is None
200
+ else f"Schema 文件缺失: {SCHEMA_PATH}"
201
+ )
202
+ # DES-10/C125-13:只 warnings.warn 的话,降级在生产环境里无人可见——
203
+ # Worker 的 stderr 不会进证据链。把事实同时写进 meta,使「严格校验是否
204
+ # 真的跑过」可以从持久化快照里被审计出来。
205
+ self.meta["schema_validation"] = {
206
+ "mode": "builtin_degraded",
207
+ "strict_json_schema": False,
208
+ "jsonschema_available": jsonschema is not None,
209
+ "schema_path": str(SCHEMA_PATH),
210
+ "reason": reason,
211
+ "validated_at": time.time(),
212
+ }
213
+ warnings.warn(
214
+ f"攻击图谱 Schema 校验已降级({reason}):改用内置轻量结构校验,"
215
+ "严格 JSON Schema 约束未被执行。",
216
+ RuntimeWarning,
217
+ stacklevel=2,
218
+ )
219
+ _validate_structure_builtin(payload)
220
+ return
221
+ with open(SCHEMA_PATH, "r", encoding="utf-8") as sf:
222
+ schema = json.load(sf)
223
+ jsonschema.validate(instance=payload, schema=schema)
224
+ self.meta["schema_validation"] = {
225
+ "mode": "jsonschema",
226
+ "strict_json_schema": True,
227
+ "jsonschema_available": True,
228
+ "schema_path": str(SCHEMA_PATH),
229
+ "validated_at": time.time(),
230
+ }
231
+
232
+ def add_role(self, role_id: str, role_type: str, **attrs: Any) -> dict[str, Any]:
233
+ """添加或更新身份角色节点 (例如 role:admin, role:user_a)。"""
234
+ node = {"id": role_id, "type": role_type, **attrs}
235
+ self.roles[role_id] = node
236
+ if hasattr(self, "event_bus"):
237
+ self.event_bus.publish("node_added", node)
238
+ return node
239
+
240
+ def add_route(self, route_id: str, method: str, auth_required: bool, **attrs: Any) -> dict[str, Any]:
241
+ """添加或更新 API 路由端点节点 (例如 route:/api/v1/orders/{id})。"""
242
+ node = {"id": route_id, "method": method.upper(), "auth_required": bool(auth_required), **attrs}
243
+ self.routes[route_id] = node
244
+ if hasattr(self, "event_bus"):
245
+ self.event_bus.publish("node_added", node)
246
+ return node
247
+
248
+ def add_parameter(self, param_id: str, name: str, **attrs: Any) -> dict[str, Any]:
249
+ """添加或更新参数节点 (例如 param:order_id)。"""
250
+ node = {"id": param_id, "name": name, **attrs}
251
+ self.parameters[param_id] = node
252
+ return node
253
+
254
+ def add_sink(self, sink_id: str, kind: str, **attrs: Any) -> dict[str, Any]:
255
+ """添加或更新危险汇聚点节点 (例如 sink:sql_query, sink:cmd_exec)。"""
256
+ node = {"id": sink_id, "kind": kind, **attrs}
257
+ self.sinks[sink_id] = node
258
+ if hasattr(self, "_paths_cache"):
259
+ self._paths_cache.clear()
260
+ return node
261
+
262
+ def add_hypothesis(
263
+ self,
264
+ hypothesis_id: str,
265
+ hyp_type: str,
266
+ target: str,
267
+ status: str = "proposed",
268
+ **attrs: Any,
269
+ ) -> dict[str, Any]:
270
+ """添加攻防假设节点 (例如 hypo:idor_orders)。"""
271
+ node = {
272
+ "id": hypothesis_id,
273
+ "type": hyp_type,
274
+ "target": target,
275
+ "status": status,
276
+ **attrs,
277
+ }
278
+ self.hypotheses[hypothesis_id] = node
279
+ if hasattr(self, "event_bus"):
280
+ self.event_bus.publish("hypothesis_added", node)
281
+ return node
282
+
283
+ def update_hypothesis_status(self, hypothesis_id: str, status: str, reason: str = "") -> None:
284
+ """推进或回溯假设状态 (proposed -> testing -> verified / refuted / not_applicable)。"""
285
+ if hypothesis_id in self.hypotheses:
286
+ self.hypotheses[hypothesis_id]["status"] = status
287
+ if reason:
288
+ self.hypotheses[hypothesis_id]["status_reason"] = reason
289
+
290
+ def add_edge(
291
+ self,
292
+ source: str,
293
+ target: str,
294
+ relation: str,
295
+ hypothesis_id: str | None = None,
296
+ ) -> dict[str, Any]:
297
+ """添加实体间的拓扑关系边。"""
298
+ edge = {"from": source, "to": target, "relation": relation}
299
+ if hypothesis_id:
300
+ edge["hypothesis_id"] = hypothesis_id
301
+ # 避免重复边
302
+ for existing in self.edges:
303
+ if (
304
+ existing.get("from") == source
305
+ and existing.get("to") == target
306
+ and existing.get("relation") == relation
307
+ and existing.get("hypothesis_id") == hypothesis_id
308
+ ):
309
+ return existing
310
+ self.edges.append(edge)
311
+ if hasattr(self, "_paths_cache"):
312
+ self._paths_cache.clear()
313
+ if hasattr(self, "event_bus"):
314
+ self.event_bus.publish("edge_added", edge)
315
+ return edge
316
+
317
+ def get_illegal_access_edges(self) -> list[dict[str, Any]]:
318
+ """获取所有已实锤的非法越权边 (Illegal Access Edges)。"""
319
+ return [e for e in self.edges if e.get("relation") in ILLEGAL_ACCESS_RELATIONS]
320
+
321
+ def find_attack_paths(
322
+ self,
323
+ source_id: str,
324
+ target_id: str | None = None,
325
+ max_depth: int = 5,
326
+ ) -> list[list[dict[str, Any]]]:
327
+ """DOC-125 优化项 2: 多跳攻击路径拓扑求解器 (Multi-Hop Path Traversal)。
328
+
329
+ 求解从起点 (如 role:user_b) 出发,到达目标 (如 sink:sql 或 route:xxx)
330
+ 的所有可行攻击链路,自动剪枝防环路,深度限制 <= max_depth。
331
+ 使用 _paths_cache 进行路径遍历记忆化缓存 (DOC-137 2.0 / D137-03)。
332
+ """
333
+ cache_key = (source_id, target_id, max_depth)
334
+ if hasattr(self, "_paths_cache") and cache_key in self._paths_cache:
335
+ return copy.deepcopy(self._paths_cache[cache_key])
336
+
337
+ paths: list[list[dict[str, Any]]] = []
338
+ adj: dict[str, list[dict[str, Any]]] = {}
339
+ for edge in self.edges:
340
+ src = edge.get("from")
341
+ if src:
342
+ adj.setdefault(src, []).append(edge)
343
+
344
+ def dfs(curr: str, visited: set[str], current_path: list[dict[str, Any]]) -> None:
345
+ if len(current_path) >= max_depth:
346
+ return
347
+ for edge in adj.get(curr, []):
348
+ dst = edge.get("to")
349
+ if not dst or dst in visited:
350
+ continue
351
+ next_path = current_path + [edge]
352
+ is_hit = False
353
+ if target_id is not None:
354
+ if dst == target_id or (target_id in ("sink:", "sink:*") and dst in self.sinks):
355
+ is_hit = True
356
+ else:
357
+ if dst in self.sinks or edge.get("relation") in ILLEGAL_ACCESS_RELATIONS:
358
+ is_hit = True
359
+
360
+ if is_hit:
361
+ paths.append(next_path)
362
+ visited.add(dst)
363
+ dfs(dst, visited, next_path)
364
+ visited.remove(dst)
365
+
366
+ dfs(source_id, {source_id}, [])
367
+ if hasattr(self, "_paths_cache"):
368
+ self._paths_cache[cache_key] = copy.deepcopy(paths)
369
+ return copy.deepcopy(paths)
370
+
371
+ def find_cross_tenant_paths(self, role_a: str, role_b: str) -> list[dict[str, Any]]:
372
+ """求解角色 A 是否存在未经授权访问角色 B 所属私有资源的边。"""
373
+ owned_by_b = {
374
+ e["to"] for e in self.edges
375
+ if e.get("from") == role_b and "LEGITIMATE" in e.get("relation", "")
376
+ }
377
+ cross = [
378
+ e for e in self.edges
379
+ if (
380
+ e.get("from") == role_a
381
+ and e.get("to") in owned_by_b
382
+ and e.get("relation") in ILLEGAL_ACCESS_RELATIONS
383
+ )
384
+ ]
385
+ return cross
386
+
387
+ def create_snapshot(self, tag: str = "") -> str:
388
+ """DOC-125 优化项 9: 创建图谱拓扑增量快照 (Incremental Snapshot)。"""
389
+ ts = time.time()
390
+ snapshot_id = f"snap_{int(ts * 1000)}_{len(self._snapshots) + 1}"
391
+ if len(self._snapshots) >= 10:
392
+ oldest_key = next(iter(self._snapshots))
393
+ del self._snapshots[oldest_key]
394
+
395
+ self._snapshots[snapshot_id] = {
396
+ "snapshot_id": snapshot_id,
397
+ "tag": tag or f"snapshot_{snapshot_id}",
398
+ "timestamp": ts,
399
+ "roles": copy.deepcopy(self.roles),
400
+ "routes": copy.deepcopy(self.routes),
401
+ "parameters": copy.deepcopy(self.parameters),
402
+ "sinks": copy.deepcopy(self.sinks),
403
+ "hypotheses": copy.deepcopy(self.hypotheses),
404
+ "edges": copy.deepcopy(self.edges),
405
+ }
406
+ return snapshot_id
407
+
408
+ def rollback_to_snapshot(self, snapshot_id: str) -> bool:
409
+ """DOC-125 优化项 9: 时间旅行回滚至指定快照。"""
410
+ if snapshot_id not in self._snapshots:
411
+ return False
412
+ snap = self._snapshots[snapshot_id]
413
+ self.roles = copy.deepcopy(snap["roles"])
414
+ self.routes = copy.deepcopy(snap["routes"])
415
+ self.parameters = copy.deepcopy(snap["parameters"])
416
+ self.sinks = copy.deepcopy(snap["sinks"])
417
+ self.hypotheses = copy.deepcopy(snap["hypotheses"])
418
+ self.edges = copy.deepcopy(snap["edges"])
419
+ if hasattr(self, "_paths_cache"):
420
+ self._paths_cache.clear()
421
+ if hasattr(self, "event_bus"):
422
+ self.event_bus.publish("snapshot_rollback", {"snapshot_id": snapshot_id, "tag": snap.get("tag", "")})
423
+ return True
424
+
425
+ def list_snapshots(self) -> list[dict[str, Any]]:
426
+ """DOC-125 优化项 9: 列出当前保留的快照列表。"""
427
+ return [
428
+ {
429
+ "snapshot_id": s["snapshot_id"],
430
+ "tag": s.get("tag", ""),
431
+ "timestamp": s["timestamp"],
432
+ "roles_count": len(s["roles"]),
433
+ "routes_count": len(s["routes"]),
434
+ "edges_count": len(s["edges"]),
435
+ }
436
+ for s in self._snapshots.values()
437
+ ]
438
+
439
+ def find_entrypoints_for_sink(
440
+ self,
441
+ sink_id: str,
442
+ max_depth: int = 5,
443
+ ) -> list[dict[str, Any]]:
444
+ """DOC-125 优化项 11: 高危汇点 (Sink) 反向污点入口推演。
445
+
446
+ 从危险汇聚点 (如 sink:sql_query, sink:cmd_exec) 出发逆向拓扑回溯,
447
+ 求解所有可达该汇点的候选入口端点 (route:*) 与参数 (param:*)。
448
+ """
449
+ in_adj: dict[str, list[dict[str, Any]]] = {}
450
+ for edge in self.edges:
451
+ dst = edge.get("to")
452
+ if dst:
453
+ in_adj.setdefault(dst, []).append(edge)
454
+
455
+ entrypoints: list[dict[str, Any]] = []
456
+ visited: set[str] = set()
457
+
458
+ def backward_dfs(curr: str, depth: int, path: list[dict[str, Any]]) -> None:
459
+ if depth >= max_depth:
460
+ return
461
+ for edge in in_adj.get(curr, []):
462
+ src = edge.get("from")
463
+ if not src or src in visited:
464
+ continue
465
+ visited.add(src)
466
+ new_path = [edge] + path
467
+ if src.startswith("route:") or src in self.routes:
468
+ entrypoints.append({
469
+ "entrypoint": src,
470
+ "sink_id": sink_id,
471
+ "distance": depth + 1,
472
+ "path": new_path,
473
+ })
474
+ backward_dfs(src, depth + 1, new_path)
475
+ visited.remove(src)
476
+
477
+ backward_dfs(sink_id, 0, [])
478
+ return entrypoints
479
+
480
+ def to_dict(self) -> dict[str, Any]:
481
+ """导出为符合 Schema 的标准字典。
482
+
483
+ DOC-125 闭环:``meta`` / ``events`` / ``reflex`` 让图谱从「一次性结构」变成
484
+ 「跨 Round 累积的会话级状态」——事件日志、单元归属与回溯历史必须一起落盘,
485
+ 否则消费者读到的永远是空图。``reflex.snapshots`` 承接 ``create_snapshot``
486
+ 的拓扑快照,使 ``rollback_to_snapshot`` 在重新 load 之后仍然可用。
487
+ """
488
+ return {
489
+ "version": self.version,
490
+ "nodes": {
491
+ "roles": copy.deepcopy(list(self.roles.values())),
492
+ "routes": copy.deepcopy(list(self.routes.values())),
493
+ "parameters": copy.deepcopy(list(self.parameters.values())),
494
+ "sinks": copy.deepcopy(list(self.sinks.values())),
495
+ "hypotheses": copy.deepcopy(list(self.hypotheses.values())),
496
+ },
497
+ "edges": copy.deepcopy(self.edges),
498
+ "meta": copy.deepcopy(self.meta),
499
+ "events": copy.deepcopy(self.events[-MAX_EVENT_JOURNAL:]),
500
+ "reflex": {
501
+ **{
502
+ key: value
503
+ for key, value in self.reflex.items()
504
+ if key != "snapshots"
505
+ },
506
+ "snapshots": copy.deepcopy(
507
+ dict(list(self._snapshots.items())[-MAX_PERSISTED_SNAPSHOTS:])
508
+ ),
509
+ },
510
+ }
511
+
512
+ @classmethod
513
+ def from_dict(cls, data: Mapping[str, Any]) -> LivingAttackGraph:
514
+ """从字典反序列化图谱。"""
515
+ graph = cls(version=str(data.get("version") or "1.0.0"))
516
+ nodes = data.get("nodes") or {}
517
+ for r in nodes.get("roles") or []:
518
+ graph.add_role(r["id"], r.get("type", "unknown"), **{k: v for k, v in r.items() if k not in ("id", "type")})
519
+ for r in nodes.get("routes") or []:
520
+ graph.add_route(r["id"], r.get("method", "GET"), r.get("auth_required", False), **{k: v for k, v in r.items() if k not in ("id", "method", "auth_required")})
521
+ for p in nodes.get("parameters") or []:
522
+ graph.add_parameter(p["id"], p.get("name", ""), **{k: v for k, v in p.items() if k not in ("id", "name")})
523
+ for s in nodes.get("sinks") or []:
524
+ graph.add_sink(s["id"], s.get("kind", ""), **{k: v for k, v in s.items() if k not in ("id", "kind")})
525
+ for h in nodes.get("hypotheses") or []:
526
+ graph.add_hypothesis(h["id"], h.get("type", ""), h.get("target", ""), h.get("status", "proposed"), **{k: v for k, v in h.items() if k not in ("id", "type", "target", "status")})
527
+ for e in data.get("edges") or []:
528
+ graph.add_edge(e["from"], e["to"], e["relation"], e.get("hypothesis_id"))
529
+ meta = data.get("meta")
530
+ if isinstance(meta, Mapping):
531
+ graph.meta = copy.deepcopy(dict(meta))
532
+ events = data.get("events")
533
+ if isinstance(events, list):
534
+ graph.events = copy.deepcopy(
535
+ [item for item in events if isinstance(item, Mapping)]
536
+ )
537
+ reflex = data.get("reflex")
538
+ if isinstance(reflex, Mapping):
539
+ restored = copy.deepcopy(dict(reflex))
540
+ snapshots = restored.pop("snapshots", None)
541
+ if isinstance(snapshots, Mapping):
542
+ # 只接受形状完整的快照,避免手工篡改的快照把回滚变成 KeyError。
543
+ graph._snapshots = {
544
+ str(key): value
545
+ for key, value in snapshots.items()
546
+ if isinstance(value, Mapping)
547
+ and all(
548
+ field in value
549
+ for field in ("snapshot_id", "roles", "routes", "sinks",
550
+ "hypotheses", "edges")
551
+ )
552
+ }
553
+ defaults = graph.reflex
554
+ for key, value in defaults.items():
555
+ if key not in restored:
556
+ restored[key] = value
557
+ graph.reflex = restored
558
+ return graph
559
+
560
+
561
+ def evaluate_runnable_tasks(
562
+ graph: LivingAttackGraph,
563
+ completed_stages: set[str] | None = None,
564
+ ) -> list[dict[str, Any]]:
565
+ """DOC-125: 流式 DAG 任务求值器 (Streaming DAG Evaluator)。
566
+
567
+ 根据图谱当前节点状态(routes, roles, parameters, hypotheses)以及已完成阶段,
568
+ 计算出所有前置依赖满足的最小可并行执行任务清单。
569
+
570
+ 调度逻辑:
571
+ 1. 若 00-scope 未就绪(completed_stages 为空且无 routes),产生 00-scope 资产发现任务;
572
+ 2. 对于公共端点 (auth_required == False):
573
+ - 若未完成 input-output 测试,立即生成 40-input-output 任务 (affinity="exploit");
574
+ 3. 对于受保护鉴权端点 (auth_required == True):
575
+ - 若尚未获取至少 2 个有效角色凭证 (len(roles) < 2 且 20-auth-session 未完成):生成 20-auth-session 任务 (affinity="auth");
576
+ - 若已有有效身份凭证:生成 30-authz-business 任务 (affinity="logic");
577
+ 4. 对于含状态异步/并发特征的端点:生成 50-state-async 任务 (affinity="logic");
578
+ 5. 全局收敛栅栏 (80-evidence-regression):
579
+ - 必须在所有已发现端点已测试,且存在已实锤/待验证假设时,放行最终红绿对照复现任务 (affinity="exploit")。
580
+ """
581
+ completed = set(completed_stages or [])
582
+ tasks: list[dict[str, Any]] = []
583
+
584
+ # 1. 资产侦察流
585
+ if "00-scope" not in completed and not graph.routes:
586
+ tasks.append({
587
+ "task_id": "task:00-scope",
588
+ "stage_id": "00-scope",
589
+ "affinity": "recon",
590
+ "tier": "FAST",
591
+ "description": "界定审计范围与资产边界清单",
592
+ })
593
+ return tasks
594
+
595
+ # 2. 流式端点分流派发
596
+ has_credentials = len(graph.roles) >= 2 or "20-auth-session" in completed
597
+ untested_routes = 0
598
+
599
+ for route_id, route in graph.routes.items():
600
+ tested_stages = set(route.get("tested_stages") or [])
601
+ auth_req = route.get("auth_required", False)
602
+
603
+ if not auth_req:
604
+ # 公共端点流 -> 40-input-output
605
+ if "40-input-output" not in tested_stages:
606
+ untested_routes += 1
607
+ tasks.append({
608
+ "task_id": f"task:input-output:{route_id}",
609
+ "stage_id": "40-input-output",
610
+ "target_route": route_id,
611
+ "affinity": "exploit",
612
+ "tier": "PRO",
613
+ "description": f"公共端点参数与注入挖掘: {route.get('method', 'GET')} {route_id}",
614
+ })
615
+ else:
616
+ # 鉴权端点流
617
+ if not has_credentials:
618
+ if not any(t["stage_id"] == "20-auth-session" for t in tasks):
619
+ tasks.append({
620
+ "task_id": "task:20-auth-session",
621
+ "stage_id": "20-auth-session",
622
+ "affinity": "auth",
623
+ "tier": "BALANCED",
624
+ "description": "提取多角色凭证矩阵与 Session 状态机",
625
+ })
626
+ else:
627
+ if "30-authz-business" not in tested_stages:
628
+ untested_routes += 1
629
+ tasks.append({
630
+ "task_id": f"task:authz:{route_id}",
631
+ "stage_id": "30-authz-business",
632
+ "target_route": route_id,
633
+ "affinity": "logic",
634
+ "tier": "PRO",
635
+ "description": f"鉴权端点越权/IDOR/跨租户推演: {route.get('method', 'GET')} {route_id}",
636
+ })
637
+
638
+ # 异步状态特征流
639
+ if route.get("has_async_state") and "50-state-async" not in tested_stages and "30-authz-business" in tested_stages:
640
+ tasks.append({
641
+ "task_id": f"task:state-async:{route_id}",
642
+ "stage_id": "50-state-async",
643
+ "target_route": route_id,
644
+ "affinity": "logic",
645
+ "tier": "PRO",
646
+ "description": f"异步并发条件竞争与状态机测试: {route.get('method', 'GET')} {route_id}",
647
+ })
648
+
649
+ # 3. 阶段栅栏:80-evidence-regression 全局硬收敛
650
+ verified_hypotheses = [h for h in graph.hypotheses.values() if h.get("status") == "verified"]
651
+ if untested_routes == 0 and verified_hypotheses and "80-evidence-regression" not in completed:
652
+ tasks.append({
653
+ "task_id": "task:80-evidence-regression",
654
+ "stage_id": "80-evidence-regression",
655
+ "affinity": "exploit",
656
+ "tier": "PRO",
657
+ "barrier": True,
658
+ "description": f"收敛栅栏放行:对 {len(verified_hypotheses)} 个实锤漏洞执行确定性红绿回放与负向对照验证",
659
+ })
660
+
661
+ # 4. DOC-125 优化项 11: 高危汇点 (Sink) 反向污点推演与任务优先级动态加权
662
+ high_risk_routes: set[str] = set()
663
+ for s_id, s_node in graph.sinks.items():
664
+ kind = str(s_node.get("kind", "")).lower()
665
+ if any(k in kind for k in ("sql", "rce", "cmd", "exec", "file", "ssrf")):
666
+ for ep in graph.find_entrypoints_for_sink(s_id):
667
+ high_risk_routes.add(ep["entrypoint"])
668
+
669
+ for t in tasks:
670
+ r_id = t.get("target_route")
671
+ pri = 10
672
+ if t.get("barrier"):
673
+ pri = 1000 # 收敛栅栏绝对优先
674
+ elif r_id and r_id in high_risk_routes:
675
+ pri = 100 # 可达高危汇点端点享有最高优先级
676
+ elif t.get("stage_id") == "30-authz-business":
677
+ pri = 50 # 鉴权/越权推演次优
678
+ elif t.get("stage_id") == "20-auth-session":
679
+ pri = 60 # 凭证矩阵优先获取
680
+ elif t.get("stage_id") == "00-scope":
681
+ pri = 20
682
+ t["priority"] = pri
683
+
684
+ # 按 priority 降序排列 (最高优先级任务排在队首)
685
+ tasks.sort(key=lambda x: x.get("priority", 0), reverse=True)
686
+ return tasks
687
+
688
+
689
+ class ReflexiveBacktrackingEngine:
690
+ """DOC-125: 假设驱动的反思回溯验证引擎 (Reflexive Backtracking Engine)。
691
+
692
+ 当 Worker 沙箱验证遇到 403 签名错误、401 凭证过期或 429 限流等阻碍时,
693
+ 驱动假设状态机反思修正,定向反查代码,重新构造请求(最大深度 <= 2)。
694
+ """
695
+
696
+ MAX_BACKTRACK_DEPTH = 2
697
+
698
+ STATUS_PROPOSED = "proposed"
699
+ STATUS_TESTING = "testing"
700
+ STATUS_BLOCKED = "blocked"
701
+ STATUS_BACKTRACKING = "backtracking"
702
+ STATUS_SUSPECTED = "suspected"
703
+ STATUS_VERIFIED = "verified"
704
+ STATUS_REFUTED = "refuted"
705
+ STATUS_NOT_APPLICABLE = "not_applicable"
706
+
707
+ BLOCKED_403_SIGNATURE = "HTTP_403_SIGNATURE_MISMATCH"
708
+ BLOCKED_401_TOKEN = "HTTP_401_TOKEN_EXPIRED"
709
+ BLOCKED_429_RATE_LIMIT = "HTTP_429_RATE_LIMITED"
710
+ BLOCKED_WAF = "WAF_PAYLOAD_DETECTED"
711
+
712
+ def __init__(
713
+ self,
714
+ graph: LivingAttackGraph,
715
+ *,
716
+ secret_key: str | None = None,
717
+ available_tokens: Iterable[str] | None = None,
718
+ ) -> None:
719
+ self.graph = graph
720
+ self.secret_key = secret_key.strip() if isinstance(secret_key, str) and secret_key.strip() else None
721
+ self.available_tokens = tuple(
722
+ token.strip() for token in (available_tokens or ())
723
+ if isinstance(token, str) and token.strip()
724
+ )
725
+ # 记录各假设的回溯追踪: hypothesis_id -> list[attempt_record]
726
+ # DOC-125 闭环:这里**直接别名**到 graph.reflex,而不是自建一份内存字典。
727
+ # 否则 record_attempt 的历史随进程结束蒸发,回溯深度在第 2 次尝试时被重置,
728
+ # MAX_BACKTRACK_DEPTH 门禁跨 Round 失效,消费者也永远读不到 backtrack_history。
729
+ history = graph.reflex.setdefault("backtrack_history", {})
730
+ if not isinstance(history, dict):
731
+ history = {}
732
+ graph.reflex["backtrack_history"] = history
733
+ self.backtrack_history = history
734
+
735
+ def start_testing(self, hypothesis_id: str) -> None:
736
+ """开始测试假设。"""
737
+ self.graph.update_hypothesis_status(hypothesis_id, self.STATUS_TESTING, "开始执行沙箱测试")
738
+
739
+ def build_dpo_pair(self, hypothesis_id: str) -> dict[str, Any] | None:
740
+ """DOC-126 DES-14: 合成反思回溯成功假设的 DPO 偏好对 (prompt, chosen, rejected)。"""
741
+ history = self.backtrack_history.get(hypothesis_id, [])
742
+ if len(history) < 2:
743
+ return None
744
+ if not history[-1].get("is_exploit_successful"):
745
+ return None
746
+ hypothesis = self.graph.hypotheses.get(hypothesis_id, {})
747
+ prompt = hypothesis.get("description") or f"Audit exploit for {hypothesis_id}"
748
+ chosen = [history[-1]]
749
+ rejected = history[:-1]
750
+ obstacle_types = []
751
+ for r in rejected:
752
+ reason = str(r.get("blocked_reason") or "")
753
+ if reason and reason not in obstacle_types:
754
+ obstacle_types.append(reason)
755
+ has_neg = any(h.get("has_negative_control") for h in history)
756
+ try:
757
+ from core.cloud_sync.flywheel_client import build_dpo_preference_pair
758
+ return build_dpo_preference_pair(
759
+ prompt=prompt,
760
+ chosen=chosen,
761
+ rejected=rejected,
762
+ metadata={
763
+ "hypothesis_id": hypothesis_id,
764
+ "target_route": hypothesis.get("target_route"),
765
+ "vulnerability_type": hypothesis.get("vulnerability_type"),
766
+ "backtrack_depth": len(history),
767
+ "has_negative_control": has_neg,
768
+ "obstacle_types": obstacle_types,
769
+ },
770
+ )
771
+ except Exception:
772
+ return {
773
+ "prompt": prompt,
774
+ "chosen": chosen,
775
+ "rejected": rejected,
776
+ "metadata": {
777
+ "hypothesis_id": hypothesis_id,
778
+ "has_negative_control": has_neg,
779
+ "obstacle_types": obstacle_types,
780
+ },
781
+ }
782
+
783
+ def record_attempt(
784
+ self,
785
+ hypothesis_id: str,
786
+ *,
787
+ status_code: int,
788
+ response_body: str = "",
789
+ is_exploit_successful: bool = False,
790
+ has_negative_control: bool = False,
791
+ request_context: Mapping[str, Any] | None = None,
792
+ ) -> dict[str, Any]:
793
+ """记录一次测试尝试结果,并判定是否进入反思回溯、实锤或阻断。"""
794
+ history = self.backtrack_history.setdefault(hypothesis_id, [])
795
+ depth = len(history)
796
+
797
+ record = {
798
+ "attempt_index": depth + 1,
799
+ "status_code": status_code,
800
+ "body_snippet": response_body[:200],
801
+ "is_exploit_successful": is_exploit_successful,
802
+ "has_negative_control": has_negative_control,
803
+ "request_context": dict(request_context or {}),
804
+ }
805
+ history.append(record)
806
+
807
+ # 1. 验证实锤分支:利用成功且具备负向对照。单独的 2xx
808
+ # 响应只能说明请求成功,不能证明漏洞成立。
809
+ if is_exploit_successful and has_negative_control:
810
+ self.graph.update_hypothesis_status(
811
+ hypothesis_id,
812
+ self.STATUS_VERIFIED,
813
+ reason="利用成功并完成对照验证",
814
+ )
815
+ dpo_pair = self.build_dpo_pair(hypothesis_id)
816
+ res = {
817
+ "status": self.STATUS_VERIFIED,
818
+ "action": "commit_evidence",
819
+ "current_depth": depth + 1,
820
+ "advice": "漏洞实锤成立!请提交正向利用证据与负向对照报文。",
821
+ }
822
+ if dpo_pair:
823
+ res["dpo_preference_pair"] = dpo_pair
824
+ return res
825
+ if is_exploit_successful:
826
+ self.graph.update_hypothesis_status(
827
+ hypothesis_id,
828
+ self.STATUS_SUSPECTED,
829
+ reason="正向请求成功,但尚未完成负向对照验证",
830
+ )
831
+ return {
832
+ "status": self.STATUS_SUSPECTED,
833
+ "action": "hold_for_negative_control",
834
+ "current_depth": depth + 1,
835
+ "advice": "保留为疑似结果;必须补充负向对照后才能确认为漏洞。",
836
+ }
837
+
838
+ # 2. 遇阻分支:判断是否可反思回溯
839
+ blocked_reason = ""
840
+ advice = ""
841
+
842
+ if status_code == 403 and any(w in response_body.lower() for w in ("sign", "signature", "nonce", "timestamp")):
843
+ blocked_reason = self.BLOCKED_403_SIGNATURE
844
+ advice = "检测到签名/防重放拦截:请定向反查控制器/拦截器代码,提取签名生成算法与密钥,修正 Header 后重试。"
845
+ elif status_code == 401:
846
+ blocked_reason = self.BLOCKED_401_TOKEN
847
+ advice = "检测到身份凭证失效:请调用 20-auth-session 刷新 Token 或更换测试身份。"
848
+ elif status_code == 429:
849
+ blocked_reason = self.BLOCKED_429_RATE_LIMIT
850
+ advice = "触发频率限制拦截:实施指数退避并降低并发发包速率。"
851
+ elif "waf" in response_body.lower() or "blocked by security" in response_body.lower():
852
+ blocked_reason = self.BLOCKED_WAF
853
+ advice = "触发安全过滤器/WAF硬拦截:对测试 Payload 实施混淆/多层编码变异。"
854
+ else:
855
+ # 业务明确拒绝或无漏洞特征
856
+ if status_code in (403, 404):
857
+ self.graph.update_hypothesis_status(
858
+ hypothesis_id,
859
+ self.STATUS_REFUTED,
860
+ reason=f"目标明确拒绝请求 (HTTP {status_code}),假设不成立",
861
+ )
862
+ return {
863
+ "status": self.STATUS_REFUTED,
864
+ "action": "close_hypothesis",
865
+ "current_depth": depth + 1,
866
+ "advice": "目标正常鉴权拦截,假设被反驳。",
867
+ }
868
+
869
+ record["blocked_reason"] = blocked_reason
870
+
871
+ # 3. 反思深度判定 (硬上限 <= 2)
872
+ if depth + 1 >= self.MAX_BACKTRACK_DEPTH:
873
+ self.graph.update_hypothesis_status(
874
+ hypothesis_id,
875
+ self.STATUS_NOT_APPLICABLE,
876
+ reason=f"反思回溯深度超限 ({self.MAX_BACKTRACK_DEPTH} 次),放弃进一步尝试",
877
+ )
878
+ return {
879
+ "status": self.STATUS_NOT_APPLICABLE,
880
+ "action": "abort_exhausted",
881
+ "current_depth": depth + 1,
882
+ "advice": f"已达最大反思回溯深度 ({self.MAX_BACKTRACK_DEPTH}),标记 not_applicable 并释放。",
883
+ }
884
+
885
+ # 4. 触发反思回溯
886
+ self.graph.update_hypothesis_status(
887
+ hypothesis_id,
888
+ self.STATUS_BACKTRACKING,
889
+ reason=f"遇到阻碍 ({blocked_reason}),进入反思回溯环",
890
+ )
891
+ heuristic_fix = HeuristicAutoFixer.diagnose_and_suggest_fix(
892
+ status_code=status_code,
893
+ response_body=response_body,
894
+ last_request=request_context,
895
+ available_tokens=self.available_tokens,
896
+ secret_key=self.secret_key,
897
+ )
898
+ auto_fixed = (
899
+ heuristic_fix.get("patch_headers") if heuristic_fix
900
+ else HeuristicAutoFixer.fix_request_headers(
901
+ blocked_reason,
902
+ {},
903
+ available_tokens=self.available_tokens,
904
+ secret_key=self.secret_key,
905
+ )
906
+ )
907
+ return {
908
+ "status": self.STATUS_BACKTRACKING,
909
+ "action": "reflexive_retry",
910
+ "blocked_reason": blocked_reason,
911
+ "current_depth": depth + 1,
912
+ "advice": advice,
913
+ "heuristic_fix": heuristic_fix,
914
+ "suggested_headers": auto_fixed,
915
+ }
916
+
917
+ def execute_in_situ_fast_replay(
918
+ self,
919
+ hypothesis_id: str,
920
+ patch_headers: Mapping[str, str],
921
+ sender_fn: Any,
922
+ *,
923
+ target_fingerprint: str | None = None,
924
+ ) -> dict[str, Any]:
925
+ """DOC-125 优化项 10: 启发式修包就地免 LLM 快速重放闭环 (In-Situ Fast Replay)。
926
+
927
+ 直接调用传入的网络发包回调在沙箱网络栈快速试探 1 次。
928
+ 若直接命中利用成功 (status 200/201/204 或 is_exploit_successful=True),
929
+ 直接推进至 verified 状态并固化证据,免去一次昂贵的大模型推理往返。
930
+ """
931
+ expected_target = (
932
+ target_fingerprint.strip()
933
+ if isinstance(target_fingerprint, str)
934
+ else ""
935
+ )
936
+ try:
937
+ bound_target = str(getattr(sender_fn, "target_fingerprint", "")).strip()
938
+ except Exception:
939
+ bound_target = ""
940
+ if not expected_target or bound_target != expected_target:
941
+ return {
942
+ "fast_replay_attempted": False,
943
+ "success": False,
944
+ "action": "blocked_target_binding",
945
+ "error": (
946
+ "快速重放必须绑定 target_fingerprint,且必须与 sender_fn 声明一致"
947
+ ),
948
+ }
949
+ try:
950
+ resp = sender_fn(dict(patch_headers))
951
+ except Exception as exc:
952
+ return {
953
+ "fast_replay_attempted": True,
954
+ "success": False,
955
+ "error": str(exc),
956
+ "action": "fallback_to_llm",
957
+ }
958
+
959
+ status_code = int(resp.get("status_code", 0))
960
+ is_success = bool(resp.get("is_exploit_successful", False))
961
+ has_negative = bool(resp.get("has_negative_control", False))
962
+
963
+ if is_success and has_negative:
964
+ self.graph.update_hypothesis_status(
965
+ hypothesis_id,
966
+ self.STATUS_VERIFIED,
967
+ reason="启发式修包就地快速重放成功实锤 (Zero-LLM Fast Path)",
968
+ )
969
+ return {
970
+ "fast_replay_attempted": True,
971
+ "success": True,
972
+ "status": self.STATUS_VERIFIED,
973
+ "action": "commit_evidence_fast_path",
974
+ "status_code": status_code,
975
+ "advice": "就地重放成功!已绕过大模型推理直接确权实锤。",
976
+ }
977
+
978
+ if is_success or status_code in (200, 201, 204):
979
+ self.graph.update_hypothesis_status(
980
+ hypothesis_id,
981
+ self.STATUS_SUSPECTED,
982
+ reason="快速重放成功但缺少负向对照",
983
+ )
984
+ return {
985
+ "fast_replay_attempted": True,
986
+ "success": False,
987
+ "status": self.STATUS_SUSPECTED,
988
+ "status_code": status_code,
989
+ "action": "hold_for_negative_control",
990
+ "advice": "快速重放仅形成疑似结果,补充负向对照后再确权。",
991
+ }
992
+
993
+ return {
994
+ "fast_replay_attempted": True,
995
+ "success": False,
996
+ "status_code": status_code,
997
+ "action": "fallback_to_llm",
998
+ "advice": "就地快速重放未成功,继续由大模型进行深度反思。",
999
+ }
1000
+
1001
+
1002
+ class HeuristicAutoFixer:
1003
+ """DOC-125 优化项 3: 常见阻碍启发式自动修包引擎 (Heuristic Auto-Fixer)。
1004
+
1005
+ 针对 403 签名/防重放缺失、401 凭证过期或 Content-Type 畸变,
1006
+ 在回溯层自动尝试生成修正 Header,先免模型重放一次。
1007
+ """
1008
+
1009
+ @classmethod
1010
+ def diagnose_and_suggest_fix(
1011
+ cls,
1012
+ status_code: int,
1013
+ response_body: str,
1014
+ last_request: Mapping[str, Any] | None = None,
1015
+ available_tokens: Iterable[str] | None = None,
1016
+ secret_key: str | None = None,
1017
+ ) -> dict[str, Any] | None:
1018
+ """根据 HTTP 响应状态码及响应体智能诊断并生成修包补丁。"""
1019
+ req = dict(last_request or {})
1020
+ headers = dict(req.get("headers") or {})
1021
+ body_lower = response_body.lower()
1022
+
1023
+ if status_code == 403 and any(k in body_lower for k in ("sign", "timestamp", "nonce", "expire")):
1024
+ if not secret_key:
1025
+ return None
1026
+ now_str = str(int(time.time()))
1027
+ nonce = hashlib.md5(now_str.encode("utf-8")).hexdigest()[:16]
1028
+ sig = hashlib.sha256(f"{now_str}_{nonce}_{secret_key}".encode("utf-8")).hexdigest()
1029
+ patch_headers = {
1030
+ "X-Timestamp": now_str,
1031
+ "X-Nonce": nonce,
1032
+ "X-Sign": sig,
1033
+ "X-Signature": sig,
1034
+ }
1035
+ return {
1036
+ "action": "fix_signature_timestamp",
1037
+ "patch_headers": patch_headers,
1038
+ "advice": "目标提示签名或时间戳失效,已启发式计算最新 X-Timestamp/X-Nonce/X-Sign",
1039
+ }
1040
+
1041
+ elif status_code == 401 or "token" in body_lower or "jwt" in body_lower:
1042
+ tokens = [
1043
+ token.strip() for token in (available_tokens or ())
1044
+ if isinstance(token, str) and token.strip()
1045
+ ]
1046
+ if not tokens:
1047
+ return None
1048
+ return {
1049
+ "action": "refresh_auth_token",
1050
+ "patch_headers": {"Authorization": f"Bearer {tokens[0]}"},
1051
+ "advice": "目标鉴权 Token 失效,已调度凭证池刷新 Bearer Token",
1052
+ }
1053
+
1054
+ elif status_code in (415, 400) and any(k in body_lower for k in ("media type", "content-type", "expected application/json", "json")):
1055
+ target_ct = "application/json" if "application/json" in body_lower else "application/x-www-form-urlencoded"
1056
+ return {
1057
+ "action": "switch_content_type",
1058
+ "patch_headers": {"Content-Type": target_ct},
1059
+ "advice": f"目标提示 Payload 格式不兼容,已自动纠偏 Content-Type 为 {target_ct}",
1060
+ }
1061
+
1062
+ return None
1063
+
1064
+ @staticmethod
1065
+ def fix_request_headers(
1066
+ blocked_reason: str,
1067
+ current_headers: Mapping[str, str],
1068
+ *,
1069
+ secret_key: str | None = None,
1070
+ available_tokens: Iterable[str] | None = None,
1071
+ ) -> dict[str, str] | None:
1072
+ """根据遇阻原因启发式修正请求头。返回修正后的字典,若无法自动修正则返回 None。"""
1073
+ headers = dict(current_headers)
1074
+ if blocked_reason == ReflexiveBacktrackingEngine.BLOCKED_403_SIGNATURE:
1075
+ if not secret_key:
1076
+ return None
1077
+ now_str = str(int(time.time()))
1078
+ nonce = hashlib.md5(now_str.encode("utf-8")).hexdigest()[:16]
1079
+ sig = hashlib.sha256(f"{now_str}_{nonce}_{secret_key}".encode("utf-8")).hexdigest()
1080
+ headers["X-Timestamp"] = now_str
1081
+ headers["X-Nonce"] = nonce
1082
+ headers["X-Signature"] = sig
1083
+ return headers
1084
+
1085
+ elif blocked_reason == ReflexiveBacktrackingEngine.BLOCKED_401_TOKEN:
1086
+ tokens = list(available_tokens or [])
1087
+ if tokens:
1088
+ headers["Authorization"] = f"Bearer {tokens[0]}"
1089
+ return headers
1090
+
1091
+ elif blocked_reason == "CONTENT_TYPE_MISMATCH":
1092
+ if "json" in headers.get("Content-Type", "").lower():
1093
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
1094
+ return headers
1095
+
1096
+ return None