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,1219 @@
1
+ #!/usr/bin/env python3
2
+ """launch_phases/supervisor_degraded.py - 降级探针治理、自愈修复、突变门禁与工具链豁免。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import shlex
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from collections.abc import Mapping
17
+ from core.launch_phases.common import (
18
+ resolve_project_root,
19
+ uses_project_layout,
20
+ supervisor_state_path,
21
+ child_environment,
22
+ run_child,
23
+ bugx_paths,
24
+ )
25
+ from core.launch_phases.session_runtime import (
26
+ load_runtime,
27
+ save_runtime,
28
+ iso_time,
29
+ runtime_lock,
30
+ )
31
+ from core.repair import self_heal
32
+ from core.host_runtime import host_registry
33
+ from core.runtime.tool_install_targets import PROBE_REPAIR_TARGETS
34
+
35
+
36
+
37
+ def ask_interaction(*args, **kwargs):
38
+ sb = _sb()
39
+ if sb and hasattr(sb, "ask_interaction"):
40
+ fn = getattr(sb, "ask_interaction")
41
+ if fn is not ask_interaction:
42
+ return fn(*args, **kwargs)
43
+ from core.launch_phases.startup_interaction import ask_interaction as real
44
+ return real(*args, **kwargs)
45
+
46
+ def answered_values(*args, **kwargs):
47
+ sb = _sb()
48
+ if sb and hasattr(sb, "answered_values"):
49
+ fn = getattr(sb, "answered_values")
50
+ if fn is not answered_values:
51
+ return fn(*args, **kwargs)
52
+ from core.launch_phases.startup_interaction import answered_values as real
53
+ return real(*args, **kwargs)
54
+
55
+ def answered_value(*args, **kwargs):
56
+ sb = _sb()
57
+ if sb and hasattr(sb, "answered_value"):
58
+ fn = getattr(sb, "answered_value")
59
+ if fn is not answered_value:
60
+ return fn(*args, **kwargs)
61
+ from core.launch_phases.startup_interaction import answered_value as real
62
+ return real(*args, **kwargs)
63
+
64
+ def _degraded_install(*args, **kwargs):
65
+ sb = _sb()
66
+ if sb and hasattr(sb, "_degraded_install"):
67
+ fn = getattr(sb, "_degraded_install")
68
+ if fn is not _degraded_install:
69
+ return fn(*args, **kwargs)
70
+ return degraded_install(*args, **kwargs)
71
+
72
+
73
+ def run_preflight_probes(*args, **kwargs):
74
+ sb = _sb()
75
+ if sb and hasattr(sb, "run_preflight_probes"):
76
+ return sb.run_preflight_probes(*args, **kwargs)
77
+ raise RuntimeError("supervisor_bridge.run_preflight_probes not available")
78
+
79
+
80
+ class _AgentDirProxy:
81
+ def _target(self):
82
+ sb = _sb()
83
+ if sb and hasattr(sb, "AGENT_DIR"):
84
+ return getattr(sb, "AGENT_DIR")
85
+ from core.launch_phases.common import AGENT_DIR as real
86
+ return real
87
+ def resolve(self):
88
+ return self._target().resolve()
89
+ def __getattr__(self, name):
90
+ return getattr(self._target(), name)
91
+
92
+ AGENT_DIR = _AgentDirProxy()
93
+
94
+ def _sb():
95
+ return sys.modules.get("core.launch_phases.supervisor_bridge") or sys.modules.get("launch_phases.supervisor_bridge")
96
+
97
+ def _get_sb_attr(name: str, fallback=None):
98
+ sb = _sb()
99
+ if sb and hasattr(sb, name):
100
+ return getattr(sb, name)
101
+ return fallback
102
+
103
+ def _resolve_project_root(*args, **kwargs):
104
+ fn = _get_sb_attr("resolve_project_root", resolve_project_root)
105
+ return fn(*args, **kwargs)
106
+
107
+ def degraded_actions(report: dict, *, probe_name: str = "") -> list[dict]:
108
+ """从探针 JSON 报告提取降级项与对应处置选项。
109
+
110
+ MCP 缺失/未配置必须进入专用交互菜单。``probe_name`` 用来保留探针
111
+ 的组件语义:codebase-memory-mcp 的子检查名称是 binary/cli,单看子
112
+ 检查名无法识别它属于 MCP。
113
+ """
114
+ from core.probes import probe_registry
115
+ return probe_registry.extract_degraded_actions(report, probe_name=probe_name)
116
+
117
+ _LAST_SELF_HEAL_REPORT: self_heal.HealReport | None = None
118
+
119
+ # C1 decisions are deliberately separate from their human-readable labels.
120
+ # A display string can be copied from a prompt or supplied by a host; it must
121
+ # never be able to manufacture a successful gate result.
122
+ DEGRADED_HEALED = "healed"
123
+ DEGRADED_NOT_APPLICABLE = "not_applicable"
124
+ DEGRADED_EXEMPTED = "exempted"
125
+ DEGRADED_BLOCKED = "blocked"
126
+ DEGRADED_DEFERRED = "deferred"
127
+ DEGRADED_TRANSIENT = "transient"
128
+ DEGRADED_PASSING_STATUSES = frozenset({
129
+ DEGRADED_HEALED, DEGRADED_NOT_APPLICABLE, DEGRADED_TRANSIENT,
130
+ })
131
+
132
+ _DEGRADED_HEALED = DEGRADED_HEALED
133
+ _DEGRADED_NOT_APPLICABLE = DEGRADED_NOT_APPLICABLE
134
+ _DEGRADED_EXEMPTED = DEGRADED_EXEMPTED
135
+ _DEGRADED_BLOCKED = DEGRADED_BLOCKED
136
+ _DEGRADED_DEFERRED = DEGRADED_DEFERRED
137
+ _DEGRADED_TRANSIENT = DEGRADED_TRANSIENT
138
+ _DEGRADED_PASSING_STATUSES = DEGRADED_PASSING_STATUSES
139
+
140
+
141
+ class DegradedDecision(str):
142
+ """String-compatible display value carrying an internal typed C1 status."""
143
+
144
+ __slots__ = ("status", "receipt")
145
+
146
+ def __new__(
147
+ cls, status: str, display: str, receipt: Mapping[str, Any] | None = None,
148
+ ):
149
+ value = str.__new__(cls, display)
150
+ value.status = status
151
+ value.receipt = dict(receipt or {})
152
+ return value
153
+
154
+
155
+ def degraded_decision(
156
+ status: str, display: str, receipt: Mapping[str, Any] | None = None,
157
+ ) -> _DegradedDecision:
158
+ return _DegradedDecision(status, display, receipt)
159
+
160
+
161
+ def degraded_item_not_applicable(item: Mapping[str, Any]) -> bool:
162
+ """Return True only for an explicit machine-level applicability result."""
163
+ status = str(item.get("status", "")).strip().casefold()
164
+ applicability = str(item.get("applicability", "")).strip().casefold()
165
+ return bool(
166
+ item.get("not_applicable") is True
167
+ or status == _DEGRADED_NOT_APPLICABLE
168
+ or applicability == _DEGRADED_NOT_APPLICABLE
169
+ )
170
+
171
+
172
+ def degraded_item_advisory(item: Mapping[str, Any]) -> bool:
173
+ """描述符声明 ``required=False`` 的建议性探针(如 openwiki)。
174
+
175
+ 注册表已判定"缺失不阻断启动",门禁必须尊重同一份机器声明;否则
176
+ advisory 探针会从降级通道反向变成硬阻断,与它自己的注册契约冲突。
177
+ """
178
+ return item.get("advisory") is True
179
+
180
+
181
+ def degraded_item_transient(item: Mapping[str, Any]) -> bool:
182
+ """二进制/插件**存在**但本次调用超时或异常(``transient`` 由注册中心置位)。"""
183
+ return item.get("transient") is True
184
+
185
+
186
+ def degraded_item_critical(item: Mapping[str, Any]) -> bool:
187
+ """能力是否 critical:以描述符机器声明为准,缺失时才回落到 ``kind=mcp`` 猜测。"""
188
+ declared = item.get("critical")
189
+ if isinstance(declared, bool):
190
+ return declared
191
+ name = str(item.get("name", "")).casefold()
192
+ return bool(item.get("kind") == "mcp" or "mcp" in name)
193
+
194
+
195
+ def degraded_exemption_hit(name: str, exemptions: set[str]) -> bool:
196
+ """豁免名匹配:支持完整条目名与探针级前缀(``codebase-memory-mcp/cli`` ← ``codebase-memory-mcp``)。"""
197
+ lowered = name.casefold()
198
+ if lowered in exemptions:
199
+ return True
200
+ probe = lowered.split("/", 1)[0].strip()
201
+ return bool(probe) and probe in exemptions
202
+
203
+
204
+ def degraded_decision_for_policy(item: Mapping[str, Any]) -> _DegradedDecision | None:
205
+ """按注册表机器语义给出**非阻断**决策;返回 None 表示仍需人工/自愈决策。
206
+
207
+ 顺序即优先级:显式不适用 → 建议性探针 → 瞬态降级。三者都必须留痕,
208
+ 且都不得借此启用任何能力(例如 codebase-memory 仍会被强制降级模式)。
209
+ """
210
+ name = str(item.get("name", "unknown"))
211
+ detail = str(item.get("detail", ""))
212
+ if _degraded_item_not_applicable(item):
213
+ return _degraded_decision(
214
+ _DEGRADED_NOT_APPLICABLE,
215
+ f"不适用:{detail or '探针已按项目形态剪枝'}",
216
+ {
217
+ "source": "probe_applicability",
218
+ "name": name,
219
+ "status": _DEGRADED_NOT_APPLICABLE,
220
+ },
221
+ )
222
+ if _degraded_item_advisory(item):
223
+ return _degraded_decision(
224
+ _DEGRADED_NOT_APPLICABLE,
225
+ f"不阻断:建议性探针未就绪({detail or '无详情'})",
226
+ {
227
+ "source": "probe_advisory",
228
+ "name": name,
229
+ "status": _DEGRADED_NOT_APPLICABLE,
230
+ "probe": item.get("probe", ""),
231
+ },
232
+ )
233
+ if _degraded_item_transient(item) and not _degraded_item_critical(item):
234
+ return _degraded_decision(
235
+ _DEGRADED_TRANSIENT,
236
+ f"瞬态降级:本次探测超时({detail or '无详情'})",
237
+ {
238
+ "source": "probe_transient",
239
+ "name": name,
240
+ "status": _DEGRADED_TRANSIENT,
241
+ "probe": item.get("probe", ""),
242
+ },
243
+ )
244
+ return None
245
+
246
+
247
+ def degraded_receipt_for_report(report: self_heal.HealReport | None) -> dict[str, Any] | None:
248
+ if report is None:
249
+ return None
250
+ try:
251
+ return report.as_dict()
252
+ except (AttributeError, TypeError, ValueError):
253
+ return {"status": "unserializable", "attempts": len(report.attempts)}
254
+
255
+
256
+ def report_self_heal(report: self_heal.HealReport) -> None:
257
+ """打印穷尽自愈的处置清单,并留存供门禁在阻断时一并展示(DOC-236 C2)。"""
258
+ global _LAST_SELF_HEAL_REPORT
259
+ _LAST_SELF_HEAL_REPORT = report
260
+ print(f"[launch_bugx] 穷尽自愈未能补齐(已试 {len(report.attempts)} 个方案):")
261
+ for line in self_heal.escalation_lines(report):
262
+ print(f"[launch_bugx] {line}")
263
+
264
+
265
+ def emit_self_heal_evidence() -> None:
266
+ """阻断时向人展示本轮已试过的自愈方案与失败原因(穷尽后上报)。"""
267
+ report = _LAST_SELF_HEAL_REPORT
268
+ if report is None or not report.attempts:
269
+ return
270
+ print(" 已尝试的自愈方案(穷尽后上报):")
271
+ for line in self_heal.escalation_lines(report):
272
+ print(f" {line}")
273
+
274
+
275
+ def preflight_probe_id(item: dict) -> str:
276
+ raw = str(item.get("name", "")).strip().casefold().split("/", 1)[0]
277
+ normalized = raw.replace("_", "-")
278
+ return "codebase-memory" if normalized == "codebase-memory-mcp" else normalized
279
+
280
+
281
+ def auto_provision_accelerators(
282
+ root: Path,
283
+ degraded: list[dict],
284
+ *,
285
+ required_tools: set[str] | None = None,
286
+ ) -> tuple[list[dict], list[str]]:
287
+ """尝试自动装配/就绪缺失的环境加速器(DOC-155 满血自治就绪)。
288
+
289
+ 针对未建立索引的 codebase-memory-mcp 等本地已安装工具,在自治启动前
290
+ 自动触发就绪命令,而不是消极降级关闭。返回 (未能自动补齐的剩余降级项, 已成功就绪说明列表)。
291
+ """
292
+ if os.environ.get("BUGX_AUTO_PROVISION", "1").strip() in ("0", "false", "no"):
293
+ return degraded, []
294
+
295
+ remaining: list[dict] = []
296
+ provisioned: list[str] = []
297
+
298
+ selected_tools = {
299
+ "codebase-memory" if str(value).strip().casefold().replace("_", "-")
300
+ == "codebase-memory-mcp" else str(value).strip().casefold().replace("_", "-")
301
+ for value in (required_tools or set())
302
+ }
303
+
304
+ for item in degraded:
305
+ name = str(item.get("name", "")).strip().casefold()
306
+ detail = str(item.get("detail", ""))
307
+ probe_id = _preflight_probe_id(item)
308
+ if required_tools is not None and probe_id not in selected_tools \
309
+ and "supervisor" not in probe_id:
310
+ remaining.append(item)
311
+ continue
312
+
313
+ # 1. codebase-memory-mcp 自动安装与自动建索引
314
+ if probe_id == "codebase-memory":
315
+ try:
316
+ from core.probes import codebase_memory_probe
317
+
318
+ probe_report = codebase_memory_probe.inspect(root)
319
+ failed_checks = [
320
+ check for check in probe_report.get("checks", [])
321
+ if isinstance(check, dict) and check.get("ok") is False
322
+ ] if isinstance(probe_report, dict) else []
323
+ runtime_mismatch = any(
324
+ check.get("name") in {"binary", "validated_version", "supported_version"}
325
+ for check in failed_checks
326
+ )
327
+ if isinstance(probe_report, dict) and probe_report.get("status") == "READY":
328
+ msg = f"✓ {item.get('name')} 已由统一探针复核就绪"
329
+ print(f"[launch_bugx] {msg}")
330
+ provisioned.append(msg)
331
+ os.environ["BUGX_USE_CODEBASE_MEMORY"] = "1"
332
+ continue
333
+
334
+ if runtime_mismatch:
335
+ print(
336
+ f"[launch_bugx] {item.get('name')} 缺少固定版本,"
337
+ "启动隔离安装自愈并按固定版本复核..."
338
+ )
339
+ healed, heal_report = self_heal.heal_tool(
340
+ "codebase-memory", detail=detail, root=root,
341
+ )
342
+ if not healed:
343
+ _report_self_heal(heal_report)
344
+ else:
345
+ # Installation success is not accelerator readiness: run
346
+ # the full version and project-index probe again.
347
+ probe_report = codebase_memory_probe.inspect(root)
348
+ if isinstance(probe_report, dict) \
349
+ and probe_report.get("status") == "READY":
350
+ msg = f"✓ {item.get('name')} 自愈后由统一探针复核就绪"
351
+ print(f"[launch_bugx] {msg}")
352
+ provisioned.append(msg)
353
+ os.environ["BUGX_USE_CODEBASE_MEMORY"] = "1"
354
+ continue
355
+ failed_checks = [
356
+ check for check in probe_report.get("checks", [])
357
+ if isinstance(check, dict) and check.get("ok") is False
358
+ ] if isinstance(probe_report, dict) else []
359
+
360
+ check_names = [str(check.get("name", "unknown")) for check in failed_checks]
361
+ if not runtime_mismatch:
362
+ check_names.extend(
363
+ str(check.get("name", "unknown"))
364
+ for check in probe_report.get("checks", [])
365
+ if isinstance(check, dict) and check.get("ok") is False
366
+ )
367
+ failed = ", ".join(list(dict.fromkeys(check_names))[:4]) or str(
368
+ probe_report.get("status", "invalid-report")
369
+ if isinstance(probe_report, dict) else "invalid-report"
370
+ )
371
+ print(
372
+ f"[launch_bugx] Codebase Memory 复核未 READY({failed}),保留降级选项"
373
+ )
374
+ except Exception as exc:
375
+ print(
376
+ "[launch_bugx] Codebase Memory 自愈/复核异常 "
377
+ f"({type(exc).__name__}),保留降级选项"
378
+ )
379
+
380
+ # 2. bugx-supervisor / 宿主 MCP 自动就地配置注入
381
+ if "supervisor" in probe_id or "bugx-supervisor" in probe_id:
382
+ try:
383
+ from bugx_cli.commands.plugin import write_host_mcp_config
384
+ from core.supervisor import supervisor_host
385
+ adapter = supervisor_host.detect_host(root)
386
+ if adapter and host_registry.host_mcp_writable(adapter.name):
387
+ print(f"[launch_bugx] 发现宿主 {adapter.name} 缺失 supervisor MCP 配置,正在就地自愈注入...")
388
+ st, _, _, _ = write_host_mcp_config(root, adapter.name)
389
+ if st in {"configured", "created", "updated", "unchanged"}:
390
+ msg = f"✓ 宿主 {adapter.name} supervisor MCP 配置已自动就地自愈注入"
391
+ print(f"[launch_bugx] {msg}")
392
+ provisioned.append(msg)
393
+ continue
394
+ except Exception as exc:
395
+ print(f"[launch_bugx] 自动注入 supervisor MCP 配置异常: {exc}")
396
+
397
+ # 3. 修复 SAST 工具只通过 self_heal 的固定 package spec 与复核器。
398
+ if probe_id in {"sast", "bandit", "semgrep"}:
399
+ try:
400
+ from core.runtime import project_profile
401
+ from core.probes import sast_probe
402
+ profile = project_profile.detect_project_profile(root)
403
+ languages = {str(lang).casefold() for lang in profile.get("languages", [])}
404
+ targets = list(PROBE_REPAIR_TARGETS.get(probe_id, ()))
405
+ if probe_id == "sast" and "python" not in languages:
406
+ targets = [tool for tool in targets if tool != "bandit"]
407
+
408
+ satisfied = False
409
+ for target in targets:
410
+ status = sast_probe.check_tool(target)
411
+ if status.get("ok"):
412
+ satisfied = True
413
+ if probe_id != "sast":
414
+ break
415
+ continue
416
+ healed, heal_report = self_heal.heal_tool(
417
+ target, detail=detail, root=root,
418
+ )
419
+ sast_probe.clear_tool_probe_cache()
420
+ status = sast_probe.check_tool(target)
421
+ if healed and status.get("ok"):
422
+ msg = (
423
+ f"✓ {target} 已由受信隔离配方安装并通过精确版本复核"
424
+ )
425
+ print(f"[launch_bugx] {msg}")
426
+ provisioned.append(msg)
427
+ satisfied = True
428
+ if probe_id != "sast":
429
+ break
430
+ else:
431
+ _report_self_heal(heal_report)
432
+
433
+ if probe_id == "sast" and not satisfied:
434
+ satisfied = sast_probe.inspect(root).get("status") == "READY"
435
+ if satisfied:
436
+ continue
437
+ except Exception as exc:
438
+ print(f"[launch_bugx] SAST 外部工具自愈/复核异常 ({type(exc).__name__})")
439
+
440
+ # 4. 效率探针仅对已登记的 ast-grep 加速器运行隔离自愈。
441
+ if probe_id in {"efficiency", "ast-grep"}:
442
+ from core.probes import efficiency_probe
443
+ status = efficiency_probe._command(("ast-grep", "sg"), "ast-grep")
444
+ if not status.get("ok"):
445
+ healed, heal_report = self_heal.heal_tool(
446
+ "ast-grep", detail=detail, root=root,
447
+ )
448
+ status = efficiency_probe._command(("ast-grep", "sg"), "ast-grep")
449
+ if healed and status.get("ok"):
450
+ provisioned.extend(heal_report.healed)
451
+ else:
452
+ _report_self_heal(heal_report)
453
+ if probe_id == "ast-grep" and status.get("ok"):
454
+ continue
455
+ if probe_id == "efficiency" and efficiency_probe.inspect(root).get("status") == "READY":
456
+ continue
457
+
458
+ remaining.append(item)
459
+
460
+ return remaining, provisioned
461
+
462
+
463
+ def autonomous_degraded_choices(
464
+ degraded: list[dict],
465
+ ) -> dict[str, _DegradedDecision]:
466
+ """Classify every autonomous item before the shared gate.
467
+
468
+ Autonomous mode has no user to authorize a missing capability. A fallback
469
+ option in a probe's display text is therefore never sufficient; only an
470
+ explicit probe applicability result or a non-critical project exemption
471
+ may produce an allowed decision. Every other item receives an explicit
472
+ blocked decision so the caller must route the complete set through the
473
+ shared gate and cannot accidentally record part of it and continue.
474
+ """
475
+ choices: dict[str, _DegradedDecision] = {}
476
+ exemptions = _tooling_exemptions()
477
+ for item in degraded:
478
+ name = str(item.get("name", "unknown"))
479
+ policy_decision = _degraded_decision_for_policy(item)
480
+ if policy_decision is not None:
481
+ # 形态不适用 / 建议性探针 / 瞬态超时:注册表机器结论已足够,
482
+ # 但决策与收据必须留痕(不得静默放行)。
483
+ choices[name] = policy_decision
484
+ continue
485
+ is_critical = _degraded_item_critical(item)
486
+ exempted = _degraded_exemption_hit(name, exemptions)
487
+ if exempted and not is_critical:
488
+ choices[name] = _degraded_decision(
489
+ _DEGRADED_EXEMPTED,
490
+ "显式豁免(config.json tooling_exemptions)",
491
+ {
492
+ "source": "project_config",
493
+ "name": name,
494
+ "status": _DEGRADED_EXEMPTED,
495
+ },
496
+ )
497
+ continue
498
+ # No fallback option, display text, or critical exemption is enough
499
+ # to let autonomous startup proceed; classify it for the shared gate.
500
+ if is_critical and exempted:
501
+ print(f"[launch_bugx] ✗ critical MCP/工具 {name} 不得豁免,自治启动阻断")
502
+ reason = "critical_capability_cannot_be_exempted"
503
+ else:
504
+ reason = "autonomous_decision_required"
505
+ choices[name] = _degraded_decision(
506
+ _DEGRADED_BLOCKED,
507
+ "阻断:自治模式未取得真实自愈/非适用/豁免结论",
508
+ {
509
+ "source": "autonomous_classification",
510
+ "name": name,
511
+ "attempted": False,
512
+ "reason": reason,
513
+ },
514
+ )
515
+ return choices
516
+
517
+ def watchlist_error_report(exc: Exception) -> dict[str, Any]:
518
+ """Return and report a sanitized Watchlist failure without hiding its state."""
519
+ error_type = type(exc).__name__
520
+ if not error_type.isascii() or not error_type.isidentifier() or len(error_type) > 64:
521
+ error_type = "Exception"
522
+ print(
523
+ "⚠ [BugX 回归看护] 巡查不可用 "
524
+ f"(status=ERROR, error_type={error_type});可检查账本后运行 "
525
+ "fix_watchlist.py check --root <项目根> --json。"
526
+ )
527
+ return {
528
+ "status": "ERROR",
529
+ "possible_regressions": 0,
530
+ "inconclusive": 0,
531
+ "error_type": error_type,
532
+ }
533
+
534
+
535
+ def safe_watchlist_incident_id(value: object) -> str:
536
+ text = str(value or "")
537
+ if (
538
+ len(text) == 14 and text.startswith("I-")
539
+ and all(char in "0123456789abcdef" for char in text[2:])
540
+ ):
541
+ return text
542
+ return "invalid-id"
543
+
544
+
545
+ def check_fix_regressions(root: Path | None = None) -> dict:
546
+ """巡查近期已修复代码片段,并显式报告回归、不可判定和巡查错误。"""
547
+ try:
548
+ proj_root = (root or resolve_project_root()).resolve()
549
+ ledger_file = proj_root / ".bugx" / "knowledge" / "lesson-ledger.json"
550
+ if not ledger_file.is_file():
551
+ return {"status": "NO_LEDGER", "possible_regressions": 0, "inconclusive": 0}
552
+
553
+ from core.repair import fix_watchlist
554
+ report = fix_watchlist.check(ledger_file, proj_root, limit=20)
555
+ if not isinstance(report, dict):
556
+ raise TypeError("Watchlist report must be an object")
557
+ report = dict(report)
558
+ report["status"] = "COMPLETED"
559
+ possible = report.get("possible_regressions", 0)
560
+ inconclusive = report.get("inconclusive", 0)
561
+ possible = possible if isinstance(possible, int) and not isinstance(possible, bool) else 0
562
+ inconclusive = (
563
+ inconclusive
564
+ if isinstance(inconclusive, int) and not isinstance(inconclusive, bool)
565
+ else 0
566
+ )
567
+ if possible > 0 or inconclusive > 0:
568
+ print(
569
+ "[BugX 回归看护] 巡查完成:"
570
+ f"incidents={report.get('incidents_watched', 0)},"
571
+ f"intact={report.get('intact', 0)},"
572
+ f"possible-regression={possible},inconclusive={inconclusive}。"
573
+ )
574
+ for entry in report.get("entries", []):
575
+ if not isinstance(entry, dict):
576
+ continue
577
+ status = entry.get("status")
578
+ if status not in {"possible-regression", "inconclusive", "skipped"}:
579
+ continue
580
+ incident_id = _safe_watchlist_incident_id(entry.get("incident_id"))
581
+ reason_code = entry.get("reason_code")
582
+ if not isinstance(reason_code, str) or not reason_code.isascii() \
583
+ or not reason_code.replace("_", "").isalnum():
584
+ reason_code = "none"
585
+ print(
586
+ f" • Incident {incident_id}: {status}, "
587
+ f"reason_code={reason_code}"
588
+ )
589
+ if possible > 0:
590
+ print(" → possible-regression 是片段级 advisory,需按 Incident 核验;不会自动阻断 post。")
591
+ if inconclusive > 0:
592
+ print(" → inconclusive 表示证据不足;先处理原因码,再重新巡查。")
593
+ return report
594
+ except Exception as exc:
595
+ return _watchlist_error_report(exc)
596
+
597
+
598
+ def _sync_codebase_memory_env(profile: dict) -> None:
599
+ """把 codebase-memory 探针结论同步到进程环境变量。"""
600
+ cb_probe = (profile.get("probes") or {}).get("codebase-memory")
601
+ if isinstance(cb_probe, dict):
602
+ os.environ["BUGX_USE_CODEBASE_MEMORY"] = (
603
+ "1" if cb_probe.get("status") == "READY" else "0"
604
+ )
605
+
606
+
607
+ def report_degraded_probes(*, refresh: bool = False,
608
+ degraded: list[dict] | None = None) -> list[dict]:
609
+ """收集并显式汇报探针 DEGRADED 项;返回降级动作清单供写入准备记录。
610
+
611
+ ``degraded`` 允许由 :func:`run_preflight_probes` 预计算后传入,这样同一
612
+ 次 ``pre()`` 只需执行一轮探针(PERF-09/DES-13),不会重复扇出子进程。
613
+ """
614
+ if degraded is None:
615
+ from core.probes import probe_registry
616
+ profile = probe_registry.run_preflight_probes(
617
+ resolve_project_root(), parallel=True, refresh=refresh,
618
+ )
619
+ degraded = list(profile.get("degraded_actions", []))
620
+
621
+ # 同步环境变量
622
+ _sync_codebase_memory_env(profile)
623
+
624
+ # 启动前主动触发修复代码看护巡查
625
+ check_fix_regressions(resolve_project_root())
626
+
627
+ if not degraded:
628
+ return []
629
+ print()
630
+ print("⚠ 环境加速器降级告警(启动前必须取得用户处置决定)")
631
+ for item in degraded:
632
+ print(f" ✗ {item['name']}: {item['detail']}")
633
+ for option in item.get("options", []):
634
+ print(f" · {option}")
635
+ print(" → 发现 MCP 未安装/未配置时,下一步立即弹出交互选择;无终端时停止启动,"
636
+ "不会静默进入后续审计。")
637
+ print()
638
+ return degraded
639
+
640
+ def record_degraded_choices(
641
+ degraded: list[dict], choices: Mapping[str, object],
642
+ ) -> None:
643
+ """把降级项与用户选择追加写入准备记录(存在才写,不代用户创建)。
644
+
645
+ **DOC-004 Engine-State Separation**:运行时记录**绝不**写进引擎目录。
646
+ 实测污染:旧实现回落到 ``AGENT_DIR / "prep-record.md"``,导致运行/测试把
647
+ "环境加速器降级处置" 段追加进引擎自带的协议资产(``core/prep-record.md``)。
648
+ 现在只写项目态记录;解析失败或目标落在引擎目录内 ⇒ 直接跳过(不创建、不改写)。
649
+ """
650
+ if not degraded:
651
+ return
652
+ try:
653
+ record = bugx_paths.require(resolve_project_root()).prep_record
654
+ except (OSError, ValueError, RuntimeError):
655
+ # 项目布局缺失/不安全(LayoutError 继承 RuntimeError)⇒ 不写、不创建。
656
+ return
657
+ try:
658
+ record.resolve().relative_to(AGENT_DIR.resolve())
659
+ except ValueError:
660
+ pass
661
+ else:
662
+ print("[pre] 跳过降级记录写入:目标位于引擎目录(Engine-State Separation)")
663
+ return
664
+ if not record.is_file():
665
+ return
666
+ heading = "## 环境加速器降级处置(pre 自动记录)"
667
+ lines = [heading]
668
+ for item in degraded:
669
+ choice = choices.get(item["name"], "未选择")
670
+ if isinstance(choice, _DegradedDecision):
671
+ receipt = json.dumps(
672
+ choice.receipt, ensure_ascii=False, sort_keys=True, default=str,
673
+ )
674
+ rendered = f"{choice} [status={choice.status}; receipt={receipt}]"
675
+ else:
676
+ rendered = str(choice)
677
+ lines.append(f"- {item['name']}: {item['detail']} → 用户选择:{rendered}")
678
+ try:
679
+ existing = record.read_text(encoding="utf-8")
680
+ block = "\n".join(lines)
681
+ if heading in existing:
682
+ start = existing.index(heading)
683
+ end = existing.find("\n## ", start + len(heading))
684
+ if end < 0:
685
+ end = len(existing)
686
+ existing = existing[:start].rstrip() + "\n\n" + block + existing[end:]
687
+ else:
688
+ existing = existing.rstrip() + "\n\n" + block + "\n"
689
+ record.write_text(existing, encoding="utf-8")
690
+ except OSError:
691
+ pass
692
+
693
+ def degraded_install(item: dict) -> _DegradedDecision:
694
+ """Attempt one bounded provisioning action and fail closed on uncertainty.
695
+
696
+ A missing unified installer, a failed installer, or an unverified result is
697
+ a blocked decision. The returned receipt carries the actual attempt and
698
+ any self-heal report; it is never converted into a fallback success.
699
+ """
700
+ global _LAST_SELF_HEAL_REPORT
701
+ previous_report = _LAST_SELF_HEAL_REPORT
702
+ name = str(item.get("name", "未命名工具"))
703
+ receipt: dict[str, Any] = {
704
+ "action": "auto_provision_accelerators",
705
+ "name": name,
706
+ "attempted": True,
707
+ "provisioned": [],
708
+ "remaining": [name],
709
+ }
710
+ try:
711
+ remaining, provisioned = _auto_provision_accelerators(resolve_project_root(), [item])
712
+ receipt["provisioned"] = list(provisioned)
713
+ receipt["remaining"] = [
714
+ str(entry.get("name", "unknown"))
715
+ for entry in remaining
716
+ if isinstance(entry, Mapping)
717
+ ]
718
+ current_report = _LAST_SELF_HEAL_REPORT
719
+ if provisioned and not remaining:
720
+ return _degraded_decision(
721
+ _DEGRADED_HEALED,
722
+ "✓ 自动就地自愈安装就绪",
723
+ receipt,
724
+ )
725
+ if current_report is not None and current_report is not previous_report:
726
+ receipt["self_heal"] = _degraded_receipt_for_report(current_report)
727
+ except Exception as exc:
728
+ receipt["exception"] = f"{type(exc).__name__}: {exc}"
729
+ print(f" [launch_bugx] 自动装配尝试异常: {exc}")
730
+
731
+ print(
732
+ f" [launch_bugx] ✗ 工具 {name} 未完成自动装配;本轮启动阻断,"
733
+ "请完成配置后重试。"
734
+ )
735
+ return _degraded_decision(
736
+ _DEGRADED_BLOCKED,
737
+ "阻断:自动装配未完成(真实尝试收据已记录)",
738
+ receipt,
739
+ )
740
+
741
+ def prompt_degraded_choices(
742
+ degraded: list[dict],
743
+ explicit_choices: dict[str, str] | None = None,
744
+ ) -> dict[str, _DegradedDecision]:
745
+ """Ask for a bounded action; skip/defer always remains blocked."""
746
+ choices: dict[str, _DegradedDecision] = {}
747
+ if not degraded:
748
+ return choices
749
+
750
+ combined_explicit: dict[str, str] = dict(explicit_choices or {})
751
+ # [BEGIN DEV_ONLY: FAST_VERIFICATION_TOOLING]
752
+ from core.runtime.interaction import try_get_preset_runtime_config
753
+ if try_get_preset_runtime_config is not None:
754
+ preset_cfg = try_get_preset_runtime_config(resolve_project_root() if uses_project_layout() else None)
755
+ if preset_cfg.get("auto_install_tools") or preset_cfg.get("missing_tools_action") == "install":
756
+ for item in degraded:
757
+ name = str(item.get("name", "unknown"))
758
+ if name not in combined_explicit:
759
+ combined_explicit[name] = "install"
760
+ elif preset_cfg.get("missing_tools_action") in {"skip", "fallback"}:
761
+ for item in degraded:
762
+ name = str(item.get("name", "unknown"))
763
+ if name not in combined_explicit:
764
+ combined_explicit[name] = "defer"
765
+ # [END DEV_ONLY: FAST_VERIFICATION_TOOLING]
766
+ env_choices = os.environ.get("BUGX_TOOLING_CHOICES", "")
767
+ if env_choices:
768
+ for part in env_choices.split(","):
769
+ if "=" in part:
770
+ k, v = part.split("=", 1)
771
+ if k.strip() not in combined_explicit:
772
+ combined_explicit[k.strip()] = v.strip()
773
+
774
+ # A non-interactive host cannot silently authorize a missing capability.
775
+ # It receives a durable blocked decision instead of an implicit fallback.
776
+ is_interactive = False
777
+ try:
778
+ is_interactive = bool(sys.stdin.isatty())
779
+ except (OSError, AttributeError):
780
+ pass
781
+
782
+ exemptions = _tooling_exemptions()
783
+
784
+ pending: list[dict] = []
785
+ for item in degraded:
786
+ name = str(item.get("name", "unknown"))
787
+ detail = str(item.get("detail", ""))
788
+ is_mcp = item.get("kind") == "mcp" or "mcp" in name.casefold()
789
+
790
+ # DOC-236 C1:项目 ``config.json`` 的显式豁免是唯一放行通道,且必须与
791
+ # 自治路径同源生效。非 critical 能力被显式豁免 ⇒ 留痕放行,
792
+ # 不再落进「非交互环境未取得决策」的阻断分支。
793
+ if _degraded_exemption_hit(name, exemptions) and not _degraded_item_critical(item):
794
+ choices[name] = _degraded_decision(
795
+ _DEGRADED_EXEMPTED,
796
+ "显式豁免(config.json tooling_exemptions)",
797
+ {
798
+ "source": "project_config",
799
+ "name": name,
800
+ "status": _DEGRADED_EXEMPTED,
801
+ "probe": item.get("probe", ""),
802
+ },
803
+ )
804
+ continue
805
+
806
+ if _degraded_item_not_applicable(item):
807
+ choices[name] = _degraded_decision(
808
+ _DEGRADED_NOT_APPLICABLE,
809
+ f"不适用:{detail or '探针已按项目形态剪枝'}",
810
+ {
811
+ "source": "probe_applicability",
812
+ "name": name,
813
+ "status": _DEGRADED_NOT_APPLICABLE,
814
+ },
815
+ )
816
+ continue
817
+
818
+ # 建议性探针 / 瞬态超时:注册表已机器判定这两种情形不构成启动阻断。
819
+ # 它们仍然留痕(决策 + 收据 + 控制台告警),不是静默降级。
820
+ if _degraded_item_advisory(item):
821
+ choices[name] = _degraded_decision(
822
+ _DEGRADED_NOT_APPLICABLE,
823
+ f"不阻断:建议性探针未就绪({detail or '无详情'})",
824
+ {
825
+ "source": "probe_advisory",
826
+ "name": name,
827
+ "status": _DEGRADED_NOT_APPLICABLE,
828
+ "probe": item.get("probe", ""),
829
+ },
830
+ )
831
+ print(
832
+ f"[launch_bugx] ⚠ 建议性探针 {name} 未就绪,按注册表策略不阻断启动(已记录)"
833
+ )
834
+ continue
835
+ if _degraded_item_transient(item) and not _degraded_item_critical(item):
836
+ choices[name] = _degraded_decision(
837
+ _DEGRADED_TRANSIENT,
838
+ f"瞬态降级:本次探测超时({detail or '无详情'})",
839
+ {
840
+ "source": "probe_transient",
841
+ "name": name,
842
+ "status": _DEGRADED_TRANSIENT,
843
+ "probe": item.get("probe", ""),
844
+ },
845
+ )
846
+ print(
847
+ f"[launch_bugx] ⚠ {name} 本次探测超时(非未安装),"
848
+ "按瞬态降级继续,本轮走内置回退(已记录)"
849
+ )
850
+ continue
851
+
852
+ # 非交互环境且未显式指定选择时,明确阻断而不是自动采纳回退
853
+ if not is_interactive and name not in combined_explicit and not any(k.casefold() == name.casefold() for k in combined_explicit):
854
+ choices[name] = _degraded_decision(
855
+ _DEGRADED_BLOCKED,
856
+ "阻断:非交互环境未取得安装/配置决策",
857
+ {
858
+ "source": "noninteractive",
859
+ "name": name,
860
+ "attempted": False,
861
+ "reason": "decision_required",
862
+ },
863
+ )
864
+ print(f"[launch_bugx] ✗ 非交互环境未取得加速器 {name} 的安装/配置决策,启动阻断")
865
+ continue
866
+
867
+ explicit_action = None
868
+ for k, v in combined_explicit.items():
869
+ if k.casefold() == name.casefold():
870
+ explicit_action = v.strip().lower()
871
+ break
872
+ if explicit_action is not None:
873
+ if explicit_action in {"skip", "fallback", "2"}:
874
+ choices[name] = _degraded_decision(
875
+ _DEGRADED_BLOCKED,
876
+ "阻断:跳过/回退不会放行本轮启动",
877
+ {
878
+ "source": "explicit_choice",
879
+ "name": name,
880
+ "attempted": False,
881
+ "reason": "fallback_not_authorized",
882
+ },
883
+ )
884
+ elif explicit_action in {"defer", "later", "next", "3"}:
885
+ choices[name] = _degraded_decision(
886
+ _DEGRADED_DEFERRED,
887
+ "下次再说(停止本轮启动)",
888
+ {
889
+ "source": "explicit_choice",
890
+ "name": name,
891
+ "attempted": False,
892
+ "reason": "deferred_by_user",
893
+ },
894
+ )
895
+ elif explicit_action in {"install", "config", "1"}:
896
+ choices[name] = _degraded_install(item)
897
+ else:
898
+ choices[name] = _degraded_decision(
899
+ _DEGRADED_BLOCKED,
900
+ f"阻断:未知降级处置 {explicit_action}",
901
+ {
902
+ "source": "explicit_choice",
903
+ "name": name,
904
+ "attempted": False,
905
+ "reason": "unknown_choice",
906
+ },
907
+ )
908
+ continue
909
+
910
+ pending.append(item)
911
+
912
+ if not pending:
913
+ return choices
914
+
915
+ if len(pending) > 1:
916
+ # 同名多实例合并:同一探针名可能产出多条降级项(如 web_conformance
917
+ # 的 5 个实例),若逐条出选项会出现完全同名同描述、用户无法区分的
918
+ # 重复项。按名称去重成组,单条选项代表该名称的全部实例,并标注计数。
919
+ groups: dict[str, list[dict]] = {}
920
+ for item in pending:
921
+ groups.setdefault(str(item.get("name", "unknown")), []).append(item)
922
+ options = []
923
+ for group_name, instances in groups.items():
924
+ label = (
925
+ group_name if len(instances) == 1
926
+ else f"{group_name}({len(instances)} 个探针实例)"
927
+ )
928
+ is_auto = any(
929
+ any(k in str(item.get("name", "")).casefold() for k in ("codebase-memory", "supervisor", "sast", "bandit", "semgrep", "ast-grep"))
930
+ for item in instances
931
+ )
932
+ tag = "[支持自动装配]" if is_auto else "[无自动安装器,选择将启用内置回退]"
933
+ details: list[str] = []
934
+ for item in instances:
935
+ detail = str(item.get("detail") or "").strip()
936
+ if detail and detail not in details:
937
+ details.append(detail)
938
+ desc = ";".join(details) if details else "本轮选择安装/配置该工具"
939
+ options.append((
940
+ label,
941
+ f"{tag} {desc}",
942
+ ))
943
+ result = ask_interaction(
944
+ "tooling:batch",
945
+ "请勾选本轮要安装/配置的工具(留空表示全部阻断本轮启动;"
946
+ "同名多个探针实例已合并为一条,勾选即对该名称的全部实例生效)。"
947
+ "也可不经交互:设置环境变量 BUGX_TOOLING_CHOICES=name=install|defer",
948
+ options,
949
+ phase="tooling", detail="未勾选的工具本轮阻断启动",
950
+ default=0, multiple=True, emit_request=True,
951
+ )
952
+ values = answered_values(result)
953
+ if values is None:
954
+ return choices
955
+ selected = set(values)
956
+ for index, (group_name, instances) in enumerate(groups.items(), 1):
957
+ chosen = (
958
+ _degraded_install(instances[0]) if str(index) in selected
959
+ else _degraded_decision(
960
+ _DEGRADED_BLOCKED,
961
+ "阻断:批量未勾选,不会启用回退方案",
962
+ {
963
+ "source": "batch_selection",
964
+ "name": group_name,
965
+ "attempted": False,
966
+ "reason": "not_selected",
967
+ },
968
+ )
969
+ )
970
+ choices[group_name] = chosen
971
+ return choices
972
+
973
+ for item in pending:
974
+ name = str(item.get("name", "unknown"))
975
+ detail = str(item.get("detail", ""))
976
+ is_mcp = item.get("kind") == "mcp" or "mcp" in name.casefold()
977
+
978
+ options = [
979
+ ("立即安装/配置", "完成该工具配置后重新探测"),
980
+ ("停止本轮启动", "未完成配置不得以回退方案放行"),
981
+ ]
982
+ if is_mcp:
983
+ options.append(("下次再说", "停止本轮启动,稍后重新处理该 MCP"))
984
+ result = ask_interaction(
985
+ f"tooling:{name}", f"工具 {name} 未就绪,选择本轮处置方式", options,
986
+ phase="tooling", detail=detail, default=0, emit_request=True,
987
+ )
988
+ value = answered_value(result)
989
+ if value is None:
990
+ return choices
991
+ if value == "2":
992
+ choices[name] = _degraded_decision(
993
+ _DEGRADED_DEFERRED,
994
+ "下次再说(停止本轮启动)",
995
+ {
996
+ "source": "interactive_choice",
997
+ "name": name,
998
+ "attempted": False,
999
+ "reason": "deferred_by_user",
1000
+ },
1001
+ )
1002
+ elif value == "3" and is_mcp:
1003
+ choices[name] = _degraded_decision(
1004
+ _DEGRADED_DEFERRED,
1005
+ "下次再说(停止本轮启动)",
1006
+ {
1007
+ "source": "interactive_choice",
1008
+ "name": name,
1009
+ "attempted": False,
1010
+ "reason": "deferred_by_user",
1011
+ },
1012
+ )
1013
+ elif value == "1":
1014
+ choices[name] = _degraded_install(item)
1015
+ else:
1016
+ return choices
1017
+ return choices
1018
+
1019
+ def tooling_exemptions() -> set[str]:
1020
+ """DOC-236 C1:显式豁免通道(``config.json`` 的 ``tooling_exemptions``)。
1021
+
1022
+ 取消"可选件自动回退放行"后,无安装器的专有工具会阻断启动;唯一放行方式是
1023
+ **项目配置里显式列出名称**(可审计、可追溯),而不是命令行开关或静默降级。
1024
+ 读取失败/类型不符一律返回空集(fail-closed)。
1025
+
1026
+ 注意:这里**只**要求 ``<root>/.bugx/config.json`` 这个普通文件本身可读,
1027
+ 不再要求完整的 lifecycle 布局(``bugx_paths.require``)。否则在尚未
1028
+ ``init`` 完整布局的工作区里,阻断提示让用户去写 ``tooling_exemptions``,
1029
+ 而读取端却拒绝读同一份文件——形成无法自救的死锁。
1030
+ """
1031
+ names: set[str] = set()
1032
+ try:
1033
+ cfg = _resolve_project_root() / ".bugx" / "config.json"
1034
+ if not cfg.is_file() or cfg.is_symlink() or cfg.stat().st_size > 64 * 1024:
1035
+ return names
1036
+ payload = json.loads(cfg.read_text(encoding="utf-8"))
1037
+ except (OSError, ValueError):
1038
+ return names
1039
+ raw = payload.get("tooling_exemptions") if isinstance(payload, dict) else None
1040
+ if isinstance(raw, list):
1041
+ names = {
1042
+ str(item).strip().casefold()
1043
+ for item in raw
1044
+ if isinstance(item, str) and str(item).strip()
1045
+ }
1046
+ return names
1047
+
1048
+
1049
+ def degraded_gate(
1050
+ degraded: list[dict],
1051
+ explicit_choices: Mapping[str, object] | None = None,
1052
+ ) -> bool:
1053
+ """Require a machine-valid disposition for every degraded item.
1054
+
1055
+ Human-readable choice text is intentionally never parsed here. Values
1056
+ returned by older callers or test doubles are treated as blocked unless a
1057
+ non-critical item is explicitly exempted in project configuration.
1058
+ """
1059
+ if not degraded:
1060
+ return True
1061
+ try:
1062
+ structured = bool(explicit_choices) and all(
1063
+ isinstance(value, _DegradedDecision)
1064
+ for value in explicit_choices.values()
1065
+ )
1066
+ if structured:
1067
+ choices: Mapping[str, object] = dict(explicit_choices)
1068
+ else:
1069
+ raw_choices = (
1070
+ {str(key): str(value) for key, value in explicit_choices.items()}
1071
+ if explicit_choices is not None else None
1072
+ )
1073
+ choices = _prompt_degraded_choices(degraded, explicit_choices=raw_choices)
1074
+ except Exception as exc: # noqa: BLE001
1075
+ print(f"启动前降级项询问失败,不能自动继续: {exc}")
1076
+ return False
1077
+ names = {str(item.get("name", "unknown")) for item in degraded}
1078
+ missing = sorted(names - set(choices))
1079
+ if missing:
1080
+ print("启动前仍有降级项未取得用户决策,不能自动继续: " + ", ".join(missing))
1081
+ _record_degraded_choices(degraded, choices)
1082
+ return False
1083
+ exemptions = _tooling_exemptions()
1084
+ normalized: dict[str, object] = dict(choices)
1085
+ real_blockers: list[str] = []
1086
+ deferred: list[str] = []
1087
+ for item in degraded:
1088
+ name = str(item.get("name", ""))
1089
+ choice = choices.get(name)
1090
+ is_typed_decision = (
1091
+ isinstance(choice, _DegradedDecision)
1092
+ and choice.status in {
1093
+ _DEGRADED_HEALED,
1094
+ _DEGRADED_NOT_APPLICABLE,
1095
+ _DEGRADED_EXEMPTED,
1096
+ _DEGRADED_BLOCKED,
1097
+ _DEGRADED_DEFERRED,
1098
+ _DEGRADED_TRANSIENT,
1099
+ }
1100
+ and isinstance(choice.receipt, dict)
1101
+ )
1102
+ status = choice.status if is_typed_decision else None
1103
+ is_critical = _degraded_item_critical(item)
1104
+ exempted = _degraded_exemption_hit(name, exemptions)
1105
+ if "codebase-memory" in name.casefold() and status != _DEGRADED_HEALED:
1106
+ # A degraded choice is never allowed to enable the bridge. The
1107
+ # successful probe path above is the only automatic enable path.
1108
+ os.environ["BUGX_USE_CODEBASE_MEMORY"] = "0"
1109
+ if status in _DEGRADED_PASSING_STATUSES:
1110
+ continue
1111
+ if exempted and not is_critical:
1112
+ # Explicit project policy is the only non-success release valve.
1113
+ print(
1114
+ f" ⚠ [launch_bugx] {name} 未完成,但已在 config.json "
1115
+ "tooling_exemptions 中显式豁免(已记录)"
1116
+ )
1117
+ receipt = choice.receipt if is_typed_decision else {}
1118
+ normalized[name] = _degraded_decision(
1119
+ _DEGRADED_EXEMPTED,
1120
+ "显式豁免(config.json tooling_exemptions)",
1121
+ {
1122
+ "source": "project_config",
1123
+ "name": name,
1124
+ "status": _DEGRADED_EXEMPTED,
1125
+ "original_status": status or "unstructured",
1126
+ "original_receipt": receipt,
1127
+ },
1128
+ )
1129
+ continue
1130
+ if is_critical and exempted:
1131
+ normalized[name] = _degraded_decision(
1132
+ _DEGRADED_BLOCKED,
1133
+ "阻断:critical MCP/工具不得豁免",
1134
+ {
1135
+ "source": "project_config",
1136
+ "name": name,
1137
+ "reason": "critical_capability_cannot_be_exempted",
1138
+ },
1139
+ )
1140
+ real_blockers.append(name)
1141
+ continue
1142
+ if status == _DEGRADED_DEFERRED:
1143
+ deferred.append(name)
1144
+ continue
1145
+ real_blockers.append(name)
1146
+
1147
+ # Persist the normalized final decision before returning either success or
1148
+ # failure, so explicit exemptions and real failed attempts cannot vanish
1149
+ # on a sibling blocker.
1150
+ _record_degraded_choices(degraded, normalized)
1151
+ if real_blockers:
1152
+ print("MCP/环境工具安装或配置尚未完成,本轮启动已停止:" + ", ".join(real_blockers))
1153
+ print(
1154
+ " DOC-236 C1:本轮不允许降级放行——请先自愈安装/配置后重跑;"
1155
+ "确无自动安装器的专有工具,可在项目 .bugx/config.json 的 "
1156
+ "tooling_exemptions 中显式列出(会留痕,不影响 critical 结论)。"
1157
+ )
1158
+ _emit_self_heal_evidence()
1159
+ return False
1160
+ if deferred:
1161
+ print("MCP/环境工具处置选择为“下次再说”,本轮启动已停止:"
1162
+ + ", ".join(deferred))
1163
+ print(" 处理完成后重新运行启动流程,不会自动绕过该 MCP 决策。")
1164
+ return False
1165
+ return True
1166
+
1167
+
1168
+
1169
+ _degraded_actions = degraded_actions
1170
+ _DegradedDecision = DegradedDecision
1171
+ _degraded_decision = degraded_decision
1172
+ _degraded_item_not_applicable = degraded_item_not_applicable
1173
+ _degraded_item_advisory = degraded_item_advisory
1174
+ _degraded_item_transient = degraded_item_transient
1175
+ _degraded_item_critical = degraded_item_critical
1176
+ _degraded_exemption_hit = degraded_exemption_hit
1177
+ _degraded_decision_for_policy = degraded_decision_for_policy
1178
+ _degraded_receipt_for_report = degraded_receipt_for_report
1179
+ _report_self_heal = report_self_heal
1180
+ _emit_self_heal_evidence = emit_self_heal_evidence
1181
+ _preflight_probe_id = preflight_probe_id
1182
+ _watchlist_error_report = watchlist_error_report
1183
+ _safe_watchlist_incident_id = safe_watchlist_incident_id
1184
+ def _record_degraded_choices(*args, **kwargs):
1185
+ sb = _sb()
1186
+ if sb and hasattr(sb, "_record_degraded_choices"):
1187
+ fn = getattr(sb, "_record_degraded_choices")
1188
+ if fn is not _record_degraded_choices:
1189
+ return fn(*args, **kwargs)
1190
+ return record_degraded_choices(*args, **kwargs)
1191
+ def _auto_provision_accelerators(*args, **kwargs):
1192
+ sb = _sb()
1193
+ if sb and hasattr(sb, "auto_provision_accelerators"):
1194
+ fn = getattr(sb, "auto_provision_accelerators")
1195
+ if fn is not _auto_provision_accelerators and fn is not auto_provision_accelerators:
1196
+ return fn(*args, **kwargs)
1197
+ return auto_provision_accelerators(*args, **kwargs)
1198
+
1199
+ def _degraded_install(item):
1200
+ sb = _sb()
1201
+ if sb and hasattr(sb, "_degraded_install"):
1202
+ fn = getattr(sb, "_degraded_install")
1203
+ if fn is not _degraded_install:
1204
+ return fn(item)
1205
+ return degraded_install(item)
1206
+ def _prompt_degraded_choices(*args, **kwargs):
1207
+ sb = _sb()
1208
+ if sb and hasattr(sb, "_prompt_degraded_choices"):
1209
+ fn = getattr(sb, "_prompt_degraded_choices")
1210
+ if fn is not _prompt_degraded_choices:
1211
+ return fn(*args, **kwargs)
1212
+ return prompt_degraded_choices(*args, **kwargs)
1213
+ def _tooling_exemptions(*args, **kwargs):
1214
+ sb = _sb()
1215
+ if sb and hasattr(sb, "_tooling_exemptions"):
1216
+ fn = getattr(sb, "_tooling_exemptions")
1217
+ if fn is not _tooling_exemptions:
1218
+ return fn(*args, **kwargs)
1219
+ return tooling_exemptions(*args, **kwargs)