bugx-cli 0.0.0-stage → 0.1.0

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 (751) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +280 -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 +50 -0
  13. package/core/agent/__init__.py +146 -0
  14. package/core/agent/agent_artifacts.py +764 -0
  15. package/core/agent/agent_eval.py +1073 -0
  16. package/core/agent/agent_execution.py +552 -0
  17. package/core/agent/agent_orchestrator.py +1345 -0
  18. package/core/agent/agent_targets.py +871 -0
  19. package/core/agent/agent_workspace.py +770 -0
  20. package/core/assets/README.md +24 -0
  21. package/core/assets/bugx-avatar-1024.png +0 -0
  22. package/core/assets/bugx-avatar-512.png +0 -0
  23. package/core/assets/bugx-avatar-tight.svg +23 -0
  24. package/core/assets/bugx-avatar.svg +28 -0
  25. package/core/assets/bugx-hero-cn.png +0 -0
  26. package/core/assets/bugx-hero-en.png +0 -0
  27. package/core/assets/project-layout.md +42 -0
  28. package/core/audit_packs/README.md +37 -0
  29. package/core/audit_packs/data-audit/manifest.json +94 -0
  30. package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  31. package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  32. package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  33. package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  34. package/core/audit_packs/desktop-audit/manifest.json +123 -0
  35. package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  36. package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  37. package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  38. package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  39. package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  40. package/core/audit_packs/memory-testing.md +227 -0
  41. package/core/audit_packs/mobile-audit/manifest.json +155 -0
  42. package/core/audit_packs/mobile-audit/modules/android.md +19 -0
  43. package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  44. package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  45. package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  46. package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  47. package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  48. package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  49. package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  50. package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  51. package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  52. package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  53. package/core/audit_packs/native-audit/manifest.json +127 -0
  54. package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  55. package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  56. package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  57. package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  58. package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  59. package/core/audit_packs/platform-testing.md +174 -0
  60. package/core/audit_packs/web-audit/manifest.json +191 -0
  61. package/core/audit_packs/web-audit/modules/graphql.md +5 -0
  62. package/core/audit_packs/web-audit/modules/h5.md +18 -0
  63. package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  64. package/core/audit_packs/web-audit/modules/oauth.md +4 -0
  65. package/core/audit_packs/web-audit/modules/upload.md +4 -0
  66. package/core/audit_packs/web-audit/modules/websocket.md +4 -0
  67. package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  68. package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  69. package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  70. package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  71. package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  72. package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  73. package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  74. package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  75. package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  76. package/core/autonomous_cve/INTERFACE.md +61 -0
  77. package/core/autonomous_cve/README.md +58 -0
  78. package/core/autonomous_cve/SPEC.md +25 -0
  79. package/core/autonomous_cve/__init__.py +109 -0
  80. package/core/autonomous_cve/attack_graph.py +1096 -0
  81. package/core/autonomous_cve/attack_graph_store.py +1822 -0
  82. package/core/autonomous_cve/audit_campaign.py +1232 -0
  83. package/core/autonomous_cve/behavior_graph.py +459 -0
  84. package/core/autonomous_cve/ghsa_advisories.py +174 -0
  85. package/core/autonomous_cve/models.py +93 -0
  86. package/core/autonomous_cve/mutator.py +87 -0
  87. package/core/autonomous_cve/patcher.py +126 -0
  88. package/core/autonomous_cve/scout.py +278 -0
  89. package/core/autonomous_cve/synthesizer.py +207 -0
  90. package/core/autonomous_cve/verifier.py +100 -0
  91. package/core/bugx.md +1299 -0
  92. package/core/bugx_paths.py +1846 -0
  93. package/core/cloud_sync/INTERFACE.md +32 -0
  94. package/core/cloud_sync/README.md +62 -0
  95. package/core/cloud_sync/SPEC.md +25 -0
  96. package/core/cloud_sync/__init__.py +23 -0
  97. package/core/cloud_sync/auto_sync.py +398 -0
  98. package/core/cloud_sync/cloud_client.py +1199 -0
  99. package/core/cloud_sync/cloud_onboard.py +702 -0
  100. package/core/cloud_sync/cloud_schema.py +648 -0
  101. package/core/cloud_sync/consent.py +81 -0
  102. package/core/cloud_sync/device_identity.py +307 -0
  103. package/core/cloud_sync/endpoint_router.py +415 -0
  104. package/core/cloud_sync/flywheel_client.py +760 -0
  105. package/core/cloud_sync/network_transport.py +275 -0
  106. package/core/cloud_sync/onboard_wizard.py +493 -0
  107. package/core/cloud_sync/sensitive_filter.py +285 -0
  108. package/core/cloud_sync/sync_pull.py +695 -0
  109. package/core/cloud_sync/sync_push.py +721 -0
  110. package/core/contracts/AGENT_GUIDE.md +362 -0
  111. package/core/contracts/README.md +34 -0
  112. package/core/contracts/bugx-blackbox.md +541 -0
  113. package/core/contracts/bugx-opencode.md +469 -0
  114. package/core/contracts/bugx-quick.md +44 -0
  115. package/core/contracts/bugx-runtime-contract.md +353 -0
  116. package/core/contracts/bugx-worker.md +470 -0
  117. package/core/contracts/engine_gap_contracts.py +390 -0
  118. package/core/coverage/README.md +70 -0
  119. package/core/coverage/__init__.py +106 -0
  120. package/core/coverage/coverage_ai_review.py +185 -0
  121. package/core/coverage/coverage_backfill.py +54 -0
  122. package/core/coverage/coverage_bootstrap.py +713 -0
  123. package/core/coverage/coverage_business.py +36 -0
  124. package/core/coverage/coverage_cli.py +715 -0
  125. package/core/coverage/coverage_discovery.py +859 -0
  126. package/core/coverage/coverage_evidence.py +977 -0
  127. package/core/coverage/coverage_forensics.py +115 -0
  128. package/core/coverage/coverage_gate.py +277 -0
  129. package/core/coverage/coverage_intelligence.py +734 -0
  130. package/core/coverage/coverage_manifest.py +396 -0
  131. package/core/coverage/coverage_platform.py +77 -0
  132. package/core/coverage/coverage_validate.py +236 -0
  133. package/core/coverage/module_coverage.py +157 -0
  134. package/core/dev_harness/INTERFACE.md +20 -0
  135. package/core/dev_harness/README.md +21 -0
  136. package/core/dev_harness/SPEC.md +25 -0
  137. package/core/dev_harness/__init__.py +5 -0
  138. package/core/dev_harness/interaction_preset.py +408 -0
  139. package/core/engine-integrity.json +2625 -0
  140. package/core/fuzzing/README.md +49 -0
  141. package/core/fuzzing/__init__.py +82 -0
  142. package/core/fuzzing/concurrency_fuzzer.py +382 -0
  143. package/core/fuzzing/differential_oracle.py +629 -0
  144. package/core/fuzzing/fuzz_input.py +1188 -0
  145. package/core/fuzzing/stateful_fuzzer.py +332 -0
  146. package/core/governance/README.md +61 -0
  147. package/core/governance/__init__.py +130 -0
  148. package/core/governance/capacity_planner.py +124 -0
  149. package/core/governance/dependency_lock.py +317 -0
  150. package/core/governance/goal_governor.py +754 -0
  151. package/core/governance/guide_budget.py +458 -0
  152. package/core/governance/lockdown.sh +50 -0
  153. package/core/governance/readonly_enforcer.py +154 -0
  154. package/core/governance/runtime_tool_gate.py +373 -0
  155. package/core/governance/secret_redactor.py +772 -0
  156. package/core/governance/token_budget.py +38 -0
  157. package/core/host_acp/INTERFACE.md +36 -0
  158. package/core/host_acp/README.md +51 -0
  159. package/core/host_acp/SPEC.md +25 -0
  160. package/core/host_acp/__init__.py +121 -0
  161. package/core/host_acp/base.py +111 -0
  162. package/core/host_acp/claude.py +41 -0
  163. package/core/host_acp/cline.py +235 -0
  164. package/core/host_acp/codex.py +245 -0
  165. package/core/host_acp/dsh.py +48 -0
  166. package/core/host_acp/opencode.py +154 -0
  167. package/core/host_acp/pi.py +36 -0
  168. package/core/host_acp/zcode.py +41 -0
  169. package/core/host_runtime/INTERFACE.md +24 -0
  170. package/core/host_runtime/README.md +62 -0
  171. package/core/host_runtime/SPEC.md +25 -0
  172. package/core/host_runtime/__init__.py +21 -0
  173. package/core/host_runtime/adapters.py +412 -0
  174. package/core/host_runtime/autonomous_runner.py +1152 -0
  175. package/core/host_runtime/cline.py +435 -0
  176. package/core/host_runtime/common.py +103 -0
  177. package/core/host_runtime/free_models.py +786 -0
  178. package/core/host_runtime/host_bootstrap.py +389 -0
  179. package/core/host_runtime/host_evaluators.py +721 -0
  180. package/core/host_runtime/host_probe.py +41 -0
  181. package/core/host_runtime/host_provider_arbitrator.py +777 -0
  182. package/core/host_runtime/host_registry.py +655 -0
  183. package/core/host_runtime/host_usage.py +127 -0
  184. package/core/host_runtime/mcp_process_tracker.py +509 -0
  185. package/core/host_runtime/mcp_registry_gate.py +368 -0
  186. package/core/hosts/INTERFACE.md +51 -0
  187. package/core/hosts/README.md +67 -0
  188. package/core/hosts/SPEC.md +25 -0
  189. package/core/hosts/__init__.py +136 -0
  190. package/core/hosts/_base_usage.py +152 -0
  191. package/core/hosts/_codex_usage.py +297 -0
  192. package/core/hosts/_dsh_usage.py +184 -0
  193. package/core/hosts/_mcp_toml.py +365 -0
  194. package/core/hosts/_zcode_usage.py +269 -0
  195. package/core/hosts/base.py +451 -0
  196. package/core/hosts/claude.py +157 -0
  197. package/core/hosts/cline.py +225 -0
  198. package/core/hosts/codex.py +948 -0
  199. package/core/hosts/dsh.py +518 -0
  200. package/core/hosts/opencode.py +358 -0
  201. package/core/hosts/pi.py +151 -0
  202. package/core/hosts/zcode.py +219 -0
  203. package/core/i18n.py +252 -0
  204. package/core/infra/README.md +39 -0
  205. package/core/infra/__init__.py +15 -0
  206. package/core/infra/build_info.py +86 -0
  207. package/core/infra/client_metadata.py +185 -0
  208. package/core/infra/python_runtime.py +540 -0
  209. package/core/infra/safe_xml.py +221 -0
  210. package/core/launch_bugx.py +118 -0
  211. package/core/launch_phases/INTERFACE.md +31 -0
  212. package/core/launch_phases/README.md +106 -0
  213. package/core/launch_phases/SPEC.md +25 -0
  214. package/core/launch_phases/__init__.py +29 -0
  215. package/core/launch_phases/candidate_revalidation.py +484 -0
  216. package/core/launch_phases/common.py +1041 -0
  217. package/core/launch_phases/finding_confirm_phase.py +387 -0
  218. package/core/launch_phases/finding_settlement.py +1245 -0
  219. package/core/launch_phases/findings_adjudication.py +666 -0
  220. package/core/launch_phases/findings_snapshot.py +357 -0
  221. package/core/launch_phases/judge_phase.py +791 -0
  222. package/core/launch_phases/lesson_context.py +536 -0
  223. package/core/launch_phases/lifecycle_reporter.py +627 -0
  224. package/core/launch_phases/orchestrator_controls.py +682 -0
  225. package/core/launch_phases/post_commit.py +567 -0
  226. package/core/launch_phases/post_coverage_sync.py +591 -0
  227. package/core/launch_phases/post_dry_run.py +817 -0
  228. package/core/launch_phases/post_observability.py +367 -0
  229. package/core/launch_phases/post_phase.py +1087 -0
  230. package/core/launch_phases/post_receipt.py +362 -0
  231. package/core/launch_phases/post_round_lifecycle.py +786 -0
  232. package/core/launch_phases/pre_phase.py +1029 -0
  233. package/core/launch_phases/pre_recon_scout.py +862 -0
  234. package/core/launch_phases/pre_state_builder.py +1286 -0
  235. package/core/launch_phases/report_sharing.py +414 -0
  236. package/core/launch_phases/round_orchestrator.py +1133 -0
  237. package/core/launch_phases/session_runtime.py +1623 -0
  238. package/core/launch_phases/startup_gates.py +1022 -0
  239. package/core/launch_phases/startup_interaction.py +947 -0
  240. package/core/launch_phases/startup_version_gate.py +873 -0
  241. package/core/launch_phases/supervisor_bridge.py +1224 -0
  242. package/core/launch_phases/supervisor_coverage.py +417 -0
  243. package/core/launch_phases/supervisor_degraded.py +1219 -0
  244. package/core/launch_phases/worker_barriers.py +414 -0
  245. package/core/launch_phases/worker_orchestrator.py +1166 -0
  246. package/core/launch_phases/worker_prior.py +749 -0
  247. package/core/ledger/INTERFACE.md +35 -0
  248. package/core/ledger/README.md +160 -0
  249. package/core/ledger/SPEC.md +25 -0
  250. package/core/ledger/__init__.py +67 -0
  251. package/core/ledger/_facade.py +226 -0
  252. package/core/ledger/archive_ops.py +572 -0
  253. package/core/ledger/auto_materialization.py +459 -0
  254. package/core/ledger/bug-log.md +22 -0
  255. package/core/ledger/cli.py +270 -0
  256. package/core/ledger/export_ops.py +549 -0
  257. package/core/ledger/finding_confirmation.py +1274 -0
  258. package/core/ledger/finding_io.py +299 -0
  259. package/core/ledger/finding_lifecycle.py +307 -0
  260. package/core/ledger/finding_verification.py +369 -0
  261. package/core/ledger/incidents.py +999 -0
  262. package/core/ledger/lesson-replay-cases.json +20 -0
  263. package/core/ledger/lesson_ledger.py +241 -0
  264. package/core/ledger/lesson_replay.py +272 -0
  265. package/core/ledger/life_ledger.py +668 -0
  266. package/core/ledger/mistake-book.md +130 -0
  267. package/core/ledger/patterns.py +681 -0
  268. package/core/ledger/receipt_contract.py +253 -0
  269. package/core/ledger/schema.py +1192 -0
  270. package/core/ledger/sync_ops.py +935 -0
  271. package/core/ledger/tool_experience.py +682 -0
  272. package/core/ledger/verify_life.py +1526 -0
  273. package/core/lesson-ledger.json +275 -0
  274. package/core/locales/README.md +19 -0
  275. package/core/locales/en-US.json +462 -0
  276. package/core/locales/zh-CN.json +462 -0
  277. package/core/mcp_handlers/INTERFACE.md +75 -0
  278. package/core/mcp_handlers/README.md +62 -0
  279. package/core/mcp_handlers/SPEC.md +25 -0
  280. package/core/mcp_handlers/__init__.py +128 -0
  281. package/core/mcp_handlers/base.py +697 -0
  282. package/core/mcp_handlers/channel_lifecycle.py +696 -0
  283. package/core/mcp_handlers/graph_handlers.py +222 -0
  284. package/core/mcp_handlers/knowledge_handlers.py +536 -0
  285. package/core/mcp_handlers/mining_handlers.py +586 -0
  286. package/core/mcp_handlers/resource_prompt_table.py +116 -0
  287. package/core/mcp_handlers/retrieval_handlers.py +239 -0
  288. package/core/mcp_handlers/rpc_server.py +465 -0
  289. package/core/mcp_handlers/supervisor_handlers.py +1435 -0
  290. package/core/mcp_handlers/telemetry_handlers.py +227 -0
  291. package/core/mcp_handlers/tool_table.py +1015 -0
  292. package/core/mcp_runtime_support/README.md +21 -0
  293. package/core/mcp_runtime_support/__init__.py +1 -0
  294. package/core/mcp_runtime_support/common.py +363 -0
  295. package/core/mcp_runtime_support/environment.py +605 -0
  296. package/core/mcp_runtime_support/verifier.py +810 -0
  297. package/core/metadata.txt +5 -0
  298. package/core/planning/README.md +157 -0
  299. package/core/planning/__init__.py +242 -0
  300. package/core/planning/capability_plan.py +187 -0
  301. package/core/planning/capability_planner.py +195 -0
  302. package/core/planning/domain_archetype.py +542 -0
  303. package/core/planning/domain_router.py +267 -0
  304. package/core/planning/dynamic_flow_analyzer.py +328 -0
  305. package/core/planning/impact_pruner.py +435 -0
  306. package/core/planning/intent_adjudicator.py +175 -0
  307. package/core/planning/judge_pipeline.py +1163 -0
  308. package/core/planning/logic_analysis.py +419 -0
  309. package/core/planning/prompt_harness.py +1702 -0
  310. package/core/planning/source_inspector.py +267 -0
  311. package/core/planning/spec_harvester.py +449 -0
  312. package/core/planning/target_sandbox_manager.py +573 -0
  313. package/core/planning/test_capability_verifier.py +1364 -0
  314. package/core/planning/tools-kb.md +38 -0
  315. package/core/planning/unit_kind.py +122 -0
  316. package/core/probes/INTERFACE.md +73 -0
  317. package/core/probes/README.md +51 -0
  318. package/core/probes/SPEC.md +26 -0
  319. package/core/probes/__init__.py +70 -0
  320. package/core/probes/android_probe.py +384 -0
  321. package/core/probes/base.py +147 -0
  322. package/core/probes/codebase_memory_probe.py +590 -0
  323. package/core/probes/desktop_probe.py +238 -0
  324. package/core/probes/differential_probe.py +356 -0
  325. package/core/probes/efficiency_probe.py +168 -0
  326. package/core/probes/ios_binary_probe.py +368 -0
  327. package/core/probes/memory_probe.py +326 -0
  328. package/core/probes/miniprogram_probe.py +323 -0
  329. package/core/probes/mobile_probe.py +281 -0
  330. package/core/probes/native_probe.py +214 -0
  331. package/core/probes/openwiki_probe.py +193 -0
  332. package/core/probes/pattern_probe.py +347 -0
  333. package/core/probes/platform_probe.py +343 -0
  334. package/core/probes/probe_registry.py +1669 -0
  335. package/core/probes/sast_probe.py +1009 -0
  336. package/core/probes/sast_rules.py +841 -0
  337. package/core/probes/sca_scanner.py +731 -0
  338. package/core/probes/web_probe.py +359 -0
  339. package/core/project_profiler/INTERFACE.md +62 -0
  340. package/core/project_profiler/README.md +53 -0
  341. package/core/project_profiler/SPEC.md +28 -0
  342. package/core/project_profiler/__init__.py +201 -0
  343. package/core/project_profiler/arbitrator.py +311 -0
  344. package/core/project_profiler/constants.py +247 -0
  345. package/core/project_profiler/detector.py +392 -0
  346. package/core/project_profiler/extractors.py +836 -0
  347. package/core/project_profiler/fingerprint.py +116 -0
  348. package/core/project_profiler/storage.py +258 -0
  349. package/core/project_profiler/strategy.py +265 -0
  350. package/core/prompts/README.md +35 -0
  351. package/core/prompts/codex_dialog_dispatch.md +9 -0
  352. package/core/prompts/command_routing_en.md +42 -0
  353. package/core/prompts/command_routing_zh.md +42 -0
  354. package/core/prompts/l0_router.md +47 -0
  355. package/core/prompts/rules/anti_patterns.md +16 -0
  356. package/core/prompts/rules/concurrency_rules.md +14 -0
  357. package/core/prompts/rules/memory_leak_rules.md +13 -0
  358. package/core/prompts/rules/prompt_injection_defense.md +13 -0
  359. package/core/prompts/stages/stage_explore.md +31 -0
  360. package/core/prompts/stages/stage_gate.md +43 -0
  361. package/core/prompts/stages/stage_mutate.md +42 -0
  362. package/core/prompts/stages/stage_repair.md +85 -0
  363. package/core/repair/README.md +74 -0
  364. package/core/repair/__init__.py +169 -0
  365. package/core/repair/fix_watchlist.py +391 -0
  366. package/core/repair/l7_dynamic.py +418 -0
  367. package/core/repair/l7_repair_loop.py +465 -0
  368. package/core/repair/l7_selfcheck.py +862 -0
  369. package/core/repair/minimize_repro.py +466 -0
  370. package/core/repair/patch_synthesizer.py +617 -0
  371. package/core/repair/regression_pack.py +379 -0
  372. package/core/repair/rsi_fixer.py +910 -0
  373. package/core/repair/rsi_loop.py +313 -0
  374. package/core/repair/rsi_repair.py +348 -0
  375. package/core/repair/rsi_rounds.py +212 -0
  376. package/core/repair/rsi_scope.py +262 -0
  377. package/core/repair/self_heal.py +604 -0
  378. package/core/repair/test_generator.py +1108 -0
  379. package/core/repair/test_quality_auditor.py +410 -0
  380. package/core/repair/test_strategy.py +511 -0
  381. package/core/report_engine/INTERFACE.md +59 -0
  382. package/core/report_engine/README.md +69 -0
  383. package/core/report_engine/SPEC.md +28 -0
  384. package/core/report_engine/__init__.py +47 -0
  385. package/core/report_engine/attestation.py +224 -0
  386. package/core/report_engine/authority.py +255 -0
  387. package/core/report_engine/finding_report.py +417 -0
  388. package/core/report_engine/formal_report_builder.py +924 -0
  389. package/core/report_engine/html_renderers.py +696 -0
  390. package/core/report_engine/models.py +761 -0
  391. package/core/report_engine/pdf_exporter.py +231 -0
  392. package/core/report_engine/projects_assets.py +730 -0
  393. package/core/report_engine/report_client.py +743 -0
  394. package/core/report_engine/report_data_builder.py +388 -0
  395. package/core/report_engine/report_share.py +459 -0
  396. package/core/report_engine/sast_bridge.py +116 -0
  397. package/core/report_engine/server.py +822 -0
  398. package/core/report_engine/visual_report_builder.py +796 -0
  399. package/core/report_engine/web-conformance.md +63 -0
  400. package/core/report_engine/web_conformance.py +459 -0
  401. package/core/report_engine/workbench_assets.py +484 -0
  402. package/core/retrieval/INTERFACE.md +20 -0
  403. package/core/retrieval/README.md +161 -0
  404. package/core/retrieval/SPEC.md +25 -0
  405. package/core/retrieval/__init__.py +3 -0
  406. package/core/retrieval/code_analyzer.py +1684 -0
  407. package/core/retrieval/codebase_memory_bridge.py +337 -0
  408. package/core/retrieval/context_assembler.py +234 -0
  409. package/core/retrieval/corpus_fetch.py +369 -0
  410. package/core/retrieval/graph_ego.py +597 -0
  411. package/core/retrieval/knowledge_auto.py +662 -0
  412. package/core/retrieval/knowledge_sources.py +168 -0
  413. package/core/retrieval/knowledge_sync.py +909 -0
  414. package/core/retrieval/memory_store.py +480 -0
  415. package/core/retrieval/query_planner.py +1020 -0
  416. package/core/retrieval/rrf_engine.py +137 -0
  417. package/core/retrieval/slice_extractor.py +1209 -0
  418. package/core/retrieval/slice_normalizer.py +373 -0
  419. package/core/retrieval/slice_spec.py +357 -0
  420. package/core/retrieval/symbol_index.py +1132 -0
  421. package/core/retrieval/universal_code_matcher.py +437 -0
  422. package/core/retrieval/xerj_bridge.py +476 -0
  423. package/core/retrieval/xerj_supervisor.py +362 -0
  424. package/core/rules/README.md +33 -0
  425. package/core/rules/ios/PROVENANCE.json +30 -0
  426. package/core/rules/ios/crypto.yaml +36 -0
  427. package/core/rules/ios/network.yaml +20 -0
  428. package/core/rules/ios/resilience.yaml +47 -0
  429. package/core/rules/ios/storage.yaml +48 -0
  430. package/core/rules/mastg/LICENSE +173 -0
  431. package/core/rules/mastg/PROVENANCE.json +270 -0
  432. package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  433. package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  434. package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  435. package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  436. package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  437. package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  438. package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  439. package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  440. package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  441. package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  442. package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  443. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  444. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  445. package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  446. package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  447. package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  448. package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  449. package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  450. package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  451. package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  452. package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  453. package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  454. package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  455. package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  456. package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  457. package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  458. package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  459. package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  460. package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  461. package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  462. package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  463. package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  464. package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  465. package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  466. package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  467. package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  468. package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  469. package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  470. package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  471. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  472. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  473. package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  474. package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  475. package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  476. package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  477. package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  478. package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  479. package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  480. package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  481. package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  482. package/core/rules/miniprogram/PROVENANCE.json +26 -0
  483. package/core/rules/miniprogram/network.yaml +37 -0
  484. package/core/rules/miniprogram/platform.yaml +36 -0
  485. package/core/rules/miniprogram/storage.yaml +48 -0
  486. package/core/rules/mobsfscan-swift/LICENSE +165 -0
  487. package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  488. package/core/rules/mobsfscan-swift/auth.yaml +59 -0
  489. package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  490. package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  491. package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  492. package/core/rules/mobsfscan-swift/logging.yaml +23 -0
  493. package/core/rules/mobsfscan-swift/network.yaml +55 -0
  494. package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  495. package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  496. package/core/rules/mobsfscan-swift/storage.yaml +29 -0
  497. package/core/rules/mobsfscan-swift/webview.yaml +32 -0
  498. package/core/runtime/README.md +198 -0
  499. package/core/runtime/__init__.py +3 -0
  500. package/core/runtime/bugx_logging.py +1393 -0
  501. package/core/runtime/daemon_runner.py +623 -0
  502. package/core/runtime/fixture_solidify.py +449 -0
  503. package/core/runtime/global_telemetry.py +549 -0
  504. package/core/runtime/incident_eval.py +148 -0
  505. package/core/runtime/interaction.py +605 -0
  506. package/core/runtime/interaction_store.py +435 -0
  507. package/core/runtime/interactive_menu.py +95 -0
  508. package/core/runtime/log_analytics.py +922 -0
  509. package/core/runtime/mining_quality_framework.py +1387 -0
  510. package/core/runtime/model_runner.py +769 -0
  511. package/core/runtime/platform_adapter.py +579 -0
  512. package/core/runtime/prep_validate.py +476 -0
  513. package/core/runtime/project_graph.py +827 -0
  514. package/core/runtime/project_init.py +481 -0
  515. package/core/runtime/project_profile.py +224 -0
  516. package/core/runtime/project_settings.py +963 -0
  517. package/core/runtime/provider_window.py +97 -0
  518. package/core/runtime/resume_ticket.py +115 -0
  519. package/core/runtime/scenario_eval.py +814 -0
  520. package/core/runtime/seed_drill.py +549 -0
  521. package/core/runtime/self_audit.py +550 -0
  522. package/core/runtime/session_profile.py +205 -0
  523. package/core/runtime/setup_ui_env.py +229 -0
  524. package/core/runtime/startup_environment.py +859 -0
  525. package/core/runtime/sync_store.py +1421 -0
  526. package/core/runtime/tool_install_targets.py +18 -0
  527. package/core/schemas/README.md +35 -0
  528. package/core/schemas/agent-graph.schema.json +368 -0
  529. package/core/schemas/attack-graph.schema.json +88 -0
  530. package/core/schemas/evidence-bundle.schema.json +33 -0
  531. package/core/schemas/skill-pack.schema.json +230 -0
  532. package/core/schemas/worker-checkpoint.schema.json +119 -0
  533. package/core/secure_atomic.py +289 -0
  534. package/core/seed_corpus/README.md +55 -0
  535. package/core/seed_corpus/c.txt +29 -0
  536. package/core/seed_corpus/cpp.txt +32 -0
  537. package/core/seed_corpus/css.txt +70 -0
  538. package/core/seed_corpus/go.txt +46 -0
  539. package/core/seed_corpus/java.txt +30 -0
  540. package/core/seed_corpus/javascript.txt +55 -0
  541. package/core/seed_corpus/kotlin.txt +28 -0
  542. package/core/seed_corpus/python.txt +71 -0
  543. package/core/seed_corpus/rust.txt +53 -0
  544. package/core/seed_corpus/swift.txt +29 -0
  545. package/core/seed_corpus/typescript.txt +29 -0
  546. package/core/skills/README.md +53 -0
  547. package/core/skills/__init__.py +189 -0
  548. package/core/skills/bugx_docs_mcp_server.py +416 -0
  549. package/core/skills/bugx_mcp_server.py +1134 -0
  550. package/core/skills/mcp_runtime.py +968 -0
  551. package/core/skills/mcp_session_proof.py +605 -0
  552. package/core/skills/mobile_ui_inspector.py +405 -0
  553. package/core/skills/skill_pack.py +1214 -0
  554. package/core/skills/skill_synthesizer.py +1153 -0
  555. package/core/skills/tools_kb.py +313 -0
  556. package/core/supervisor/INTERFACE.md +121 -0
  557. package/core/supervisor/README.md +209 -0
  558. package/core/supervisor/SPEC.md +25 -0
  559. package/core/supervisor/__init__.py +175 -0
  560. package/core/supervisor/audit_supervisor.py +1015 -0
  561. package/core/supervisor/budget_governor.py +760 -0
  562. package/core/supervisor/checkpoint_handler.py +368 -0
  563. package/core/supervisor/checkpoint_pipeline.py +1322 -0
  564. package/core/supervisor/checkpoint_sync.py +640 -0
  565. package/core/supervisor/claim_events.py +74 -0
  566. package/core/supervisor/claim_sync.py +590 -0
  567. package/core/supervisor/cli.py +812 -0
  568. package/core/supervisor/context_sync.py +55 -0
  569. package/core/supervisor/coverage_sync.py +115 -0
  570. package/core/supervisor/finding_commit.py +470 -0
  571. package/core/supervisor/finding_sync.py +688 -0
  572. package/core/supervisor/finding_workflow.py +659 -0
  573. package/core/supervisor/finish_policy.py +224 -0
  574. package/core/supervisor/finish_sync.py +185 -0
  575. package/core/supervisor/graph_sync.py +669 -0
  576. package/core/supervisor/lease_manager.py +788 -0
  577. package/core/supervisor/lifecycle_blocks.py +124 -0
  578. package/core/supervisor/next_round_sync.py +126 -0
  579. package/core/supervisor/observability.py +140 -0
  580. package/core/supervisor/recovery_sync.py +165 -0
  581. package/core/supervisor/rejection_remedies.py +308 -0
  582. package/core/supervisor/round_governor.py +306 -0
  583. package/core/supervisor/serial_authorization.py +500 -0
  584. package/core/supervisor/start_sync.py +87 -0
  585. package/core/supervisor/state_store.py +249 -0
  586. package/core/supervisor/supervisor_host.py +511 -0
  587. package/core/supervisor/supervisor_models.py +1143 -0
  588. package/core/supervisor/systemic_failure.py +104 -0
  589. package/core/supervisor/task_scheduler.py +1640 -0
  590. package/core/supervisor/worker_checkpoint.py +223 -0
  591. package/core/supervisor/worker_execution.py +265 -0
  592. package/core/supervisor/worker_handoff.py +192 -0
  593. package/core/supervisor/worker_lifecycle.py +396 -0
  594. package/core/supervisor/worker_runtime.py +999 -0
  595. package/core/supervisor/worker_sync.py +89 -0
  596. package/core/supervisor_types/README.md +36 -0
  597. package/core/supervisor_types/__init__.py +0 -0
  598. package/core/supervisor_types/exceptions.py +52 -0
  599. package/core/supervisor_types/graph_models.py +357 -0
  600. package/core/supervisor_types/path_containment.py +151 -0
  601. package/core/supervisor_types/target_fingerprint.py +310 -0
  602. package/core/supervisor_types/worker_claim.py +402 -0
  603. package/core/webui/INTERFACE.md +50 -0
  604. package/core/webui/README.md +57 -0
  605. package/core/webui/SPEC.md +25 -0
  606. package/core/webui/__init__.py +11 -0
  607. package/core/webui/adapters/__init__.py +27 -0
  608. package/core/webui/adapters/base.py +87 -0
  609. package/core/webui/adapters/bugx.py +102 -0
  610. package/core/webui/adapters/claude.py +218 -0
  611. package/core/webui/adapters/cline.py +399 -0
  612. package/core/webui/adapters/codex.py +256 -0
  613. package/core/webui/adapters/dsh.py +173 -0
  614. package/core/webui/adapters/opencode.py +218 -0
  615. package/core/webui/adapters/pi.py +272 -0
  616. package/core/webui/adapters/registry.py +100 -0
  617. package/core/webui/adapters/zcode.py +312 -0
  618. package/core/webui/api_routes_post.py +668 -0
  619. package/core/webui/dispatcher.py +1376 -0
  620. package/core/webui/docs_session_service.py +473 -0
  621. package/core/webui/handler.py +674 -0
  622. package/core/webui/ide_cloud_service.py +526 -0
  623. package/core/webui/mcp_inspector.py +1743 -0
  624. package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  625. package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  626. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  627. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  628. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  629. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  630. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  631. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  632. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  633. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  634. package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  635. package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  636. package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  637. package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  638. package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  639. package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  640. package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  641. package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  642. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  643. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  644. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  645. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  646. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  647. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  648. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  649. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  650. package/core/webui/static/favicon.png +0 -0
  651. package/core/webui/static/icon-192.png +0 -0
  652. package/core/webui/static/index.html +42 -0
  653. package/core/webui/static/manifest.webmanifest +19 -0
  654. package/core/webui/static/project-settings.css +6458 -0
  655. package/core/webui/static/project-settings.js +9602 -0
  656. package/core/webui/static/sw.js +8 -0
  657. package/core/webui/workspace_service.py +218 -0
  658. package/docs/07_distribution/01_README_NPM.md +281 -0
  659. package/docs/07_distribution/README.md +16 -0
  660. package/docs/README.md +121 -0
  661. package/ecosystem/README.md +129 -0
  662. package/ecosystem/integrations/README.md +38 -0
  663. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
  664. package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
  665. package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
  666. package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
  667. package/ecosystem/integrations/dsh/mcp/index.js +219 -0
  668. package/ecosystem/integrations/dsh/mcp/package.json +28 -0
  669. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
  670. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
  671. package/ecosystem/integrations/dsh/ui/client.js +87 -0
  672. package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
  673. package/ecosystem/integrations/dsh/ui/index.js +7 -0
  674. package/ecosystem/integrations/dsh/ui/package.json +27 -0
  675. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
  676. package/ecosystem/integrations/opencode/mcp-lock.json +3067 -0
  677. package/ecosystem/integrations/opencode/opencode.json +118 -0
  678. package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
  679. package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
  680. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
  681. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
  682. package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
  683. package/ecosystem/integrations/qoder/connector-meta.json +21 -0
  684. package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
  685. package/ecosystem/integrations/workbuddy/icon.png +0 -0
  686. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
  687. package/ecosystem/plugins/README.md +37 -0
  688. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
  689. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
  690. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
  691. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
  692. package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
  693. package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
  694. package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
  695. package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
  696. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
  697. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  698. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
  699. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  700. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  701. package/interfaces/README.md +143 -0
  702. package/interfaces/bin/README.md +35 -0
  703. package/interfaces/bin/bugx.js +80 -0
  704. package/interfaces/cli/README.md +90 -0
  705. package/interfaces/cli/bugx_cli/__init__.py +4 -0
  706. package/interfaces/cli/bugx_cli/cli.py +1678 -0
  707. package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
  708. package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
  709. package/interfaces/cli/bugx_cli/commands/agent.py +3944 -0
  710. package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
  711. package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
  712. package/interfaces/cli/bugx_cli/commands/cloud.py +1370 -0
  713. package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
  714. package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
  715. package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
  716. package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
  717. package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -0
  718. package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
  719. package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
  720. package/interfaces/cli/bugx_cli/commands/plugin.py +2714 -0
  721. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
  722. package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
  723. package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
  724. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +728 -0
  725. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
  726. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
  727. package/interfaces/cli/bugx_cli/commands/project.py +670 -0
  728. package/interfaces/cli/bugx_cli/commands/report.py +260 -0
  729. package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
  730. package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
  731. package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
  732. package/interfaces/cli/bugx_cli/common.py +898 -0
  733. package/interfaces/cli/bugx_cli/host_adapters.py +1917 -0
  734. package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
  735. package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
  736. package/interfaces/cli/bugx_cli/hosts/registry.py +571 -0
  737. package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
  738. package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
  739. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +721 -0
  740. package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
  741. package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
  742. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
  743. package/interfaces/cli/bugx_cli/infra/security.py +332 -0
  744. package/package.json +98 -4
  745. package/pyproject.toml +246 -0
  746. package/scripts/README.md +118 -0
  747. package/scripts/ensure-python.mjs +97 -0
  748. package/scripts/isolate-npm-readme.mjs +40 -0
  749. package/scripts/runtime.lock.json +31 -0
  750. package/scripts/sync-version.mjs +37 -0
  751. package/scripts/test-npm-wrapper.mjs +265 -0
