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,814 @@
1
+ #!/usr/bin/env python3
2
+ """core/scenario_eval.py - L1–L6 分级场景自回归评测引擎。
3
+
4
+ ## 为什么需要它(而不是扩 ``agent_eval.py``)
5
+
6
+ ``agent_eval.py`` 回答的是「给定有已知漏洞的 fixture,能发现几个」。它的 case
7
+ schema **强制**要求 ``fixture`` + ``root_cause`` + ``minimum_severity``——三个
8
+ 字段都预设了「这段代码里藏着一个可命名的漏洞」。
9
+
10
+ 但 L1–L3 级测的根本不是漏洞:
11
+
12
+ L1 空项目 有没有覆盖单元?空结果是否明确而非崩溃/伪造/挂死?
13
+ L2 单文件 单元拆分对不对?干净代码上会不会**编造**发现?
14
+ L3 多语言 Python/JS/Go 是否都被真的看过,还是静默跳过某种语言?
15
+
16
+ 把这些硬塞进 ``root_cause`` 语义会得到两种坏结果:要么给干净代码编造标准答案
17
+ (污染 precision 基线),要么这些级别根本进不了评测。所以两类评测分开:
18
+ **漏洞发现**留在 ``agent_eval.py``,**流水线行为**归本模块。
19
+
20
+ ## 分级
21
+
22
+ L1 空项目 最小链路:不崩、不伪造、不死循环
23
+ L2 单文件 单元拆分 + 干净代码零误报
24
+ L3 多语言 语言覆盖完整性
25
+ L4 已知漏洞 委托 ``agent_eval.py``(本模块只做汇总)
26
+ L5 畸形环境 环境不健康时必须 fail-closed
27
+ L6 并发/超时 委托 ``scripts/run_fault_matrix.py``
28
+
29
+ ## 收据
30
+
31
+ 每次运行产出 ``scenario-receipt.json``:逐级结论 + 度量(耗时、Token)+ 与基线的
32
+ 差异。收据是**可比较**的:同一份基线跑两次,除时间戳外应当字节一致。
33
+ """
34
+ from __future__ import annotations
35
+ # --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
36
+ import sys as _sys
37
+ from pathlib import Path as _Path
38
+
39
+ for _p in _Path(__file__).resolve().parents:
40
+ if (_p / "core" / "bugx.md").is_file():
41
+ if str(_p) not in _sys.path:
42
+ _sys.path.insert(0, str(_p))
43
+ break
44
+ del _p
45
+ import sys
46
+ from pathlib import Path
47
+
48
+
49
+ import argparse
50
+ import hashlib
51
+ import json
52
+ import os
53
+ import re
54
+ import shutil
55
+ import subprocess
56
+ import tempfile
57
+ import time
58
+ from dataclasses import asdict, dataclass, field
59
+ from pathlib import Path
60
+
61
+ REPO_ROOT = Path(__file__).resolve().parents[2]
62
+ SCENARIOS_ROOT = (REPO_ROOT / "verification" / "evals" / "scenarios") if (REPO_ROOT / "verification" / "evals").is_dir() else (REPO_ROOT / "evals" / "scenarios")
63
+ RECEIPT_SCHEMA = 1
64
+
65
+ #: 级别定义。``runner`` 说明该级由谁执行:本模块或外部组件。
66
+ LEVELS: tuple[dict[str, object], ...] = (
67
+ {
68
+ "id": "L1", "name": "空项目", "dir": "L1-empty",
69
+ "runner": "builtin",
70
+ "intent": "最小链路:无覆盖单元时给出明确空结果,不崩、不伪造、不挂死",
71
+ },
72
+ {
73
+ "id": "L2", "name": "单文件", "dir": "L2-single",
74
+ "runner": "builtin",
75
+ "intent": "单元拆分正确,且干净代码上零误报",
76
+ },
77
+ {
78
+ "id": "L3", "name": "多语言", "dir": "L3-multilang",
79
+ "runner": "builtin",
80
+ "intent": "每种语言都被识别并纳入覆盖,不静默跳过",
81
+ },
82
+ {
83
+ "id": "L4", "name": "已知漏洞", "dir": None,
84
+ "runner": "builtin",
85
+ "intent": "召回率/精确率/证据有效性(委托 agent_eval.py)",
86
+ },
87
+ {
88
+ "id": "L5", "name": "畸形环境", "dir": "L5-malformed",
89
+ "runner": "builtin",
90
+ "intent": "环境不健康时 fail-closed,绝不静默降级",
91
+ },
92
+ {
93
+ "id": "L6", "name": "并发超时", "dir": None,
94
+ "runner": "builtin",
95
+ "intent": "9 类故障注入(委托 scripts/run_fault_matrix.py)",
96
+ },
97
+ {
98
+ "id": "L7", "name": "自身健康", "dir": None,
99
+ "runner": "builtin",
100
+ "intent": (
101
+ "BugX 自己有没有坏:6 类结构性风险内省(委托 l7_selfcheck.py)。"
102
+ "L1-L6 测「挖得准不准」,L7 测「BugX 自身是否健康」——"
103
+ "真机无人值守撞出的缺陷几乎全在这一层"
104
+ ),
105
+ },
106
+ )
107
+
108
+
109
+ @dataclass
110
+ class LevelResult:
111
+ """单级结论。``ok`` 是唯一判定器;``detail`` 只说人话,不参与判定。"""
112
+
113
+ level: str
114
+ name: str
115
+ ok: bool
116
+ skipped: bool = False
117
+ duration_seconds: float = 0.0
118
+ checks: list[dict[str, object]] = field(default_factory=list)
119
+ detail: str = ""
120
+ metrics: dict[str, object] = field(default_factory=dict)
121
+
122
+ def add(self, name: str, ok: bool, detail: str = "") -> None:
123
+ self.checks.append({"check": name, "ok": bool(ok), "detail": detail})
124
+ if not ok:
125
+ self.ok = False
126
+
127
+
128
+ def _run(argv: list[str], *, cwd: Path, timeout: float = 120.0,
129
+ env: dict[str, str] | None = None) -> tuple[int, str, str]:
130
+ """执行子命令并返回 (rc, stdout, stderr)。超时视为失败而非异常。"""
131
+ merged = {**os.environ, **(env or {})}
132
+ # 仓库直跑 CLI:子进程 cwd 是场景工作区,须显式指回仓库根;
133
+ # HOME 隔离:评测的全局引擎读写落在一次性沙箱,不碰真实 ~/.bugx/。
134
+ merged["PYTHONPATH"] = str(_repo_root())
135
+ merged["HOME"] = str(_sandbox_home())
136
+ try:
137
+ proc = subprocess.run(
138
+ argv, cwd=str(cwd), capture_output=True, text=True,
139
+ timeout=timeout, env=merged, check=False,
140
+ )
141
+ return proc.returncode, proc.stdout, proc.stderr
142
+ except subprocess.TimeoutExpired as exc:
143
+ return 124, exc.stdout or "", f"timeout after {timeout}s"
144
+ except (OSError, subprocess.SubprocessError) as exc:
145
+ return 127, "", f"{type(exc).__name__}: {exc}"
146
+
147
+
148
+ def _materialize(level_dir: Path, dest: Path) -> Path:
149
+ """把只读场景复制到临时工作区。场景本身保持干净,不写入运行产物。
150
+
151
+ 为什么不原地跑:``bugx init`` 会写 ``.bugx/``、``.dsh/`` 等目录。跑在仓库里
152
+ 会污染工作树,且上一轮残留会让下一轮判定失真(典型表现:L1「空项目」因为
153
+ 上一轮的 ``.bugx`` 而识别出单元)。
154
+ """
155
+ dest.mkdir(parents=True, exist_ok=True)
156
+ shutil.copytree(level_dir, dest, dirs_exist_ok=True)
157
+ return dest
158
+
159
+
160
+ def _repo_root() -> Path:
161
+ """引擎仓根(core/bugx.md 所在目录的父级)。"""
162
+ return Path(__file__).resolve().parents[2]
163
+
164
+
165
+ _SANDBOX_HOME: list[Path] = []
166
+
167
+
168
+ def _sandbox_home() -> Path:
169
+ """一次评测会话共享的隔离 HOME,保护真实 ~/.bugx/ 不被评测写入。
170
+
171
+ F-RSI-20261110-002 评测版事故:全局 ~/.bugx/core 曾被场景评测的
172
+ ``bugx init`` 静默写入(旧 build 的快照 CLI + 无 HOME 隔离),随后
173
+ 「已安装 431 > 安装源 430」的降级判定让 init 在 L1/L2/L3 全挂。
174
+ """
175
+ if not _SANDBOX_HOME:
176
+ _SANDBOX_HOME.append(Path(tempfile.mkdtemp(prefix="bugx-scenario-home-")))
177
+ return _SANDBOX_HOME[0]
178
+
179
+
180
+ def _bugx_argv() -> list[str]:
181
+ """量具与被测物同源:优先仓库直跑 CLI;PATH 快照只作最后退化。
182
+
183
+ 快照 CLI 落后仓库多个 build,用它评测仓库修复等于拿旧量具测新代码
184
+ (实测:快照 430 对仓库 434 的 init 在三个级别全部「拒绝降级」)。
185
+ """
186
+ return [sys.executable, "-m", "interfaces.cli.bugx_cli.cli"]
187
+
188
+
189
+ #: 覆盖清单的两种真实形态。写成两种不是「兼容性懒惰」——实测 2026-11-03:
190
+ #: ``module-coverage.md`` 的单元是**表格行**(``| 1 | 内部 | ROOT | ... |``),
191
+ #: 第一次写这个函数时按列表行 ``- [ ]`` 解析,于是在三语言场景上数出 0 个单元、
192
+ #: 误判成产品缺陷。同时保留列表行是因为 bootstrap 阶段确实会产出那种形态。
193
+ _TABLE_UNIT = re.compile(r"^\|\s*\d+\s*\|")
194
+ _LIST_UNIT = re.compile(r"^- \[")
195
+
196
+
197
+ def _count_units(root: Path) -> int | None:
198
+ """读覆盖清单里的单元数。清单缺失返回 None(区别于「有清单但 0 单元」)。"""
199
+ manifests = list((root / ".bugx").rglob("module-coverage.md"))
200
+ if not manifests:
201
+ return None
202
+ total = 0
203
+ for manifest in manifests:
204
+ try:
205
+ text = manifest.read_text(encoding="utf-8", errors="replace")
206
+ except OSError:
207
+ continue
208
+ for line in text.splitlines():
209
+ if _TABLE_UNIT.match(line) or _LIST_UNIT.match(line):
210
+ total += 1
211
+ return total
212
+
213
+
214
+ def run_l1_empty(root: Path, work: Path) -> LevelResult:
215
+ """L1:空项目必须给出明确的空结果。
216
+
217
+ 判定不看「有没有输出」,看三件事同时成立:
218
+ 1. 命令正常返回(不崩、不超时)
219
+ 2. 覆盖单元为 0 或被明确标注为「无」
220
+ 3. 没有伪造发现
221
+ """
222
+ result = LevelResult(level="L1", name="空项目", ok=True)
223
+ started = time.monotonic()
224
+ rc, out, err = _run([*_bugx_argv(), "init", "--root", ".", "--cloud-sync", "local"],
225
+ cwd=work, timeout=180.0)
226
+ result.add("init 成功", rc == 0, (err or out)[-300:] if rc != 0 else "")
227
+ units = _count_units(work)
228
+ result.add(
229
+ "覆盖单元为 0",
230
+ units in (0, None),
231
+ f"发现 {units} 个单元;空项目不应有可挖掘单元",
232
+ )
233
+ # 空项目若报出发现,一定是伪造
234
+ findings = list((work / ".bugx").rglob("findings*.json"))
235
+ fabricated = []
236
+ for path in findings:
237
+ try:
238
+ payload = json.loads(path.read_text(encoding="utf-8"))
239
+ except (OSError, ValueError):
240
+ continue
241
+ if isinstance(payload, dict) and payload.get("findings"):
242
+ fabricated.append(path.name)
243
+ result.add("无伪造发现", not fabricated, f"空项目产出发现:{fabricated}")
244
+ result.duration_seconds = time.monotonic() - started
245
+ result.metrics = {"units": units, "fabricated": len(fabricated)}
246
+ return result
247
+
248
+
249
+ def run_l2_single(root: Path, work: Path) -> LevelResult:
250
+ """L2:单文件必须正确拆出 1 个单元,且干净代码上零误报。"""
251
+ result = LevelResult(level="L2", name="单文件", ok=True)
252
+ started = time.monotonic()
253
+ rc, out, err = _run([*_bugx_argv(), "init", "--root", ".", "--cloud-sync", "local"],
254
+ cwd=work, timeout=180.0)
255
+ result.add("init 成功", rc == 0, (err or out)[-300:] if rc != 0 else "")
256
+ source_files = [
257
+ p for p in work.rglob("*.py")
258
+ if ".bugx" not in p.parts and p.name != "conftest.py"
259
+ ]
260
+ result.add("场景含 1 个源文件", len(source_files) == 1,
261
+ f"实际 {len(source_files)} 个:{[p.name for p in source_files]}")
262
+ # 干净代码:任何断言为 confirmed 的发现都算误报
263
+ false_positives = _confirmed_findings(work)
264
+ result.add(
265
+ "干净代码零误报", not false_positives,
266
+ f"误报 {len(false_positives)} 条:{false_positives[:3]}",
267
+ )
268
+ result.duration_seconds = time.monotonic() - started
269
+ result.metrics = {"source_files": len(source_files),
270
+ "false_positives": len(false_positives)}
271
+ return result
272
+
273
+
274
+ def _confirmed_findings(root: Path) -> list[str]:
275
+ """收集被判定为 confirmed 的发现标题(用于零误报检查)。"""
276
+ titles: list[str] = []
277
+ for path in (root / ".bugx").rglob("*.json"):
278
+ if "findings" not in path.name:
279
+ continue
280
+ try:
281
+ payload = json.loads(path.read_text(encoding="utf-8"))
282
+ except (OSError, ValueError):
283
+ continue
284
+ items = payload.get("findings") if isinstance(payload, dict) else payload
285
+ if not isinstance(items, list):
286
+ continue
287
+ for item in items:
288
+ if not isinstance(item, dict):
289
+ continue
290
+ status = str(item.get("status", "")).lower()
291
+ if status in {"confirmed", "verified", "fixed"}:
292
+ titles.append(str(item.get("title") or item.get("id") or "?"))
293
+ return titles
294
+
295
+
296
+ def run_l3_multilang(root: Path, work: Path) -> LevelResult:
297
+ """L3:三种语言都必须被识别并纳入覆盖。
298
+
299
+ 这一级抓的是「静默跳过某种语言」——最危险的一类缺陷,因为审计报告看起来
300
+ 完整,实际有文件从未被看过。
301
+ """
302
+ result = LevelResult(level="L3", name="多语言", ok=True)
303
+ started = time.monotonic()
304
+ rc, out, err = _run([*_bugx_argv(), "init", "--root", ".", "--cloud-sync", "local"],
305
+ cwd=work, timeout=180.0)
306
+ result.add("init 成功", rc == 0, (err or out)[-300:] if rc != 0 else "")
307
+ expected = {".py": "python", ".js": "javascript", ".go": "go"}
308
+ present = {ext: kind for ext, kind in expected.items()
309
+ if any(work.rglob(f"*{ext}"))}
310
+ result.add(
311
+ "场景含三种语言", len(present) == 3,
312
+ f"仅发现:{sorted(present.values())}",
313
+ )
314
+ # 语言探测必须对每个文件给出判定,缺失即「静默跳过」
315
+ rc, out, err = _run(
316
+ [*_bugx_argv(), "engine", "--root", ".", "status"], cwd=work, timeout=120.0,
317
+ )
318
+ result.add("engine status 可执行", rc == 0, (err or out)[-300:] if rc != 0 else "")
319
+ units = _count_units(work)
320
+ result.add(
321
+ "覆盖单元非空", bool(units),
322
+ f"三语言场景应有覆盖单元,实际 {units}",
323
+ )
324
+ result.duration_seconds = time.monotonic() - started
325
+ result.metrics = {"languages": sorted(present.values()), "units": units}
326
+ return result
327
+
328
+
329
+ def _doctor_check(root: Path, name_contains: str) -> dict[str, object]:
330
+ """在 ``doctor --json`` 输出里取指定检查项的结论。
331
+
332
+ 用结构化 JSON 而不是 grep 文本:文本判据无法区分「这条检查失败」与
333
+ 「别处的日志恰好含这个词」,而 L5 的全部价值就在于精确定位。
334
+ """
335
+ rc, out, err = _run(
336
+ [*_bugx_argv(), "doctor", "--root", ".", "--json"],
337
+ cwd=root, timeout=120.0,
338
+ )
339
+ payload: object = None
340
+ for candidate in (out, err):
341
+ text = (candidate or "").strip()
342
+ if not text.startswith("{"):
343
+ continue
344
+ try:
345
+ payload = json.loads(text)
346
+ break
347
+ except ValueError:
348
+ continue
349
+ if not isinstance(payload, dict):
350
+ return {"ok": False, "detail": f"doctor --json 无有效输出 (rc={rc})"}
351
+ checks = payload.get("checks")
352
+ if not isinstance(checks, list):
353
+ return {"ok": False, "detail": "doctor --json 缺 checks 数组"}
354
+ for item in checks:
355
+ if not isinstance(item, dict):
356
+ continue
357
+ if name_contains in str(item.get("name", "")):
358
+ return {"ok": bool(item.get("ok")), "detail": str(item.get("detail") or "")}
359
+ return {"ok": False, "detail": f"未找到检查项:{name_contains}"}
360
+
361
+
362
+ def _probe_engine_integrity(root: Path) -> dict[str, object]:
363
+ """引擎完整性检查项——缺 engine-integrity.json 时它必须失败。"""
364
+ return _doctor_check(root, "引擎完整性")
365
+
366
+
367
+ def _probe_state_writable(root: Path) -> dict[str, object]:
368
+ """状态目录可写性——只读时写入类检查必须失败。"""
369
+ # doctor 没有专门的「状态目录可写」项,改用实际写入探测:与 doctor 的
370
+ # fail-closed 结论等价,但更直接(能否写是一条客观事实,不是文本判断)。
371
+ probe = root / ".bugx" / "state" / ".write-probe"
372
+ try:
373
+ probe.parent.mkdir(parents=True, exist_ok=True)
374
+ probe.write_text("x", encoding="utf-8")
375
+ probe.unlink()
376
+ return {"ok": True, "detail": "状态目录可写"}
377
+ except OSError as exc:
378
+ return {"ok": False, "detail": f"{type(exc).__name__}: {exc}"}
379
+
380
+
381
+ def _probe_coverage_paths(root: Path) -> dict[str, object]:
382
+ """覆盖清单路径安全性——含逃逸路径时必须被拒。"""
383
+ return _doctor_check(root, "覆盖")
384
+
385
+
386
+ def _inject_missing_integrity(work: Path) -> None:
387
+ for path in work.rglob("engine-integrity.json"):
388
+ path.unlink()
389
+
390
+
391
+ def _inject_readonly_state(work: Path) -> None:
392
+ state = work / ".bugx" / "state"
393
+ state.mkdir(parents=True, exist_ok=True)
394
+ state.chmod(0o500)
395
+
396
+
397
+ def _inject_escaping_manifest(work: Path) -> None:
398
+ """覆盖清单里塞一个逃逸路径(../../etc/passwd 类)。"""
399
+ manifests = list((work / ".bugx").rglob("module-coverage.md"))
400
+ target = manifests[0] if manifests else (
401
+ work / ".bugx" / "state" / "module-coverage.md"
402
+ )
403
+ target.parent.mkdir(parents=True, exist_ok=True)
404
+ target.write_text(
405
+ "- [ ] ../../../../etc/passwd\n- [ ] 内部:src/app.py:all\n",
406
+ encoding="utf-8",
407
+ )
408
+
409
+
410
+ #: 畸形注入用例:(名称, 注入函数, 定向探针)。探针必须能**区分**注入前后,
411
+ #: 否则这一级等于没测——第一版就是败在这里。
412
+ MALFORMED_CASES: tuple[tuple[str, object, object], ...] = (
413
+ ("状态目录只读", _inject_readonly_state, _probe_state_writable),
414
+ ("覆盖清单含逃逸路径", _inject_escaping_manifest, _probe_coverage_paths),
415
+ )
416
+
417
+ #: 刻意**不**收录的畸形,附原因——避免后来者再把它加回来重踩:
418
+ #:
419
+ #: * 「缺 engine-integrity.json」:``engine-integrity.json`` 是**全局引擎**的
420
+ #: 文件,项目里本来就没有。删它等于什么都没做,而 doctor 如实报告「全局引擎
421
+ #: 488 个文件哈希一致」是对的。第一版把它当项目级畸形,判据因此永远通过——
422
+ #: 这类「测了一个不存在的对象」的用例,比没有用例更糟:它给出虚假的安全感。
423
+
424
+
425
+ def run_l5_malformed(root: Path, work: Path) -> LevelResult:
426
+ """L5:环境不健康时必须 fail-closed。
427
+
428
+ ## 判据为什么必须**定向**
429
+
430
+ 第一版判据是「``doctor`` 非零退出 **或** 输出里出现『缺失/拒绝/权限』等词」。
431
+ 实测这个判据是坏的:一个**完全正常**的项目跑 ``doctor`` 也返回 rc=1,并含
432
+ 27 处上述关键词——因为总有可选宿主检查在失败(hosts.json、Pi Skill、
433
+ OpenCode 配置)。于是该判据无条件放行,L5 等于什么都没测。
434
+
435
+ 现在的判据是:拿**同一次运行**里、同一条检查项在「注入前」与「注入后」的
436
+ 结论比对。只有「注入前通过 → 注入后失败」才算真的 fail-closed。这样自然
437
+ 排除了那些与本次注入无关的既存失败。
438
+ """
439
+ result = LevelResult(level="L5", name="畸形环境", ok=True)
440
+ started = time.monotonic()
441
+ scenario = SCENARIOS_ROOT / "L5-malformed"
442
+ for name, inject, probe in MALFORMED_CASES:
443
+ with tempfile.TemporaryDirectory(prefix="bugx-l5-") as tmp:
444
+ case_root = Path(tmp) / "proj"
445
+ case_root.mkdir(parents=True)
446
+ if scenario.is_dir():
447
+ shutil.copytree(scenario, case_root, dirs_exist_ok=True)
448
+ _run([*_bugx_argv(), "init", "--root", ".", "--cloud-sync", "local"],
449
+ cwd=case_root, timeout=120.0)
450
+ # 基线:注入**前**该检查项的状态。这一步是整个判据的地基。
451
+ before = probe(case_root)
452
+ try:
453
+ inject(case_root)
454
+ except OSError as exc:
455
+ result.add(f"{name}(注入)", False, f"注入失败:{exc}")
456
+ continue
457
+ after = probe(case_root)
458
+ if not before["ok"]:
459
+ # 注入前就没通过 → 这条检查项对本项目不适用,无法作为判据。
460
+ result.add(
461
+ f"{name}(前置状态)", True,
462
+ f"注入前该项已失败({before['detail'][:80]}),跳过定向比对",
463
+ )
464
+ continue
465
+ detected = not after["ok"]
466
+ result.add(
467
+ f"{name} → fail-closed",
468
+ detected,
469
+ (f"已检出({after['detail'][:120]})" if detected
470
+ else f"注入后仍报告通过({after['detail'][:120]}):畸形被静默接受"),
471
+ )
472
+ for path in case_root.rglob("*"):
473
+ try:
474
+ if path.is_dir():
475
+ path.chmod(0o700)
476
+ except OSError:
477
+ pass
478
+ result.duration_seconds = time.monotonic() - started
479
+ return result
480
+
481
+
482
+ def run_l4_known_vulns(root: Path, work: Path) -> LevelResult:
483
+ """L4:委托 ``agent_eval.py`` 的召回/精确/证据/复现评分。
484
+
485
+ 这里**不重算**任何指标——重算是分叉的开始。本函数只做两件事:调用既有评测、
486
+ 把它的结论翻译成 LevelResult。度量(耗时/Token)随收据一起记录。
487
+ """
488
+ result = LevelResult(level="L4", name="已知漏洞", ok=True)
489
+ started = time.monotonic()
490
+ rc, out, err = _run(
491
+ [sys.executable, str(REPO_ROOT / "core" / "agent" / "agent_eval.py"),
492
+ "score", "--strict"],
493
+ cwd=REPO_ROOT, timeout=300.0,
494
+ )
495
+ combined = f"{out}\n{err}"
496
+ result.add("agent_eval score 通过", rc == 0, combined[-400:] if rc != 0 else "")
497
+ # 抓取关键指标写进收据,便于跨轮比较
498
+ metrics: dict[str, object] = {}
499
+ for line in combined.splitlines():
500
+ line = line.strip()
501
+ for label, key in (
502
+ ("发现率:", "recall"), ("精确率:", "precision"),
503
+ ("证据有效率:", "evidence_validity"), ("可复现率:", "reproducibility"),
504
+ ("综合质量分:", "quality"),
505
+ ):
506
+ if line.startswith(label):
507
+ value = line[len(label):].strip()
508
+ metrics[key] = value
509
+ if line.startswith("耗时/Token:"):
510
+ parts = line[len("耗时/Token:"):].strip().split("/")
511
+ metrics["duration"] = parts[0].strip()
512
+ metrics["tokens"] = parts[-1].strip() if len(parts) > 1 else None
513
+ result.add(
514
+ "关键指标可解析", bool(metrics.get("recall")),
515
+ f"未能从输出解析发现率:{combined[-200:]}",
516
+ )
517
+ result.duration_seconds = time.monotonic() - started
518
+ result.metrics = metrics
519
+ return result
520
+
521
+
522
+ def run_l6_fault_matrix(root: Path, work: Path) -> LevelResult:
523
+ """L6:委托 ``scripts/run_fault_matrix.py`` 的 9 类故障注入。
524
+
525
+ 同样不重写:故障注入的语义(租约回收、预算终态、输出截断…)已经在那个
526
+ 脚本里被仔细定义过,复制一份只会让两处慢慢漂移。
527
+ """
528
+ result = LevelResult(level="L6", name="并发超时", ok=True)
529
+ started = time.monotonic()
530
+ sandbox = Path(tempfile.mkdtemp(prefix="bugx-l6-"))
531
+ receipt = sandbox / "fault-matrix-receipt.json"
532
+ try:
533
+ rc, out, err = _run(
534
+ [sys.executable, str(REPO_ROOT / "scripts" / "cve" / "run_fault_matrix.py"),
535
+ "--sandbox", str(sandbox), "--output", str(receipt), "--json"],
536
+ cwd=REPO_ROOT, timeout=600.0,
537
+ )
538
+ combined = f"{out}\n{err}"
539
+ result.add("故障矩阵通过", rc == 0, combined[-400:] if rc != 0 else "")
540
+ metrics: dict[str, object] = {}
541
+ if receipt.is_file():
542
+ try:
543
+ payload = json.loads(receipt.read_text(encoding="utf-8"))
544
+ except (OSError, ValueError):
545
+ payload = None
546
+ if isinstance(payload, dict):
547
+ scenarios = payload.get("scenarios") or payload.get("cases") or []
548
+ if isinstance(scenarios, list):
549
+ metrics["scenarios_total"] = len(scenarios)
550
+ # 真实收据用 ``status`` 字符串(PASSED/FAILED),不是 ``ok``
551
+ # 布尔。第一版按 ``not s.get("ok", True)`` 取失败项,恒为空,
552
+ # 于是「全部通过」与「判别失效」在收据里长得一模一样。
553
+ failed = [
554
+ (s.get("case_id") or s.get("name") or "?")
555
+ for s in scenarios
556
+ if isinstance(s, dict)
557
+ and str(s.get("status", "")).upper() not in {"PASSED", "OK"}
558
+ ]
559
+ metrics["scenarios_failed"] = failed
560
+ result.add(
561
+ "无失败场景", not failed,
562
+ f"{len(failed)} 个场景失败:{failed}",
563
+ )
564
+ result.add(
565
+ "收据含场景结果", bool(metrics.get("scenarios_total")),
566
+ "故障矩阵收据没有 scenarios/cases 数组",
567
+ )
568
+ else:
569
+ result.add("生成故障矩阵收据", False, f"缺少 {receipt}")
570
+ result.duration_seconds = time.monotonic() - started
571
+ result.metrics = metrics
572
+ return result
573
+ finally:
574
+ shutil.rmtree(sandbox, ignore_errors=True)
575
+
576
+
577
+ def run_l7_selfcheck(root: Path, work: Path) -> LevelResult:
578
+ """L7:BugX 自身健康自检。
579
+
580
+ 与 L1-L6 的根本区别:**不需要外部项目**。L1-L6 都在验证「给一个项目,
581
+ BugX 能不能正确处理」,L7 验证「BugX 自己的结构有没有坏」。
582
+
583
+ ## 静态与动态两层
584
+
585
+ 静态 6 项(``l7_selfcheck``)是结构分析,0.00s,每轮都跑。
586
+ 动态 4 项(``l7_dynamic``)真起子进程跑 CLI,约 12s,按需开启。
587
+
588
+ 为什么不在这一级默认开动态:L7 作为级别会被每轮调用,一条 12s 的
589
+ 检查会让整轮变慢 30%,然后它就会被从流程里摘掉——保护归零。
590
+ 动态层通过 ``RSI_L7_DYNAMIC=1`` 显式开启,用于提交前 / 排查。
591
+
592
+ 这个取舍是刻意的:**能持续跑的低成本检查,胜过跑不动的高成本检查**。
593
+ """
594
+ result = LevelResult(level="L7", name="自身健康", ok=True)
595
+ started = time.monotonic()
596
+ try:
597
+ from core.repair import l7_selfcheck
598
+ except ImportError as exc: # 归档路径导入失败必须显式判红,而不是换名重试
599
+ result.add("自检模块可导入", False, str(exc))
600
+ return result
601
+
602
+ dynamic = os.environ.get("RSI_L7_DYNAMIC", "").strip() in {"1", "true", "yes"}
603
+ payload = l7_selfcheck.run_all(root, dynamic=dynamic)
604
+ summary = payload.get("summary", {})
605
+ if summary.get("not_applicable"):
606
+ # 目标不是引擎仓库:跳过而不是记 0/0「通过」。0/0 会被误读成
607
+ # 「什么都没检查但绿灯」,而实际情况是「这层检查对当前目标无意义」。
608
+ result.ok = True
609
+ result.skipped = True
610
+ result.add("L7 不适用", True, str(summary.get("reason") or ""))
611
+ result.duration_seconds = round(time.monotonic() - started, 2)
612
+ return result
613
+ result.add(
614
+ "全部自检通过",
615
+ bool(summary.get("ok")),
616
+ f"{summary.get('passed', 0)}/{summary.get('total', 0)} 通过"
617
+ + (f";失败:{', '.join(summary.get('checks_failed', []))}"
618
+ if summary.get("checks_failed") else ""),
619
+ )
620
+ for check in payload.get("checks", []):
621
+ result.add(
622
+ f"{check.get('id')} {check.get('name')}",
623
+ bool(check.get("ok")),
624
+ str(check.get("detail") or "")[:300],
625
+ )
626
+ # 计时必须真实:L7 静态 0.00s、动态约 12s,两类成本差三个数量级。
627
+ # 不记时会让「动态到底值不值这个价」变成猜测。
628
+ result.duration_seconds = time.monotonic() - started
629
+ return result
630
+
631
+
632
+ BUILTIN_RUNNERS = {
633
+ "L1": run_l1_empty,
634
+ "L2": run_l2_single,
635
+ "L3": run_l3_multilang,
636
+ "L4": run_l4_known_vulns,
637
+ "L5": run_l5_malformed,
638
+ "L6": run_l6_fault_matrix,
639
+ "L7": run_l7_selfcheck,
640
+ }
641
+
642
+
643
+ #: 在**仓库根**执行、不需要临时工作区的级别。L4/L6 评的是仓库自带的评测集与
644
+ #: 故障矩阵,物化到临时目录反而会让它们找不到 ``evals/`` 和 ``scripts/``。
645
+ REPO_LEVELS = frozenset({"L4", "L6", "L7"})
646
+
647
+
648
+ def run_level(level: dict[str, object], *, keep: bool = False) -> LevelResult:
649
+ """执行单个级别。"""
650
+ level_id = str(level["id"])
651
+ runner = str(level["runner"])
652
+ if runner != "builtin":
653
+ return LevelResult(
654
+ level=level_id, name=str(level["name"]), ok=True, skipped=True,
655
+ detail=f"由 {runner} 执行:{level['intent']}",
656
+ )
657
+ if level_id in REPO_LEVELS:
658
+ return BUILTIN_RUNNERS[level_id](REPO_ROOT, REPO_ROOT)
659
+ scenario_dir = SCENARIOS_ROOT / str(level["dir"])
660
+ if not scenario_dir.is_dir():
661
+ return LevelResult(
662
+ level=level_id, name=str(level["name"]), ok=False,
663
+ detail=f"场景目录缺失:{scenario_dir}",
664
+ )
665
+ tmp_root = Path(tempfile.mkdtemp(prefix=f"bugx-{level_id.lower()}-"))
666
+ try:
667
+ work = _materialize(scenario_dir, tmp_root / "proj")
668
+ return BUILTIN_RUNNERS[level_id](tmp_root / "proj", work)
669
+ finally:
670
+ for path in tmp_root.rglob("*"):
671
+ try:
672
+ if path.is_dir():
673
+ path.chmod(0o700)
674
+ except OSError:
675
+ pass
676
+ if not keep:
677
+ shutil.rmtree(tmp_root, ignore_errors=True)
678
+
679
+
680
+ def build_receipt(results: list[LevelResult], *, started_at: float) -> dict[str, object]:
681
+ """组装机器可读收据。字段顺序固定,便于跨轮 diff。"""
682
+ total_duration = sum(r.duration_seconds for r in results)
683
+ executed = [r for r in results if not r.skipped]
684
+ failed = [r.level for r in results if not r.ok]
685
+ return {
686
+ "schema_version": RECEIPT_SCHEMA,
687
+ "generated_at_unix": int(started_at),
688
+ "levels": [
689
+ {
690
+ "level": r.level,
691
+ "name": r.name,
692
+ "ok": r.ok,
693
+ "skipped": r.skipped,
694
+ "duration_seconds": round(r.duration_seconds, 3),
695
+ "metrics": r.metrics,
696
+ "detail": r.detail,
697
+ "checks": r.checks,
698
+ }
699
+ for r in results
700
+ ],
701
+ "summary": {
702
+ "levels_total": len(results),
703
+ "levels_executed": len(executed),
704
+ "levels_failed": failed,
705
+ "ok": not failed,
706
+ "duration_seconds": round(total_duration, 3),
707
+ },
708
+ }
709
+
710
+
711
+ def receipt_digest(receipt: dict[str, object]) -> str:
712
+ """除时间戳外的内容摘要,用于「同一基线两次运行应一致」的比对。"""
713
+ stable = {k: v for k, v in receipt.items() if k != "generated_at_unix"}
714
+ blob = json.dumps(stable, sort_keys=True, ensure_ascii=False).encode("utf-8")
715
+ return hashlib.sha256(blob).hexdigest()
716
+
717
+
718
+ def compare_baseline(receipt: dict[str, object], baseline: dict[str, object]) -> list[str]:
719
+ """与基线对比,返回回退项。只报「变坏」,不报「新增通过」。"""
720
+ failures: list[str] = []
721
+ before = {str(item["level"]): item for item in baseline.get("levels", [])}
722
+ for item in receipt.get("levels", []):
723
+ level = str(item["level"])
724
+ prev = before.get(level)
725
+ if prev is None:
726
+ continue
727
+ if prev.get("ok") and not item.get("ok"):
728
+ failures.append(f"{level} 由通过回退为失败:{item.get('detail') or ''}")
729
+ # 总体回退只在「基线里的每个级别本轮都还在,且确实变坏」时才报。
730
+ # 否则新增一个从未跑过的级别(本身失败)也会触发总体告警——那不是回退,
731
+ # 是首次覆盖,混进来会让基线一加级别就永久报警。
732
+ prev_summary = baseline.get("summary", {})
733
+ known_bad = {
734
+ level for level, prev in before.items()
735
+ if prev.get("ok") is False
736
+ }
737
+ now_items = {str(item["level"]): item for item in receipt.get("levels", [])}
738
+ regressed = {
739
+ level for level in before
740
+ if before[level].get("ok") and level in now_items
741
+ and not now_items[level].get("ok")
742
+ }
743
+ if (prev_summary.get("ok") and not receipt.get("summary", {}).get("ok")
744
+ and regressed):
745
+ failures.append("总体由 ok 回退为失败")
746
+ return failures
747
+
748
+
749
+ def main(argv: list[str] | None = None) -> int:
750
+ parser = argparse.ArgumentParser(description="L1–L6 分级场景自回归评测")
751
+ parser.add_argument("--root", default=str(REPO_ROOT), help="仓库根目录")
752
+ parser.add_argument("--level", action="append", default=None,
753
+ help="只跑指定级别(可重复,如 --level L1 --level L2)")
754
+ parser.add_argument("--receipt", default=None, help="收据输出路径")
755
+ parser.add_argument("--baseline", default=None, help="基线收据路径(对比回退)")
756
+ parser.add_argument("--keep", action="store_true", help="保留临时工作区便于排查")
757
+ parser.add_argument("--json", action="store_true", help="把收据打到 stdout")
758
+ args = parser.parse_args(argv)
759
+
760
+ selected = set(args.level or [])
761
+ started = time.time()
762
+ results: list[LevelResult] = []
763
+ for level in LEVELS:
764
+ if selected and str(level["id"]) not in selected:
765
+ continue
766
+ results.append(run_level(level, keep=args.keep))
767
+
768
+ receipt = build_receipt(results, started_at=started)
769
+ receipt["digest"] = receipt_digest(receipt)
770
+
771
+ baseline_failures: list[str] = []
772
+ if args.baseline:
773
+ path = Path(args.baseline).expanduser()
774
+ if path.is_file():
775
+ try:
776
+ baseline_failures = compare_baseline(
777
+ receipt, json.loads(path.read_text(encoding="utf-8")),
778
+ )
779
+ except (OSError, ValueError) as exc:
780
+ baseline_failures = [f"基线无法读取:{exc}"]
781
+ else:
782
+ baseline_failures = [f"基线文件不存在:{path}"]
783
+ receipt["baseline_failures"] = baseline_failures
784
+
785
+ if args.receipt:
786
+ target = Path(args.receipt).expanduser()
787
+ target.parent.mkdir(parents=True, exist_ok=True)
788
+ target.write_text(
789
+ json.dumps(receipt, indent=2, ensure_ascii=False) + "\n", encoding="utf-8",
790
+ )
791
+
792
+ if args.json:
793
+ print(json.dumps(receipt, indent=2, ensure_ascii=False))
794
+ else:
795
+ for item in receipt["levels"]:
796
+ mark = "SKIP" if item["skipped"] else ("PASS" if item["ok"] else "FAIL")
797
+ print(f"[{item['level']}] {mark:4s} {item['name']:8s} "
798
+ f"{item['duration_seconds']:6.2f}s {item['detail']}")
799
+ for check in item["checks"]:
800
+ if not check["ok"]:
801
+ print(f" ✗ {check['check']}: {check['detail']}")
802
+ summary = receipt["summary"]
803
+ print(f"\n汇总:{summary['levels_executed']}/{summary['levels_total']} 级执行,"
804
+ f"失败 {summary['levels_failed'] or '无'},"
805
+ f"耗时 {summary['duration_seconds']:.2f}s")
806
+ for failure in baseline_failures:
807
+ print(f" 基线回退:{failure}")
808
+
809
+ failed = bool(receipt["summary"]["levels_failed"]) or bool(baseline_failures)
810
+ return 1 if failed else 0
811
+
812
+
813
+ if __name__ == "__main__":
814
+ sys.exit(main())