@@ -0,0 +1,1188 @@
1
+ #!/usr/bin/env python3
2
+ """fuzz_input.py — 变异模糊矩阵工具(并发批量轰输入,筛出异常样本)。
3
+
4
+ 用途:取一份合法输入,逐字段/逐字节变异成批量变体,**并发**喂给目标,
5
+ 收集每次 exit code + 输出,筛出异常样本(崩溃/挂起/非零退出)供进一步
6
+ 最小化与根因分析。与 minimize_repro.py 配套:fuzz 负责"广撒网找异常",
7
+ minimize 负责"把异常缩到最小复现"。
8
+
9
+ 用法:
10
+ python3 fuzz_input.py --input <合法输入文件> \
11
+ --cmd '<目标命令,{input} 占位>' \
12
+ --out <输出目录> [--count N] [--jobs P] [--timeout S] [--seed S]
13
+
14
+ # 从多语言种子语料选起点变异(--lang python/java/rust/swift/kotlin/
15
+ # c/cpp/typescript/javascript/css),比随机起点命中率更高:
16
+ python3 fuzz_input.py --lang python \
17
+ --cmd '<目标命令,{input} 占位>' --out /tmp/fuzz-out --count 500 --jobs 8
18
+
19
+ 示例:
20
+ # 对 json 解析器变异 500 个样本,8 并发,异常存到 /tmp/fuzz-out
21
+ python3 fuzz_input.py \
22
+ --input valid.json --cmd 'python3 -m json.tool {input}' \
23
+ --out /tmp/fuzz-out --count 500 --jobs 8
24
+
25
+ 变异策略(each sample applies one random strategy):
26
+ - truncate 截断文件尾部(模拟不完整数据)
27
+ - flip_byte 随机翻转一个字节
28
+ - insert_garbage 在随机位置插入一段垃圾字节
29
+ - mutate_numeric 把数字字段放大/改负/改零(正则)
30
+ - mutate_string 把字符串字段换成超长/CJK/emoji/控制字符
31
+ - duplicate 重复文件中间一段(制造超大/重复结构)
32
+
33
+ 种子语料:seed_corpus/ 目录存放 10 种常用语言的典型语法片段与易错输入,
34
+ `--lang` 从对应文件随机选一行作为变异起点(--input 与 --lang 二选一)。
35
+
36
+ 筛选标准:目标进程 exit code 非 0(崩溃/报错)或超时(挂起)→ 记为异常样本,
37
+ 原始输入与 stderr 一并保存到输出目录。
38
+
39
+ 安全:命令默认按 argv 执行;使用 shell 运算符时必须显式加
40
+ `--allow-shell`,且仅应对完全可信的命令模板使用。
41
+ """
42
+
43
+ from __future__ import annotations
44
+ # --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
45
+ import sys as _sys
46
+ from pathlib import Path as _Path
47
+
48
+ for _p in _Path(__file__).resolve().parents:
49
+ if (_p / "core" / "bugx.md").is_file():
50
+ if str(_p) not in _sys.path:
51
+ _sys.path.insert(0, str(_p))
52
+ break
53
+ del _p
54
+
55
+ import argparse
56
+ import hashlib
57
+ import json
58
+ import os
59
+ import random
60
+ import re
61
+ import shlex
62
+ import subprocess
63
+ import sys
64
+ import tempfile
65
+ import threading
66
+ import time
67
+ from concurrent.futures import ThreadPoolExecutor, as_completed
68
+ from pathlib import Path
69
+ from typing import Any, Mapping
70
+
71
+ _CORE_DIR = Path(__file__).resolve().parents[1]
72
+ _REPO_ROOT = _CORE_DIR.parent
73
+ for _p in (str(_REPO_ROOT), str(_CORE_DIR)):
74
+ if _p not in sys.path:
75
+ sys.path.insert(0, _p)
76
+
77
+ import core.bugx_paths as bugx_paths
78
+
79
+ from core.supervisor.worker_execution import run_bounded
80
+
81
+ SEED_CORPUS = Path(__file__).resolve().parents[1] / "seed_corpus"
82
+
83
+
84
+ def _read_confined_input(root: str | Path, raw_path: str | Path) -> bytes:
85
+ """读取项目内受控文件作为 fuzz 起点。
86
+
87
+ ``input_path`` 来自 Worker,而被审计项目的一切内容都不可信;必须做
88
+ ``resolve() + relative_to(root)`` 与逐级符号链接检查,否则它就是一个
89
+ 任意文件读取入口(读到的内容会被写进临时输入文件并喂给目标命令)。
90
+ """
91
+ return bugx_paths.read_confined_bytes(
92
+ Path(root), raw_path, max_bytes=MAX_INPUT_BYTES, error_cls=ValueError,
93
+ )
94
+
95
+ LANGS = [
96
+ "python", "go", "java", "rust", "swift", "kotlin",
97
+ "c", "cpp", "typescript", "javascript", "css",
98
+ ]
99
+
100
+
101
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
102
+ p = argparse.ArgumentParser(description=__doc__)
103
+ source = p.add_mutually_exclusive_group()
104
+ source.add_argument("--input", help="合法输入文件路径(与 --lang 二选一)")
105
+ source.add_argument("--lang", choices=LANGS,
106
+ help="从种子语料选起点变异(%s)" % ", ".join(LANGS))
107
+ p.add_argument("--cmd", required=True,
108
+ help="目标命令,用 {input} 占位表示输入文件路径")
109
+ p.add_argument("--out", required=True, help="异常样本输出目录")
110
+ p.add_argument("--root", type=Path, default=Path.cwd(),
111
+ help="项目根目录;--target-gaps 中引用的文件必须落在其内(默认当前目录)")
112
+ p.add_argument("--target-gaps", type=Path, default=None,
113
+ help="coverage_intelligence gaps JSON:把未覆盖/欠覆盖文件"
114
+ "自身作为种子优先变异(定向模糊,无插桩环境可用)")
115
+ p.add_argument("--count", type=int, default=100, help="变异样本数(默认 100)")
116
+ p.add_argument("--jobs", type=int, default=4, help="并发数(默认 4)")
117
+ p.add_argument("--timeout", type=float, default=10, help="单次执行超时秒(默认 10)")
118
+ p.add_argument("--seed", type=int, default=None, help="随机种子(可复现)")
119
+ p.add_argument("--allow-shell", action="store_true",
120
+ help="允许通过 shell 执行命令(仅限完全可信的命令模板)")
121
+ p.add_argument("--evolve", type=Path, default=None,
122
+ help="行为引导进化目录:跨轮维护行为哈希库,把触发新行为的"
123
+ "样本回填为下轮种子(dir/behaviors.json + dir/seeds/)")
124
+ p.add_argument("--accepted-exits", default="0",
125
+ help="预期退出码逗号列表(默认 0;如 CLI 参数拒绝可用 0,2)")
126
+ p.add_argument("--feedback-json", action="store_true",
127
+ help="解析 stdout 最后一条 JSON feedback envelope")
128
+ p.add_argument("--latency-baseline", type=float, default=None,
129
+ help="延迟基线秒;只有显式设置后才启用慢响应标记")
130
+ p.add_argument("--latency-factor", type=float, default=3.0,
131
+ help="慢响应阈值倍数(默认 3)")
132
+ p.add_argument("--watch-status", default="500,502,503",
133
+ help="feedback envelope 中需关注的 HTTP 状态码,逗号列表")
134
+ return p.parse_args(argv)
135
+
136
+
137
+ MAX_GAP_SEED_FILES = 50
138
+ MAX_GAP_SEED_BYTES = 256 * 1024
139
+ MAX_INPUT_BYTES = 16 * 1024 * 1024
140
+ MAX_OUTPUT_BYTES = 64 * 1024
141
+ MAX_EVOLUTION_SEED_BYTES = MAX_INPUT_BYTES
142
+ _SHELL_PUNCTUATION = ";&|<>`$()"
143
+ _SHELL_OPERATORS = frozenset({
144
+ ";", "&", "&&", "|", "||", "<", ">", ">>", "<<", "<&", ">&",
145
+ "`", "$(", "(", ")",
146
+ })
147
+
148
+
149
+ class _PayloadLimitError(ValueError):
150
+ """单个 fuzz 样本超过执行边界。"""
151
+
152
+
153
+ def split_argv(template: str) -> list[str]:
154
+ """解析 argv 模板,并拒绝未授权的 shell 语法。
155
+
156
+ 这是全仓命令拆分的唯一实现(QUA-03):``minimize_repro`` 与
157
+ ``differential_probe`` 直接复用本函数,不再各自复制一份。
158
+ """
159
+ lexer = shlex.shlex(template, posix=True, punctuation_chars=_SHELL_PUNCTUATION)
160
+ lexer.whitespace_split = True
161
+ lexer.commenters = ""
162
+ try:
163
+ argv = list(lexer)
164
+ except ValueError as exc:
165
+ raise ValueError(f"命令无法解析: {exc}") from exc
166
+ if not argv:
167
+ raise ValueError("命令不能为空")
168
+ if any(token in _SHELL_OPERATORS for token in argv):
169
+ raise ValueError("命令包含 shell 运算符;如确需使用,请显式传入 --allow-shell")
170
+ return argv
171
+
172
+
173
+ def shell_argv(rendered: str) -> list[str]:
174
+ """把已渲染的命令串交给 shell;Windows 用 COMSPEC,POSIX 用 /bin/sh。"""
175
+ if os.name == "nt": # pragma: no cover - 项目宿主目前为 POSIX
176
+ return [os.environ.get("COMSPEC", "cmd.exe"), "/c", rendered]
177
+ return ["/bin/sh", "-c", rendered]
178
+
179
+
180
+ # 兼容本模块既有的私有调用点;实现只此一份。
181
+ _split_argv = split_argv
182
+ _shell_argv = shell_argv
183
+
184
+
185
+ def _as_bytes(value: object) -> bytes:
186
+ if isinstance(value, bytes):
187
+ return value
188
+ return str(value or "").encode("utf-8", errors="replace")
189
+
190
+
191
+ def load_gap_seeds(gaps_path: Path | None, *, root: Path) -> list[bytes]:
192
+ """从 coverage gaps JSON 提取「欠覆盖文件本身」作为定向种子。
193
+
194
+ 变异对象 = 覆盖缺口文件内容:无插桩环境里最直接的定向模糊形态——
195
+ 变异产物落在同材质输入域,比通用语料更可能踩进未覆盖分支。
196
+
197
+ ``unit["path"]`` 来自被测项目的 coverage 产物(不可信)。提供 ``root``
198
+ 时该路径必须落在项目内且不含符号链接,否则跳过——否则 gaps JSON 可以
199
+ 把任意系统文件变成 fuzz 种子。
200
+ """
201
+ if gaps_path is None:
202
+ return []
203
+ try:
204
+ data = json.loads(gaps_path.read_text(encoding="utf-8"))
205
+ except (OSError, json.JSONDecodeError) as exc:
206
+ print(f"[fuzz_input] ⚠ gaps 文件无法读取(忽略定向): {exc}")
207
+ return []
208
+ units = data.get("units") if isinstance(data, dict) else data
209
+ if not isinstance(units, list):
210
+ print("[fuzz_input] ⚠ gaps JSON 无 units 数组(忽略定向)")
211
+ return []
212
+ seeds: list[bytes] = []
213
+ for unit in units:
214
+ if len(seeds) >= MAX_GAP_SEED_FILES:
215
+ break
216
+ if not isinstance(unit, dict):
217
+ continue
218
+ if unit.get("covered") is True:
219
+ continue
220
+ path = unit.get("path")
221
+ if not isinstance(path, str) or not path:
222
+ continue
223
+ try:
224
+ content = bugx_paths.read_confined_bytes(
225
+ Path(root), path, max_bytes=MAX_GAP_SEED_BYTES, error_cls=ValueError,
226
+ )
227
+ except (ValueError, OSError):
228
+ continue
229
+ if content:
230
+ seeds.append(content)
231
+ return seeds
232
+
233
+
234
+ _RESERVED_WORDS = {
235
+ b"def", b"class", b"return", b"import", b"from", b"with", b"as",
236
+ b"if", b"elif", b"else", b"while", b"for", b"in", b"try", b"except",
237
+ b"finally", b"raise", b"yield", b"async", b"await", b"pass", b"true",
238
+ b"false", b"none", b"self", b"cls",
239
+ }
240
+
241
+
242
+ def extract_gap_tokens(gaps_path: Path | None, *, root: Path) -> list[bytes]:
243
+ """从 coverage gaps JSON 提取未覆盖符号、函数名及目标标识符作为定向变异词库。
244
+
245
+ ``unit["path"]`` 属于被测项目产物(不可信);提供 ``root`` 时只读取项目内
246
+ 的普通文件,且不跟随符号链接。
247
+ """
248
+ if gaps_path is None:
249
+ return []
250
+ try:
251
+ data = json.loads(gaps_path.read_text(encoding="utf-8"))
252
+ except (OSError, json.JSONDecodeError):
253
+ return []
254
+ units = data.get("units") if isinstance(data, dict) else data
255
+ if not isinstance(units, list):
256
+ return []
257
+ tokens: set[bytes] = set()
258
+ ident_pattern = re.compile(rb"[a-zA-Z_][a-zA-Z0-9_]{2,32}")
259
+ for unit in units:
260
+ if not isinstance(unit, dict) or unit.get("covered") is True:
261
+ continue
262
+ # 1. 显式提取 symbols / functions / missing / uncovered_symbols 字段
263
+ for field in ("symbols", "functions", "uncovered_symbols", "missing", "uncovered_branches"):
264
+ vals = unit.get(field)
265
+ if isinstance(vals, list):
266
+ for v in vals:
267
+ if isinstance(v, str) and v.strip():
268
+ tokens.add(v.strip().encode("utf-8"))
269
+ # 2. 提取文件名标识符与文件内未覆盖符号
270
+ path = unit.get("path")
271
+ if isinstance(path, str) and path:
272
+ stem = Path(path).stem
273
+ if len(stem) >= 3:
274
+ tokens.add(stem.encode("utf-8"))
275
+ try:
276
+ content = bugx_paths.read_confined_bytes(
277
+ Path(root), path, max_bytes=MAX_GAP_SEED_BYTES,
278
+ error_cls=ValueError,
279
+ )
280
+ except (ValueError, OSError):
281
+ content = b""
282
+ if content:
283
+ for m in ident_pattern.findall(content):
284
+ lower_m = m.lower()
285
+ if lower_m not in _RESERVED_WORDS:
286
+ tokens.add(m)
287
+ if len(tokens) >= 120:
288
+ break
289
+ if len(tokens) >= 120:
290
+ break
291
+ return sorted(tokens)
292
+
293
+
294
+ def load_seed(lang: str) -> list[bytes]:
295
+ """从语言种子语料加载全部种子(每行一个,空行跳过)。"""
296
+ f = SEED_CORPUS / f"{lang}.txt"
297
+ if not f.is_file():
298
+ print(f"[fuzz_input] 种子语料缺失: {f}")
299
+ return []
300
+ return [
301
+ ln.encode("utf-8")
302
+ for ln in f.read_text(encoding="utf-8").splitlines()
303
+ if ln.strip() and not ln.strip().startswith("#")
304
+ ]
305
+
306
+
307
+ # ---------- 变异策略 ----------
308
+
309
+ def _mutate_truncate(data: bytes, rng: random.Random) -> bytes:
310
+ if len(data) <= 1:
311
+ return b""
312
+ cut = rng.randint(1, len(data) - 1)
313
+ return data[:cut]
314
+
315
+
316
+ def _mutate_flip_byte(data: bytes, rng: random.Random) -> bytes:
317
+ if not data:
318
+ return data
319
+ pos = rng.randrange(len(data))
320
+ val = data[pos] ^ (1 << rng.randrange(8))
321
+ return data[:pos] + bytes([val]) + data[pos + 1:]
322
+
323
+
324
+ def _mutate_insert_garbage(data: bytes, rng: random.Random) -> bytes:
325
+ garbage = bytes(
326
+ rng.choice(b"\x00\xff\x7f\n\r\x01\x1b") for _ in range(rng.randint(1, 16))
327
+ )
328
+ pos = rng.randrange(len(data) + 1)
329
+ return data[:pos] + garbage + data[pos:]
330
+
331
+
332
+ _NUM_RE = re.compile(rb"-?\d+\.?\d*")
333
+
334
+ def _mutate_numeric(data: bytes, rng: random.Random) -> bytes:
335
+ choices = [b"0", b"-1", b"999999999999999999999", b"1e999", b"-0.0"]
336
+ def repl(m: re.Match) -> bytes:
337
+ return rng.choice(choices)
338
+ mutated, matches = _NUM_RE.subn(repl, data, count=rng.randint(1, 3))
339
+ if matches:
340
+ return mutated
341
+ insertion = rng.choice(choices)
342
+ position = rng.randrange(len(data) + 1)
343
+ return data[:position] + insertion + data[position:]
344
+
345
+
346
+ _STR_FILL = [b"a" * 1000, "你好世界".encode(), "🎉🎉🎉".encode(),
347
+ b"\x00\x01\x02", b"%s%s%s%s"]
348
+
349
+ _STRING_RE = re.compile(
350
+ rb'(?P<prefix>[bBrRuUfF]{0,3})(?P<quote>"""|\'\'\'|"|\')'
351
+ rb'(?P<body>(?:\\.|[^\\])*?)(?P=quote)'
352
+ )
353
+
354
+ def _mutate_string(data: bytes, rng: random.Random) -> bytes:
355
+ def repl(match: re.Match) -> bytes:
356
+ body = match.group("body")
357
+ candidates = [fill for fill in _STR_FILL if fill != body]
358
+ replacement = rng.choice(candidates) if candidates else body + b"x"
359
+ return b"".join((
360
+ match.group("prefix"), match.group("quote"), replacement,
361
+ match.group("quote"),
362
+ ))
363
+
364
+ mutated, matches = _STRING_RE.subn(repl, data, count=rng.randint(1, 2))
365
+ if matches:
366
+ return mutated
367
+ marker = rng.choice(_STR_FILL)
368
+ position = rng.randrange(len(data) + 1)
369
+ return data[:position] + b'"' + marker + b'"' + data[position:]
370
+
371
+
372
+ def _mutate_duplicate(data: bytes, rng: random.Random) -> bytes:
373
+ if not data:
374
+ return data
375
+ mid = len(data) // 2
376
+ chunk = data[mid:mid + rng.randint(1, max(1, len(data) // 4))]
377
+ return data + chunk
378
+
379
+
380
+
381
+ # ---------- 语法感知与语义深层变异(Grammar-Aware Structural Mutators) ----------
382
+
383
+ _SECURITY_PAYLOADS = [
384
+ b"../../../etc/passwd",
385
+ b"'; SELECT pg_sleep(1); --",
386
+ b"${IFS}cat${IFS}/etc/passwd",
387
+ b"\x00\xff\xfe\xfd",
388
+ b"A" * 4096,
389
+ b"NaN",
390
+ b"Infinity",
391
+ b"-Infinity",
392
+ ]
393
+
394
+
395
+ def _mutate_boundary_injection(data: bytes, rng: random.Random) -> bytes:
396
+ """在输入任意位置注入经典安全与数值边界载荷。"""
397
+ payload = rng.choice(_SECURITY_PAYLOADS)
398
+ pos = rng.randrange(len(data) + 1)
399
+ return data[:pos] + payload + data[pos:]
400
+
401
+
402
+ def _mutate_json_structural(data: bytes, rng: random.Random) -> bytes:
403
+ """语法树保持型 JSON 结构化突变:穿透语法解析层,直击深层业务逻辑崩溃。"""
404
+ try:
405
+ raw_str = data.decode("utf-8")
406
+ parsed = json.loads(raw_str)
407
+ except Exception:
408
+ return _mutate_flip_byte(data, rng)
409
+
410
+ def _walk_and_mutate(obj: Any, depth: int = 0) -> Any:
411
+ if depth > 4:
412
+ return obj
413
+ if isinstance(obj, dict):
414
+ if not obj:
415
+ return {"_fuzz_injected": "payload"}
416
+ keys = list(obj.keys())
417
+ action = rng.choice(["swap_val", "delete_key", "pollute_key", "nest_bomb", "walk"])
418
+ target_key = rng.choice(keys)
419
+ if action == "swap_val":
420
+ obj[target_key] = rng.choice([None, {}, [], 1e308, -1, "\x00\xff", True, 9223372036854775807])
421
+ elif action == "delete_key" and len(obj) > 1:
422
+ del obj[target_key]
423
+ elif action == "pollute_key":
424
+ obj[rng.choice(["__proto__", "constructor", "prototype", "\x00key"])] = {"polluted": True}
425
+ elif action == "nest_bomb":
426
+ bomb: Any = "deep_recursion_overflow"
427
+ for _ in range(25):
428
+ bomb = {"nested": bomb}
429
+ obj[target_key] = bomb
430
+ else:
431
+ obj[target_key] = _walk_and_mutate(obj[target_key], depth + 1)
432
+ return obj
433
+ elif isinstance(obj, list):
434
+ if not obj:
435
+ return ["injected_item"]
436
+ action = rng.choice(["insert_large", "type_swap", "mutate_item"])
437
+ if action == "insert_large":
438
+ obj.extend([rng.randint(-999999, 999999) for _ in range(20)])
439
+ elif action == "type_swap":
440
+ idx = rng.randrange(len(obj))
441
+ obj[idx] = rng.choice([{}, None, "overflow_string", 0, 1e308])
442
+ elif action == "mutate_item":
443
+ idx = rng.randrange(len(obj))
444
+ obj[idx] = _walk_and_mutate(obj[idx], depth + 1)
445
+ return obj
446
+ elif isinstance(obj, str):
447
+ payloads = [
448
+ "../../../../../../etc/passwd",
449
+ "' OR '1'='1",
450
+ "%s%s%s%s%n",
451
+ "\x00\x01\x02",
452
+ "A" * 1500,
453
+ "\u202e\u202d\ufeff",
454
+ ]
455
+ return rng.choice(payloads)
456
+ elif isinstance(obj, (int, float)):
457
+ return rng.choice([0, -1, 1e308, -1e308, 9223372036854775807, -9223372036854775808])
458
+ elif isinstance(obj, bool):
459
+ return not obj
460
+ return obj
461
+
462
+ import copy
463
+ mutated_obj = _walk_and_mutate(copy.deepcopy(parsed))
464
+ try:
465
+ return json.dumps(mutated_obj, ensure_ascii=False).encode("utf-8")
466
+ except Exception:
467
+ return data
468
+
469
+
470
+ def _mutate_gap_guided(data: bytes, rng: random.Random, tokens: list[bytes]) -> bytes:
471
+ """覆盖导向自适应变异:将未覆盖目标符号定向合成到当前载荷中。"""
472
+ if not tokens:
473
+ return data
474
+ target_token = rng.choice(tokens)
475
+ stripped = data.strip()
476
+ if (stripped.startswith(b"{") and stripped.endswith(b"}")) or (stripped.startswith(b"[") and stripped.endswith(b"]")):
477
+ try:
478
+ parsed = json.loads(data.decode("utf-8"))
479
+ token_str = target_token.decode("utf-8", errors="replace")
480
+ if isinstance(parsed, dict):
481
+ key_choice = rng.choice(["inject_key", "inject_val", "inject_action"])
482
+ if key_choice == "inject_key":
483
+ parsed[token_str] = "gap_targeted_probe"
484
+ elif key_choice == "inject_val" and parsed:
485
+ k = rng.choice(list(parsed.keys()))
486
+ parsed[k] = token_str
487
+ else:
488
+ parsed["action"] = token_str
489
+ return json.dumps(parsed, ensure_ascii=False).encode("utf-8")
490
+ except Exception:
491
+ pass
492
+
493
+ pos = rng.randrange(len(data) + 1)
494
+ sep = b" " if (data and not data.endswith(b" ")) else b""
495
+ return data[:pos] + sep + target_token + sep + data[pos:]
496
+
497
+
498
+ STRATEGIES = [
499
+ ("truncate", _mutate_truncate),
500
+ ("flip_byte", _mutate_flip_byte),
501
+ ("insert_garbage", _mutate_insert_garbage),
502
+ ("mutate_numeric", _mutate_numeric),
503
+ ("mutate_string", _mutate_string),
504
+ ("duplicate", _mutate_duplicate),
505
+ ("boundary_injection", _mutate_boundary_injection),
506
+ ("json_structural", _mutate_json_structural),
507
+ ]
508
+
509
+
510
+ def mutate(
511
+ data: bytes,
512
+ rng: random.Random,
513
+ gap_tokens: list[bytes] | None = None,
514
+ ) -> tuple[str, bytes]:
515
+ """对输入施加自适应变异策略,支持语法树保持与覆盖导向符号注入。"""
516
+ # 覆盖导向增强:若提供未覆盖缺失符号,以 40% 倾向性权重定向注入缺失符号
517
+ if gap_tokens and rng.random() < 0.40:
518
+ mutated = _mutate_gap_guided(data, rng, gap_tokens)
519
+ if mutated != data:
520
+ return "gap_guided", mutated
521
+
522
+ # 自省检测:如果是合法的 JSON 结构化数据,优先以 65% 概率调用语法感知结构变异
523
+ stripped = data.strip()
524
+ if (stripped.startswith(b"{") and stripped.endswith(b"}")) or (stripped.startswith(b"[") and stripped.endswith(b"]")):
525
+ if rng.random() < 0.65:
526
+ mutated = _mutate_json_structural(data, rng)
527
+ if mutated != data:
528
+ return "json_structural", mutated
529
+
530
+ name, fn = rng.choice(STRATEGIES)
531
+ mutated = fn(data, rng)
532
+ if mutated != data:
533
+ return name, mutated
534
+ return name, _mutate_flip_byte(data, rng) if data else b"\x00"
535
+
536
+
537
+ def _seed_for_index(seeds: list[bytes], index: int) -> bytes:
538
+ if not seeds:
539
+ raise ValueError("seeds 不能为空")
540
+ return seeds[index % len(seeds)]
541
+
542
+
543
+ def _crash_signature(kind: str, exit_code: object, stderr: bytes = b"") -> str:
544
+ text = stderr.decode("utf-8", errors="replace") if isinstance(stderr, bytes) else str(stderr)
545
+ text = re.sub(r"0x[0-9a-fA-F]+", "0xADDR", text)
546
+ text = re.sub(r"\b\d+\b", "N", text)
547
+ text = "\n".join(line.strip() for line in text.splitlines() if line.strip())[:500]
548
+ value = "\0".join((kind, str(exit_code), text))
549
+ return hashlib.sha256(value.encode("utf-8", errors="replace")).hexdigest()[:16]
550
+
551
+
552
+ def _group_crashes(crashes: list[dict]) -> list[dict]:
553
+ grouped: dict[str, dict] = {}
554
+ for crash in sorted(crashes, key=lambda item: item["idx"]):
555
+ signature = crash["crash_signature"]
556
+ current = grouped.get(signature)
557
+ if current is None:
558
+ current = dict(crash)
559
+ current["occurrences"] = 0
560
+ current["sample_indices"] = []
561
+ current["payload_hashes"] = []
562
+ grouped[signature] = current
563
+ current["occurrences"] += 1
564
+ current["sample_indices"].append(crash["idx"])
565
+ payload_hash = crash.get("payload_sha256")
566
+ if payload_hash and payload_hash not in current["payload_hashes"]:
567
+ current["payload_hashes"].append(payload_hash)
568
+ return list(grouped.values())
569
+
570
+
571
+ # ---------- 执行与筛选 ----------
572
+
573
+ def _parse_code_set(value: str, name: str) -> frozenset[int]:
574
+ try:
575
+ values = frozenset(int(item.strip()) for item in value.split(",") if item.strip())
576
+ except (TypeError, ValueError) as exc:
577
+ raise ValueError(f"{name} 必须是逗号分隔的整数") from exc
578
+ if not values:
579
+ raise ValueError(f"{name} 不能为空")
580
+ return values
581
+
582
+
583
+ _FEEDBACK_KEYS = frozenset({"status_code", "state", "error_signature", "feedback"})
584
+ _FEEDBACK_SECRET = re.compile(
585
+ r"(?:bearer\s+\S+|(?:token|secret|password|passwd|api[_-]?key)\s*[:=]\s*\S+)",
586
+ re.I,
587
+ )
588
+
589
+
590
+ def _feedback_value(value: object) -> str | int | float | bool | None:
591
+ if isinstance(value, bool):
592
+ return value
593
+ if isinstance(value, int) and not isinstance(value, bool):
594
+ return value
595
+ if isinstance(value, float) and value == value and abs(value) != float("inf"):
596
+ return value
597
+ if isinstance(value, str):
598
+ value = _FEEDBACK_SECRET.sub("[REDACTED]", value.strip())[:128]
599
+ return value or None
600
+ return None
601
+
602
+
603
+ def _extract_feedback(stdout: bytes, stderr: bytes, enabled: bool) -> dict:
604
+ """读取显式 envelope;非 JSON 或未知字段都按无反馈处理。"""
605
+ if not enabled:
606
+ return {}
607
+ for stream in (stdout, stderr):
608
+ lines = stream.decode("utf-8", errors="replace").splitlines()
609
+ for line in reversed(lines):
610
+ try:
611
+ decoded = json.loads(line)
612
+ except json.JSONDecodeError:
613
+ continue
614
+ if not isinstance(decoded, dict):
615
+ continue
616
+ candidate = decoded.get("feedback") if isinstance(decoded.get("feedback"), dict) else decoded
617
+ vector: dict[str, object] = {}
618
+ for key in _FEEDBACK_KEYS - {"feedback"}:
619
+ if key not in candidate:
620
+ continue
621
+ safe = _feedback_value(candidate[key])
622
+ if safe is not None:
623
+ vector[key] = safe
624
+ nested = candidate.get("feedback") if isinstance(candidate, dict) else None
625
+ if isinstance(nested, dict):
626
+ safe_nested = {
627
+ str(key)[:64]: safe
628
+ for key, value in list(nested.items())[:8]
629
+ if (safe := _feedback_value(value)) is not None
630
+ }
631
+ if safe_nested:
632
+ vector["feedback"] = safe_nested
633
+ return vector
634
+ return {}
635
+
636
+
637
+ def _feedback_vector(feedback: dict, duration_ms: float,
638
+ latency_baseline: float | None, latency_factor: float,
639
+ watch_status: frozenset[int]) -> dict:
640
+ vector = dict(feedback)
641
+ status = vector.get("status_code")
642
+ if isinstance(status, str) and status.isdigit():
643
+ status = int(status)
644
+ vector["status_code"] = status
645
+ slow = (
646
+ latency_baseline is not None
647
+ and latency_baseline > 0
648
+ and latency_factor > 0
649
+ and duration_ms / 1000.0 >= latency_baseline * latency_factor
650
+ )
651
+ vector["latency_class"] = "slow" if slow else "normal"
652
+ vector["watched_status"] = isinstance(status, int) and status in watch_status
653
+ return vector
654
+
655
+
656
+ def _behavior_hash(exit_code: object, stdout: bytes = b"", stderr: bytes = b"",
657
+ feedback: Mapping[str, object] | None = None) -> str:
658
+ """行为指纹:退出码、双流与显式反馈向量的 SHA-256。"""
659
+ digest = hashlib.sha256()
660
+ digest.update(str(exit_code).encode())
661
+ digest.update(b"\0")
662
+ digest.update(stdout[:4096])
663
+ digest.update(b"\0")
664
+ digest.update(stderr[:4096])
665
+ digest.update(b"\0")
666
+ digest.update(json.dumps(feedback or {}, ensure_ascii=False, sort_keys=True,
667
+ separators=(",", ":")).encode("utf-8"))
668
+ return digest.hexdigest()
669
+
670
+
671
+ def _load_evolution(evolve: Path | None) -> tuple[set[str], list[bytes]]:
672
+ """读取既有行为哈希库与进化种子;目录不存在则初始化空库。"""
673
+ behaviors: set[str] = set()
674
+ seeds: list[bytes] = []
675
+ if evolve is None:
676
+ return behaviors, seeds
677
+ index = evolve / "behaviors.json"
678
+ if index.is_file():
679
+ try:
680
+ data = json.loads(index.read_text(encoding="utf-8"))
681
+ behaviors = {
682
+ str(item) for item in (data or {}).get("behaviors", [])
683
+ if isinstance(item, str)
684
+ }
685
+ except (OSError, json.JSONDecodeError):
686
+ print(f"[fuzz_input] ⚠ 行为库损坏,按空库重启: {index}")
687
+ seeds_dir = evolve / "seeds"
688
+ if seeds_dir.is_dir():
689
+ for path in sorted(seeds_dir.glob("*.bin")):
690
+ if path.is_symlink():
691
+ continue
692
+ try:
693
+ if path.stat().st_size > MAX_EVOLUTION_SEED_BYTES:
694
+ continue
695
+ seeds.append(path.read_bytes())
696
+ except OSError:
697
+ continue
698
+ return behaviors, seeds
699
+
700
+
701
+ def _save_evolution(evolve: Path, behaviors: set[str],
702
+ new_records: list[dict], max_seeds: int = 200) -> int:
703
+ """把新行为样本写回进化目录(种子 + 行为库),返回新增种子数。"""
704
+ bugx_paths.ensure_dir(evolve)
705
+ seeds_dir = bugx_paths.ensure_dir(evolve / "seeds")
706
+ written = 0
707
+ for record in new_records:
708
+ payload = record.get("payload")
709
+ if not isinstance(payload, bytes) or len(payload) > MAX_EVOLUTION_SEED_BYTES:
710
+ continue
711
+ name = f"seed-{record['idx']:08d}-{record['behavior_sha256'][:12]}.bin"
712
+ target = seeds_dir / name
713
+ if target.is_symlink():
714
+ continue
715
+ target.write_bytes(payload)
716
+ written += 1
717
+ existing_seeds = sorted(seeds_dir.glob("*.bin"))
718
+ if len(existing_seeds) > max_seeds:
719
+ for stale in existing_seeds[:len(existing_seeds) - max_seeds]:
720
+ try:
721
+ stale.unlink()
722
+ except OSError:
723
+ pass
724
+ index_path = evolve / "behaviors.json"
725
+ if index_path.is_symlink():
726
+ raise ValueError(f"拒绝写入符号链接行为库: {index_path}")
727
+ content = json.dumps({
728
+ "schema_version": 1,
729
+ "behaviors": sorted(behaviors),
730
+ "seeds": min(len(existing_seeds), max_seeds),
731
+ }, ensure_ascii=False, indent=2) + "\n"
732
+ temporary = index_path.with_name(f".{index_path.name}.tmp")
733
+ temporary.write_text(content, encoding="utf-8")
734
+ temporary.replace(index_path)
735
+ return written
736
+
737
+
738
+ def _run_target(cmd: str, payload: bytes, tmp: Path,
739
+ timeout: float, allow_shell: bool = False) -> subprocess.CompletedProcess:
740
+ if len(payload) > MAX_INPUT_BYTES:
741
+ raise _PayloadLimitError(
742
+ f"输入样本超过 {MAX_INPUT_BYTES} 字节上限: {len(payload)}"
743
+ )
744
+ if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0:
745
+ raise ValueError("timeout 必须是正数")
746
+ if not tmp.is_dir():
747
+ raise ValueError(f"执行工作目录不是目录: {tmp}")
748
+ inp = tmp / "input"
749
+ if inp.is_symlink():
750
+ inp.unlink()
751
+ inp.write_bytes(payload)
752
+ if allow_shell:
753
+ rendered = cmd.replace("{input}", shlex.quote(str(inp)))
754
+ argv = _shell_argv(rendered)
755
+ else:
756
+ argv = [token.replace("{input}", str(inp)) for token in _split_argv(cmd)]
757
+ return run_bounded(
758
+ argv,
759
+ cwd=tmp,
760
+ timeout=timeout,
761
+ max_output_bytes=MAX_OUTPUT_BYTES,
762
+ )
763
+
764
+
765
+ def fuzz_once(cmd: str, data: bytes, rng: random.Random, tmp: Path,
766
+ timeout: float, idx: int, allow_shell: bool = False,
767
+ seen_payloads: set[str] | None = None,
768
+ seen_lock: threading.Lock | None = None,
769
+ track_behavior: bool = False,
770
+ seen_behaviors: set[str] | None = None,
771
+ accepted_exits: frozenset[int] | None = None,
772
+ feedback_json: bool = False,
773
+ latency_baseline: float | None = None,
774
+ latency_factor: float = 3.0,
775
+ watch_status: frozenset[int] | None = None,
776
+ gap_tokens: list[bytes] | None = None) -> dict | None:
777
+ """跑一个变异样本;异常或新的反馈行为返回记录,正常返回 None。
778
+
779
+ ``track_behavior`` 开启后,正常退出但行为指纹未见过的样本也返回
780
+ ``kind="new-behavior"`` 记录——它们会被回填为下一轮种子,实现
781
+ 行为多样性引导(无插桩环境下的最小覆盖引导形态)。
782
+ """
783
+ name, payload = mutate(data, rng, gap_tokens=gap_tokens)
784
+ accepted_exits = accepted_exits or frozenset({0})
785
+ watch_status = watch_status or frozenset()
786
+ payload_hash = hashlib.sha256(payload).hexdigest()
787
+ if seen_payloads is not None:
788
+ if seen_lock is None:
789
+ duplicate = payload_hash in seen_payloads
790
+ seen_payloads.add(payload_hash)
791
+ else:
792
+ with seen_lock:
793
+ duplicate = payload_hash in seen_payloads
794
+ seen_payloads.add(payload_hash)
795
+ if duplicate:
796
+ return {
797
+ "idx": idx, "strategy": name, "kind": "duplicate",
798
+ "len": len(payload), "payload_sha256": payload_hash,
799
+ }
800
+ case_tmp = tmp / f"case-{idx:08d}"
801
+ case_tmp.mkdir(parents=True, exist_ok=True)
802
+ try:
803
+ r = _run_target(cmd, payload, case_tmp, timeout, allow_shell)
804
+ except _PayloadLimitError as exc:
805
+ behavior = _behavior_hash("INPUT_LIMIT")
806
+ return {
807
+ "idx": idx, "strategy": name, "kind": "input-limit",
808
+ "exit": "INPUT_LIMIT", "len": len(payload), "payload": payload,
809
+ "payload_sha256": payload_hash,
810
+ "crash_signature": _crash_signature("input-limit", "INPUT_LIMIT"),
811
+ "behavior_sha256": behavior, "error": str(exc),
812
+ }
813
+ except OSError as exc:
814
+ behavior = _behavior_hash("EXECUTION_ERROR")
815
+ return {
816
+ "idx": idx, "strategy": name, "kind": "execution-error",
817
+ "exit": "EXECUTION_ERROR", "len": len(payload), "payload": payload,
818
+ "payload_sha256": payload_hash,
819
+ "crash_signature": _crash_signature("execution-error", "EXECUTION_ERROR"),
820
+ "behavior_sha256": behavior, "error": str(exc),
821
+ }
822
+ if getattr(r, "timed_out", False):
823
+ behavior = _behavior_hash("TIMEOUT")
824
+ return {
825
+ "idx": idx, "strategy": name, "kind": "timeout",
826
+ "exit": "TIMEOUT", "len": len(payload), "payload": payload,
827
+ "payload_sha256": payload_hash,
828
+ "crash_signature": _crash_signature("timeout", "TIMEOUT"),
829
+ "behavior_sha256": behavior,
830
+ }
831
+ stdout = _as_bytes(r.stdout)
832
+ stderr = _as_bytes(r.stderr)
833
+ duration_ms = round(float(getattr(r, "duration_seconds", 0.0) or 0.0) * 1000, 2)
834
+ feedback = _extract_feedback(stdout, stderr, feedback_json)
835
+ vector = _feedback_vector(
836
+ feedback, duration_ms, latency_baseline, latency_factor, watch_status,
837
+ )
838
+ if getattr(r, "output_exceeded", False):
839
+ behavior = _behavior_hash("OUTPUT_LIMIT", stdout, stderr, vector)
840
+ return {
841
+ "idx": idx, "strategy": name, "kind": "output-limit",
842
+ "exit": "OUTPUT_LIMIT", "len": len(payload), "payload": payload,
843
+ "stderr": stderr[:2000], "payload_sha256": payload_hash,
844
+ "crash_signature": _crash_signature("output-limit", "OUTPUT_LIMIT", stderr),
845
+ "behavior_sha256": behavior, "output_limit": MAX_OUTPUT_BYTES,
846
+ "duration_ms": duration_ms, "feedback": vector,
847
+ }
848
+ behavior = _behavior_hash(r.returncode, stdout, stderr, vector)
849
+ if r.returncode not in accepted_exits:
850
+ return {
851
+ "idx": idx, "strategy": name, "kind": "crash",
852
+ "exit": r.returncode, "len": len(payload), "payload": payload,
853
+ "stderr": stderr[:2000],
854
+ "payload_sha256": payload_hash,
855
+ "crash_signature": _crash_signature("crash", r.returncode, stderr),
856
+ "behavior_sha256": behavior, "duration_ms": duration_ms,
857
+ "feedback": vector,
858
+ }
859
+ if vector.get("watched_status") or vector.get("latency_class") == "slow":
860
+ kind = "feedback-anomaly" if vector.get("watched_status") else "latency-anomaly"
861
+ return {
862
+ "idx": idx, "strategy": name, "kind": kind,
863
+ "exit": r.returncode, "len": len(payload), "payload": payload,
864
+ "stderr": stderr[:2000], "payload_sha256": payload_hash,
865
+ "crash_signature": _crash_signature(kind, vector, stderr),
866
+ "behavior_sha256": behavior, "duration_ms": duration_ms,
867
+ "feedback": vector,
868
+ }
869
+ if track_behavior and seen_behaviors is not None:
870
+ if seen_lock is None:
871
+ known = behavior in seen_behaviors
872
+ seen_behaviors.add(behavior)
873
+ else:
874
+ with seen_lock:
875
+ known = behavior in seen_behaviors
876
+ seen_behaviors.add(behavior)
877
+ if not known:
878
+ return {
879
+ "idx": idx, "strategy": name, "kind": "new-behavior",
880
+ "exit": 0, "len": len(payload), "payload": payload,
881
+ "payload_sha256": payload_hash,
882
+ "behavior_sha256": behavior,
883
+ "duration_ms": duration_ms, "feedback": vector,
884
+ }
885
+ return None
886
+
887
+
888
+ def fuzz_target(
889
+ cmd: str,
890
+ *,
891
+ input_content: str | bytes | None = None,
892
+ input_path: str | Path | None = None,
893
+ root: str | Path | None = None,
894
+ lang: str | None = None,
895
+ count: int = 50,
896
+ jobs: int = 4,
897
+ timeout: float = 5.0,
898
+ allow_shell: bool = False,
899
+ out_dir: str | Path | None = None,
900
+ target_gaps: str | Path | None = None,
901
+ accepted_exits: set[int] | None = None,
902
+ seed: int | None = None,
903
+ ) -> dict[str, Any]:
904
+ """供 Python 模块或 MCP 工具调用的输入变异模糊测试执行引擎。
905
+
906
+ ``input_content`` 是**纯内容**:即使它的字面量恰好等于某个已存在文件的
907
+ 路径,也不会被当作文件读取。需要「从项目内文件取种子」时显式使用
908
+ ``input_path``(必须落在 ``root`` 内且不含符号链接)。把两者合并成
909
+ 「恰好是文件就当路径」的嗅探,曾让 ``input_content`` 变成任意文件读取入口。
910
+ """
911
+ if count < 1 or jobs < 1 or timeout <= 0:
912
+ raise ValueError("count、jobs 必须 >= 1,timeout 必须 > 0")
913
+ if not allow_shell:
914
+ _split_argv(cmd)
915
+
916
+ actual_seed = seed if seed is not None else random.SystemRandom().randrange(2**63)
917
+ seed_inputs: list[bytes] | None = None
918
+ gap_path = Path(target_gaps) if target_gaps else None
919
+ gap_root = Path(root) if root is not None else None
920
+ gap_seeds = load_gap_seeds(gap_path, root=gap_root)
921
+ gap_tokens = extract_gap_tokens(gap_path, root=gap_root)
922
+
923
+ if input_content is not None and input_path is not None:
924
+ raise ValueError("input_content 与 input_path 不能同时提供")
925
+ if input_path is not None:
926
+ if root is None:
927
+ raise ValueError("使用 input_path 时必须提供 root 以校验项目边界")
928
+ data = _read_confined_input(root, input_path)
929
+ elif input_content is not None:
930
+ if isinstance(input_content, bytes):
931
+ data = input_content
932
+ else:
933
+ data = str(input_content).encode("utf-8")
934
+ elif gap_seeds:
935
+ seed_inputs = gap_seeds
936
+ data = seed_inputs[0]
937
+ elif lang:
938
+ seed_inputs = load_seed(lang)
939
+ if not seed_inputs:
940
+ raise ValueError(f"指定语言种子缺失: {lang}")
941
+ data = seed_inputs[0]
942
+ else:
943
+ data = b'{"test": 1, "value": "demo"}'
944
+
945
+ temp_out_dir = None
946
+ if out_dir:
947
+ out = Path(out_dir).expanduser().resolve()
948
+ bugx_paths.ensure_dir(out)
949
+ else:
950
+ temp_out_dir = tempfile.TemporaryDirectory(prefix="bugx-fuzz-")
951
+ out = Path(temp_out_dir.name)
952
+
953
+ crashes_dir = bugx_paths.ensure_dir(out / "crashes")
954
+
955
+ crashes: list[dict] = []
956
+ duplicates_skipped = 0
957
+ seen_payloads: set[str] = set()
958
+ seen_lock = threading.Lock()
959
+ accepted = accepted_exits or {0}
960
+
961
+ with tempfile.TemporaryDirectory(prefix="fuzz-tmp-") as td:
962
+ tmp = Path(td)
963
+
964
+ def _seed_pool(index: int) -> bytes:
965
+ base = [data] if seed_inputs is None else seed_inputs
966
+ pool = gap_seeds + base
967
+ return pool[index % len(pool)]
968
+
969
+ with ThreadPoolExecutor(max_workers=jobs) as pool:
970
+ futs = {
971
+ pool.submit(
972
+ fuzz_once, cmd,
973
+ _seed_pool(i),
974
+ random.Random(actual_seed + i), tmp,
975
+ timeout, i, allow_shell,
976
+ seen_payloads, seen_lock,
977
+ False, None, accepted, None,
978
+ None, 3.0, None, gap_tokens,
979
+ ): i
980
+ for i in range(count)
981
+ }
982
+ for fut in as_completed(futs):
983
+ try:
984
+ res = fut.result()
985
+ except Exception:
986
+ continue
987
+ if res is not None and res.get("kind") == "duplicate":
988
+ duplicates_skipped += 1
989
+ elif res is not None and res.get("kind") != "new-behavior":
990
+ crashes.append(res)
991
+
992
+ unique_crashes = _group_crashes(crashes)
993
+ records = []
994
+ for c in unique_crashes:
995
+ rec = {k: v for k, v in c.items() if k != "payload"}
996
+ if isinstance(rec.get("stderr"), bytes):
997
+ rec["stderr"] = rec["stderr"].decode("utf-8", errors="replace")
998
+ records.append(rec)
999
+
1000
+ return {
1001
+ "status": "ok",
1002
+ "total": count,
1003
+ "executed": count - duplicates_skipped,
1004
+ "duplicates_skipped": duplicates_skipped,
1005
+ "anomalies": len(crashes),
1006
+ "unique_anomalies": len(unique_crashes),
1007
+ "crashes": records[:10],
1008
+ "crash_signatures": sorted(list({c.get("crash_signature", "") for c in unique_crashes if c.get("crash_signature")})),
1009
+ "out_dir": str(out),
1010
+ }
1011
+
1012
+
1013
+ def main(argv: list[str] | None = None) -> int:
1014
+ args = parse_args(argv)
1015
+ if args.count < 1 or args.jobs < 1 or args.timeout <= 0:
1016
+ print("[fuzz_input] --count、--jobs 必须 >= 1,--timeout 必须 > 0")
1017
+ return 2
1018
+ if args.latency_baseline is not None and args.latency_baseline <= 0:
1019
+ print("[fuzz_input] --latency-baseline 必须 > 0")
1020
+ return 2
1021
+ if args.latency_factor <= 0:
1022
+ print("[fuzz_input] --latency-factor 必须 > 0")
1023
+ return 2
1024
+ try:
1025
+ accepted_exits = _parse_code_set(args.accepted_exits, "--accepted-exits")
1026
+ watch_status = _parse_code_set(args.watch_status, "--watch-status")
1027
+ except ValueError as exc:
1028
+ print(f"[fuzz_input] {exc}")
1029
+ return 2
1030
+ if not args.allow_shell:
1031
+ try:
1032
+ _split_argv(args.cmd)
1033
+ except ValueError as exc:
1034
+ print(f"[fuzz_input] 命令无效: {exc}")
1035
+ return 2
1036
+ seed = args.seed if args.seed is not None else random.SystemRandom().randrange(2**63)
1037
+ seed_inputs: list[bytes] | None = None
1038
+ gap_seeds = load_gap_seeds(args.target_gaps, root=args.root)
1039
+ gap_tokens = extract_gap_tokens(args.target_gaps, root=args.root)
1040
+ if gap_seeds:
1041
+ print(f"[fuzz_input] 定向模式:{len(gap_seeds)} 个欠覆盖文件作为优先种子")
1042
+ if gap_tokens:
1043
+ print(f"[fuzz_input] 覆盖导向:提取到 {len(gap_tokens)} 个缺失符号引导变异")
1044
+ if args.input:
1045
+ src = Path(args.input)
1046
+ if not src.is_file():
1047
+ print(f"[fuzz_input] 输入文件不存在: {src}")
1048
+ return 2
1049
+ data = src.read_bytes()
1050
+ source_name = src.name
1051
+ elif gap_seeds:
1052
+ seed_inputs = gap_seeds
1053
+ data = seed_inputs[0]
1054
+ source_name = f"gap-seeds({len(gap_seeds)} 个欠覆盖文件)"
1055
+ elif args.lang:
1056
+ seed_inputs = load_seed(args.lang)
1057
+ if not seed_inputs:
1058
+ return 2
1059
+ data = seed_inputs[0]
1060
+ source_name = f"seed:{args.lang}({len(seed_inputs)} 条,按样本轮询)"
1061
+ else:
1062
+ print("[fuzz_input] 必须提供 --input / --lang / --target-gaps 之一作为种子来源")
1063
+ return 2
1064
+ out = Path(args.out).expanduser()
1065
+ if out.is_symlink():
1066
+ print(f"[fuzz_input] 拒绝写入符号链接输出目录: {out}")
1067
+ return 2
1068
+ out = out.resolve()
1069
+ bugx_paths.ensure_dir(out)
1070
+ crashes_dir = bugx_paths.ensure_dir(out / "crashes")
1071
+
1072
+ evolve_arg = args.evolve.expanduser() if args.evolve else None
1073
+ if evolve_arg and evolve_arg.is_symlink():
1074
+ print(f"[fuzz_input] 拒绝使用符号链接进化目录: {evolve_arg}")
1075
+ return 2
1076
+ evolve = evolve_arg.resolve() if evolve_arg else None
1077
+ seen_behaviors, evolve_seeds = _load_evolution(evolve)
1078
+ if evolve and evolve_seeds:
1079
+ print(f"[fuzz_input] 进化种子库: {len(evolve_seeds)} 条 "
1080
+ f"(已知行为 {len(seen_behaviors)} 个)")
1081
+
1082
+ print(f"[fuzz_input] 目标: {source_name} ({len(data)} 字节) "
1083
+ f"样本={args.count} 并发={args.jobs} 种子={seed}")
1084
+ crashes: list[dict] = []
1085
+ new_behaviors: list[dict] = []
1086
+ duplicates_skipped = 0
1087
+ seen_payloads: set[str] = set()
1088
+ seen_lock = threading.Lock()
1089
+ with tempfile.TemporaryDirectory(prefix="fuzz-") as td:
1090
+ tmp = Path(td)
1091
+
1092
+ def _seed_pool(index: int) -> bytes:
1093
+ base = [data] if seed_inputs is None else seed_inputs
1094
+ pool = gap_seeds + base + evolve_seeds
1095
+ return pool[index % len(pool)]
1096
+
1097
+ with ThreadPoolExecutor(max_workers=args.jobs) as pool:
1098
+ futs = {
1099
+ pool.submit(fuzz_once, args.cmd,
1100
+ _seed_pool(i),
1101
+ random.Random(seed + i), tmp,
1102
+ args.timeout, i, args.allow_shell,
1103
+ seen_payloads, seen_lock,
1104
+ bool(evolve),
1105
+ seen_behaviors if evolve else None,
1106
+ accepted_exits, args.feedback_json,
1107
+ args.latency_baseline, args.latency_factor,
1108
+ watch_status, gap_tokens): i
1109
+ for i in range(args.count)
1110
+ }
1111
+ for fut in as_completed(futs):
1112
+ try:
1113
+ res = fut.result()
1114
+ except Exception as e: # noqa: BLE001
1115
+ print(f" ! 任务异常: {e}")
1116
+ continue
1117
+ if res is not None and res.get("kind") == "duplicate":
1118
+ duplicates_skipped += 1
1119
+ elif res is not None and res.get("kind") == "new-behavior":
1120
+ new_behaviors.append(res)
1121
+ elif res is not None:
1122
+ crashes.append(res)
1123
+
1124
+ # 写异常样本
1125
+ meta = out / "summary.json"
1126
+ unique_crashes = _group_crashes(crashes)
1127
+ records = []
1128
+ for c in unique_crashes:
1129
+ fn = crashes_dir / (
1130
+ f"crash-{c['idx']:04d}-{c['strategy']}-exit{c['exit']}"
1131
+ f"-{c['crash_signature']}"
1132
+ )
1133
+ fn.write_bytes(c["payload"])
1134
+ rec = {k: v for k, v in c.items() if k != "payload"}
1135
+ if isinstance(rec.get("stderr"), bytes):
1136
+ rec["stderr"] = rec["stderr"].decode("utf-8", errors="replace")
1137
+ rec["file"] = fn.name
1138
+ records.append(rec)
1139
+ meta.write_text(
1140
+ json.dumps({
1141
+ "total": args.count,
1142
+ "executed": args.count - duplicates_skipped,
1143
+ "duplicates_skipped": duplicates_skipped,
1144
+ "anomalies": len(crashes),
1145
+ "unique_anomalies": len(unique_crashes),
1146
+ "new_behaviors": len(new_behaviors) if evolve else None,
1147
+ "feedback_anomalies": sum(
1148
+ 1 for item in crashes if item.get("kind") == "feedback-anomaly"
1149
+ ),
1150
+ "latency_anomalies": sum(
1151
+ 1 for item in crashes if item.get("kind") == "latency-anomaly"
1152
+ ),
1153
+ "accepted_exits": sorted(accepted_exits),
1154
+ "feedback_json": args.feedback_json,
1155
+ "evolve_dir": str(evolve) if evolve else None,
1156
+ "crashes": records,
1157
+ }, ensure_ascii=False, indent=2),
1158
+ encoding="utf-8",
1159
+ )
1160
+
1161
+ if evolve:
1162
+ # 异常行为同样入行为库:同一崩溃签名跨轮不必重复留种。
1163
+ for c in crashes:
1164
+ if c.get("behavior_sha256"):
1165
+ seen_behaviors.add(c["behavior_sha256"])
1166
+ seed_records = new_behaviors + [
1167
+ c for c in crashes if c.get("behavior_sha256")
1168
+ ]
1169
+ written = _save_evolution(evolve, seen_behaviors, seed_records)
1170
+ print(f"[fuzz_input] 进化回写: 新行为 {len(new_behaviors)} 个,"
1171
+ f"新增种子 {written} 条(库内行为共 {len(seen_behaviors)} 个)-> {evolve}")
1172
+
1173
+ by_kind: dict[str, int] = {}
1174
+ for c in crashes:
1175
+ by_kind[c["kind"]] = by_kind.get(c["kind"], 0) + 1
1176
+ print(f"[fuzz_input] 完成: {args.count} 样本, 去重跳过 {duplicates_skipped} 个,"
1177
+ f"异常 {len(crashes)} 个(唯一签名 {len(unique_crashes)},{by_kind})")
1178
+ print(f"[fuzz_input] 异常样本已写入: {crashes_dir}")
1179
+ print(f"[fuzz_input] 汇总: {meta}")
1180
+ if crashes:
1181
+ print(" 下一步: 用 minimize_repro.py 把异常样本缩到最小复现,再定位根因。")
1182
+ if evolve:
1183
+ print(" 进化模式: 新行为样本已回填种子,下一轮 --evolve 同目录继续。")
1184
+ return 0
1185
+
1186
+
1187
+ if __name__ == "__main__":
1188
+ sys.exit(main())