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,1134 @@
1
+ #!/usr/bin/env python3
2
+ """BugX 本地 Supervisor MCP 服务。
3
+
4
+ 这是一个无第三方依赖的 MCP stdio 适配层。它只把现有
5
+ ``audit_supervisor.Supervisor`` 的状态机暴露给宿主 AI,不执行 worker 命令,
6
+ 不执行 worker 命令,不访问网络,也不把 ``.bugx`` 的事实源迁移到 MCP 服务进程之外。
7
+
8
+ 每个请求都是一次有限的状态操作;服务不会通过长轮询阻塞等待 worker。宿主应
9
+ 根据 ``next_action`` 决定下一次调用,lease 超时则由 Supervisor 的 status/gate
10
+ 操作回收并记录。
11
+ """
12
+
13
+ from __future__ import annotations
14
+ # --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
15
+ import sys as _sys
16
+ from pathlib import Path as _Path
17
+
18
+ for _p in _Path(__file__).resolve().parents:
19
+ if (_p / "core" / "bugx.md").is_file():
20
+ if str(_p) not in _sys.path:
21
+ _sys.path.insert(0, str(_p))
22
+ break
23
+ del _p
24
+
25
+ import argparse
26
+ import atexit
27
+ import errno
28
+ import hashlib
29
+ import json
30
+ import math
31
+ import os
32
+ import re
33
+ import signal
34
+ import subprocess
35
+ import sys
36
+ import threading
37
+ import time
38
+ from pathlib import Path
39
+ from typing import Any, Callable, Mapping, Sequence
40
+ from urllib.parse import parse_qs, urlparse
41
+
42
+ try:
43
+ import fcntl
44
+ except ImportError: # pragma: no cover - Windows hosts use msvcrt or fallback.
45
+ fcntl = None # type: ignore[assignment]
46
+
47
+ try:
48
+ import msvcrt
49
+ except ImportError:
50
+ msvcrt = None # type: ignore[assignment]
51
+
52
+ _CORE_DIR = Path(__file__).resolve().parent.parent if Path(__file__).resolve().parent.name == "skills" else Path(__file__).resolve().parent
53
+ _REPO_ROOT = _CORE_DIR.parent
54
+ for _p in (str(_REPO_ROOT), str(_CORE_DIR)):
55
+ if _p not in sys.path:
56
+ sys.path.insert(0, _p)
57
+
58
+ # 这些是核心领域模块(core/),缺失即安装损坏:直接 import 让错误在
59
+ # 启动时显式失败,不再用 None 兜底掩盖(DOC-031)。
60
+ from core.supervisor import audit_supervisor
61
+ import core.bugx_paths as bugx_paths
62
+ # 双入口守卫(**不是**兼容别名):本模块既被包内导入,也被宿主以
63
+ # ``python core/skills/<name>.py`` 直接当脚本启动(MCP stdio 子进程)。
64
+ # 脚本模式下 ``__package__`` 为空,相对导入会 ``ImportError: attempted
65
+ # relative import with no known parent package``;此时改用绝对点号名。
66
+ # 两条路径指向**同一个**文件,不存在第二套实现。
67
+ if __package__:
68
+ from . import mcp_session_proof
69
+ else:
70
+ from core.skills import mcp_session_proof
71
+ from core.runtime import bugx_logging
72
+ from core.coverage import coverage_bootstrap
73
+ from core.coverage import module_coverage
74
+ from core.retrieval import knowledge_sources
75
+ import core.secure_atomic as secure_atomic
76
+ from core.planning import unit_kind
77
+ from core.supervisor import checkpoint_pipeline
78
+ from core.supervisor.supervisor_models import VALID_COVERAGE_STATES, VALID_EVIDENCE_STATES
79
+
80
+ # LOG-06:租约上限的单一来源。此前 inputSchema 硬编码 3600,而
81
+ # supervisor_models.MAX_LEASE_SECONDS 是 14400(注释还写「1 小时」),
82
+ # task_scheduler 的推算上限又是 3600——三处漂移。直接引用常量,
83
+ # 让 test_consistency 之外也能靠符号本身保持同步。
84
+ LEASE_SECONDS_MAX = audit_supervisor.MAX_LEASE_SECONDS
85
+
86
+ # DES-05:业务单元前缀的单一来源。schema 里的正则此前硬编码 "^业务:.+",
87
+ # 与 unit_kind.PREFIXES 分离——新增单元类型时会漏改协议层校验,导致
88
+ # 「协议层接受、领域层不认」或反之的静默不一致。
89
+ UNIT_BUSINESS_PATTERN = f"^{unit_kind.UnitKind.BUSINESS.value}:.+"
90
+
91
+ from core.mcp_handlers import (
92
+ HANDLER_REGISTRY,
93
+ MAX_ARTIFACT_PATH_LENGTH,
94
+ MAX_COMMAND_LENGTH,
95
+ MAX_COVERAGE_PER_CHECKPOINT,
96
+ MAX_EVIDENCE_PER_CHECKPOINT,
97
+ MAX_FINDING_FIELD_LENGTH,
98
+ MAX_FINDING_FINGERPRINT_LENGTH,
99
+ MAX_FINDINGS_PER_CHECKPOINT,
100
+ MAX_MCP_JSON_DEPTH,
101
+ MAX_MCP_JSON_KEYS,
102
+ MAX_MCP_REQUEST_BYTES,
103
+ MAX_UNITS_PER_CLAIM,
104
+ McpProtocolError,
105
+ TOKEN_BASE_BUDGET,
106
+ TOKEN_HARD_CEILING,
107
+ TOKEN_MAX_RENEWALS,
108
+ TOKEN_NEEDED_MAX,
109
+ TOKEN_NEEDED_MIN,
110
+ TOKEN_REASON_MAX_LENGTH,
111
+ TOKEN_RENEWAL_MAX_GRANT,
112
+ TOKEN_RENEWAL_STATE_VERSION,
113
+ bool_argument,
114
+ check_json_depth_and_keys,
115
+ compact_json,
116
+ format_result,
117
+ next_action,
118
+ number_argument,
119
+ optional_string,
120
+ optional_string_array_argument,
121
+ project_state,
122
+ recovery_chain,
123
+ serialize_value,
124
+ string_array_argument,
125
+ validate_checkpoint_sizes,
126
+ )
127
+
128
+
129
+ def _finding_severity_levels() -> tuple[str, ...]:
130
+ """finding 严重度单一真源(BX-ENGINE-18);委托给唯一访问器。
131
+
132
+ 仅为渲染 MCP schema 的 ``severity`` enum,避免「schema 无 enum / 门禁有词表」
133
+ 再次漂移。词表与 fallback 快照的唯一定义在
134
+ ``supervisor_models.finding_severity_levels``,此处不再复制字面量。
135
+ """
136
+ try:
137
+ from core.supervisor.supervisor_models import finding_severity_levels
138
+
139
+ return finding_severity_levels()
140
+ except ImportError: # pragma: no cover - 引擎目录不完整时
141
+ return ("info", "low", "medium", "high", "critical")
142
+
143
+
144
+ _FINDING_SEVERITY_LEVELS = _finding_severity_levels()
145
+
146
+ def _i18n_exc(key: str, fallback: str, locale: str | None = None, **kwargs: Any) -> str:
147
+ try:
148
+ import core.i18n as i18n
149
+ return i18n.exception_text(key, locale=locale, fallback=fallback, **kwargs)
150
+ except Exception:
151
+ if not kwargs:
152
+ return fallback
153
+ try:
154
+ return fallback.format(**kwargs)
155
+ except Exception:
156
+ return fallback
157
+
158
+
159
+ def _i18n_prompt(key: str, fallback: str, locale: str | None = None, **kwargs: Any) -> str:
160
+ try:
161
+ import core.i18n as i18n
162
+ return i18n.prompt_text(key, locale=locale, fallback=fallback, **kwargs)
163
+ except Exception:
164
+ if not kwargs:
165
+ return fallback
166
+ try:
167
+ return fallback.format(**kwargs)
168
+ except Exception:
169
+ return fallback
170
+
171
+
172
+ MCP_PROTOCOL_VERSION = "2024-11-05"
173
+ SERVER_NAME = "bugx-supervisor"
174
+ SERVER_VERSION = "1.0.0"
175
+ JSONRPC_VERSION = "2.0"
176
+ # A CLI ``pre`` command is short-lived, while the host MCP stdio process owns
177
+ # the Session afterwards. Keep the interval well below the time it takes for
178
+ # the next CLI phase to start so a new polling scope is claimed before the
179
+ # runtime orphan detector sees the pre process as dead.
180
+ HOST_SESSION_HEARTBEAT_INTERVAL_SECONDS = 5.0
181
+ MCP_ROLES = {"host", "worker"}
182
+ # DES-08:MCP 工具元数据的**单一真源**。
183
+ #
184
+ # 原先工具元数据分散在三处维护,任一处笔误都会静默产生「被宣告但无法分发」
185
+ # 或「能分发但未被宣告」的工具:
186
+ # 1. HOST_TOOLS / WORKER_TOOLS / READ_ONLY_TOOLS 三个角色集合(原在本处);
187
+ # 2. ``_tool_definitions()`` 内的 41 条 schema 字面量;
188
+ # 3. ``mcp_handlers.HANDLER_REGISTRY``(工具名 -> 实现的分发表)。
189
+ # 现在:角色归属与 schema 在 ``_build_tool_table()`` 里**同处声明**,三个集合由它派生,
190
+ # 分发表由模块底部的 ``_assert_tool_registry_consistent()`` 强制校验。
191
+ #
192
+ # 角色语义:三个集合**两两不相交**,并集即全部工具。
193
+ # _HOST_ONLY 仅宿主可调用;_WORKER_ONLY 仅 Worker 可调用;_SHARED_ROLES 双方均可。
194
+ _HOST_ONLY = frozenset({"host"})
195
+ _WORKER_ONLY = frozenset({"worker"})
196
+ _SHARED_ROLES = frozenset({"host", "worker"})
197
+
198
+ # (Protocol caps and McpProtocolError imported from mcp_handlers)
199
+
200
+
201
+ import core.mcp_handlers.channel_lifecycle as _cl
202
+
203
+ _pid_alive = _cl._pid_alive
204
+ _idle_self_exit_seconds = _cl._idle_self_exit_seconds
205
+ _ChannelActivity = _cl._ChannelActivity
206
+ _channel_active_claim_keys = _cl._channel_active_claim_keys
207
+ _channel_idle_exit_reason = _cl._channel_idle_exit_reason
208
+ _record_lease_event = _cl._record_lease_event
209
+ _channel_self_retire = _cl._channel_self_retire
210
+ _channel_idle_monitor_loop = _cl._channel_idle_monitor_loop
211
+ _read_lease_holder = _cl._read_lease_holder
212
+ _holder_idle_seconds = _cl._holder_idle_seconds
213
+ _takeover_holder = _cl._takeover_holder
214
+ _host_channel_state_path = _cl._host_channel_state_path
215
+ _clear_host_channel_unavailable = _cl._clear_host_channel_unavailable
216
+ _run_external = _cl._run_external
217
+ _holder_started_at = _cl._holder_started_at
218
+ _record_host_channel_unavailable = _cl._record_host_channel_unavailable
219
+ _ControllerLease = _cl._ControllerLease
220
+ _host_session_heartbeat_once = _cl._host_session_heartbeat_once
221
+ _host_session_heartbeat_loop = _cl._host_session_heartbeat_loop
222
+
223
+ def _error_payload(error: BaseException) -> dict[str, object]:
224
+ return {
225
+ "error_type": type(error).__name__,
226
+ "message": str(error) or type(error).__name__,
227
+ "error_code": "MCP_CALL_FAILED",
228
+ "interactive_required": True,
229
+ "next_action": "PROMPT_USER",
230
+ "prompt": (
231
+ "MCP 调用失败,请立即询问用户:1) 立即重试 2) 本轮切换手动/回退 "
232
+ "3) 下次再说(停止本轮)"
233
+ ),
234
+ "choices": ["retry", "fallback", "later"],
235
+ }
236
+
237
+
238
+ def _call_failure_data(operation: object, error: BaseException) -> dict[str, object]:
239
+ """为 tools/call 协议错误提供可被宿主直接呈现的交互门禁。"""
240
+ payload = _error_payload(error)
241
+ payload["operation"] = str(operation or "unknown")
242
+ return payload
243
+
244
+
245
+ # (next_action imported from mcp_handlers)
246
+
247
+
248
+ class BugxMcpService:
249
+ """MCP facade bound to one project and active lifecycle.
250
+
251
+ Construction is deliberately fail-closed: it never creates or repairs the
252
+ ``.bugx`` layout on its own. A missing or incomplete layout must be
253
+ created through an explicit, host-confirmed entry (``bugx init`` /
254
+ ``bugx_paths.initialize`` or a host-driven bootstrap), so an arbitrary
255
+ directory opened by a host cannot silently become a BugX project.
256
+ """
257
+
258
+ # Controlled explicit initialization entry retained for hosts that need
259
+ # to bootstrap a fresh workspace. It requires an explicit host
260
+ # confirmation and never runs implicitly from construction.
261
+ @staticmethod
262
+ def initialize_project(root: Path, *, bugx_version: str = SERVER_VERSION) -> object:
263
+ """Explicit, host-confirmed project initialization entry.
264
+
265
+ Callers must have obtained user/host confirmation before invoking.
266
+ This is the only MCP-side path that may create ``.bugx``.
267
+ """
268
+ target = root.expanduser().resolve()
269
+ if not target.is_dir():
270
+ raise McpProtocolError(f"项目根目录不是目录: {target}")
271
+ return bugx_paths.initialize(target, bugx_version=bugx_version)
272
+
273
+ def __init__(self, root: Path, *, role: str = "host") -> None:
274
+ self.root = root.expanduser().resolve()
275
+ if not self.root.is_dir():
276
+ raise McpProtocolError(f"项目根目录不是目录: {self.root}")
277
+ if role not in MCP_ROLES:
278
+ raise McpProtocolError(f"MCP role 必须是 {sorted(MCP_ROLES)}")
279
+ self.role = role
280
+ # Host injects this identity only into the dedicated Worker stdio
281
+ # process it launches. A caller-supplied MCP argument is never enough
282
+ # to authenticate a graph Worker.
283
+ self.native_agent_id = (
284
+ os.environ.get("BUGX_NATIVE_AGENT_ID") if role == "worker" else None
285
+ )
286
+ # ``tools/list`` can happen before ``pre`` creates a new polling
287
+ # scope. Retain only the bounded names so a later request/heartbeat
288
+ # can republish the same receipt into the current scope.
289
+ self._session_tool_names: tuple[str, ...] = ()
290
+ # DOC-230 3.1 层 2 / 3.2:由 ``serve()`` 注入的通道活动记录。
291
+ # 非 stdio 场景(进程内服务、测试)保持 None,行为完全不变。
292
+ self.activity: _ChannelActivity | None = None
293
+ # A stdio process can outlive a BugX polling scope. Bind its proof to
294
+ # one UUID and refresh the scope fields on each publication so a stale
295
+ # PID or a replacement connection cannot overwrite this receipt.
296
+ self._session_instance_id = mcp_session_proof.new_instance_id()
297
+ self._session_process_start_token = mcp_session_proof.process_start_token(os.getpid())
298
+ self._session_last_request_at: float | None = None
299
+ self._session_last_progress_at: float | None = None
300
+ # Fail-closed: do not touch the filesystem here. Layout validation
301
+ # is deferred to _scope() so construction has no side effects.
302
+
303
+ def _scope(self):
304
+ try:
305
+ return bugx_paths.require(self.root)
306
+ except bugx_paths.LayoutError as exc:
307
+ # Surface as a structured MCP protocol error so hosts can prompt
308
+ # for explicit initialization instead of silently creating state.
309
+ raise McpProtocolError(
310
+ f"[INITIALIZATION_REQUIRED] 项目未初始化或布局不完整: {exc};请先通过受控入口初始化(bugx install --root . --agent {self.role} --non-interactive)",
311
+ code=-32602,
312
+ ) from exc
313
+
314
+ def is_initialized(self) -> bool:
315
+ """Check whether the active workspace layout is complete."""
316
+ try:
317
+ bugx_paths.require(self.root)
318
+ return True
319
+ except bugx_paths.LayoutError:
320
+ return False
321
+
322
+ def acquire_controller_lease(self) -> _ControllerLease:
323
+ """Acquire the single IDE control lease for the host channel."""
324
+ if self.role != "host":
325
+ raise McpProtocolError("worker MCP 通道不能持有主控租约")
326
+ lease = _ControllerLease(self._scope().state_root / "controller.lock")
327
+ lease.acquire()
328
+ return lease
329
+
330
+ def _session_proof_path(self) -> Path:
331
+ return mcp_session_proof.proof_path(
332
+ self._scope().state_root, self._session_instance_id,
333
+ )
334
+
335
+ def _session_scope_fields(self) -> tuple[str | None, str | None, int]:
336
+ """Read the current lifecycle binding without making one up."""
337
+ lifecycle_id: str | None = None
338
+ scope: str | None = None
339
+ generation = 0
340
+ try:
341
+ current = bugx_paths.read_current(self.root)
342
+ lifecycle_id = str(
343
+ current.get("lifecycle_id") or current.get("polling_id") or ""
344
+ ).strip() or None
345
+ scope = str(current.get("scope") or lifecycle_id or "").strip() or None
346
+ raw_generation = current.get("scope_generation", 0)
347
+ if isinstance(raw_generation, int) and not isinstance(raw_generation, bool):
348
+ generation = max(0, raw_generation)
349
+ except Exception:
350
+ pass
351
+ if scope is None:
352
+ try:
353
+ scope = self._scope().lifecycle_root.name
354
+ except Exception:
355
+ pass
356
+ return lifecycle_id, scope, generation
357
+
358
+ def _session_entrypoint_hash(self) -> str:
359
+ try:
360
+ return __import__("hashlib").sha256(
361
+ Path(__file__).read_bytes()
362
+ ).hexdigest()
363
+ except OSError:
364
+ return "0" * 64
365
+
366
+ def _touch_session_request(self) -> None:
367
+ self._session_last_request_at = time.time()
368
+ try:
369
+ mcp_session_proof.update_proof(
370
+ self._scope().state_root, self._session_instance_id,
371
+ last_request_at=self._session_last_request_at,
372
+ inflight=1,
373
+ )
374
+ except (OSError, ValueError, RuntimeError):
375
+ pass
376
+
377
+ def _touch_session_progress(self) -> None:
378
+ self._session_last_progress_at = time.time()
379
+ try:
380
+ mcp_session_proof.update_proof(
381
+ self._scope().state_root, self._session_instance_id,
382
+ last_progress_at=self._session_last_progress_at,
383
+ inflight=0,
384
+ )
385
+ except (OSError, ValueError, RuntimeError):
386
+ pass
387
+
388
+ def write_session_proof(self, tool_names: Sequence[str]) -> Path:
389
+ """Publish a bounded receipt after the real MCP tools/list handshake."""
390
+ names = tuple(str(name)[:256] for name in list(tool_names)[:256])
391
+ self._session_tool_names = names
392
+ now = time.time()
393
+ lifecycle_id, scope, generation = self._session_scope_fields()
394
+ phase = mcp_session_proof.PHASE_ACTIVE
395
+ try:
396
+ existing = mcp_session_proof.read_proof(
397
+ self._session_proof_path(),
398
+ expected_instance_id=self._session_instance_id,
399
+ )
400
+ phase = str(existing.get("phase") or phase)
401
+ self._session_last_request_at = existing.get("last_request_at") # type: ignore[assignment]
402
+ self._session_last_progress_at = existing.get("last_progress_at") # type: ignore[assignment]
403
+ except (OSError, ValueError, RuntimeError):
404
+ pass
405
+ return mcp_session_proof.write_proof(
406
+ self._scope().state_root,
407
+ {
408
+ "schema_version": mcp_session_proof.SCHEMA_VERSION,
409
+ "server": SERVER_NAME,
410
+ "server_version": SERVER_VERSION,
411
+ "root": str(self.root),
412
+ "scope": scope,
413
+ "lifecycle_id": lifecycle_id,
414
+ "scope_generation": generation,
415
+ "role": self.role,
416
+ "instance_id": self._session_instance_id,
417
+ "pid": os.getpid(),
418
+ "process_start_token": self._session_process_start_token,
419
+ "engine_build": SERVER_VERSION,
420
+ "entrypoint_hash": self._session_entrypoint_hash(),
421
+ "transport": "stdio",
422
+ "phase": phase,
423
+ "written_at": now,
424
+ "proof_written_at": now,
425
+ "last_request_at": self._session_last_request_at,
426
+ "last_progress_at": self._session_last_progress_at,
427
+ "inflight": 0,
428
+ "loaded": True,
429
+ "callable": True,
430
+ "healthy": phase == mcp_session_proof.PHASE_ACTIVE,
431
+ "tool_names": list(names),
432
+ },
433
+ instance=self._session_instance_id,
434
+ now=now,
435
+ )
436
+
437
+ def refresh_session_proof(self) -> Path | None:
438
+ """Republish the tools/list receipt after the current scope changes.
439
+
440
+ OpenCode keeps MCP stdio processes alive across BugX Session creation.
441
+ The service therefore cannot treat the scope captured at process start
442
+ as authoritative. A refresh is best-effort for MCP availability; the
443
+ autonomous lifecycle gate remains the fail-closed authority.
444
+ """
445
+ if not self._session_tool_names:
446
+ return None
447
+ try:
448
+ return self.write_session_proof(self._session_tool_names)
449
+ except (OSError, ValueError, RuntimeError):
450
+ return None
451
+
452
+ def clear_session_proof(self) -> None:
453
+ """Cooperatively close this connection without deleting its receipt."""
454
+ try:
455
+ mcp_session_proof.set_phase(
456
+ self._scope().state_root, self._session_instance_id,
457
+ mcp_session_proof.PHASE_RETIRING,
458
+ )
459
+ mcp_session_proof.set_phase(
460
+ self._scope().state_root, self._session_instance_id,
461
+ mcp_session_proof.PHASE_CLOSED,
462
+ )
463
+ except (OSError, UnicodeError, ValueError, RuntimeError):
464
+ return
465
+
466
+ def get_supervisor(self, *, budget: Any = None):
467
+ active = self._scope()
468
+ return audit_supervisor.Supervisor(
469
+ self.root,
470
+ budget=budget,
471
+ state_path=active.supervisor,
472
+ )
473
+
474
+ def _coverage_units(self) -> list[str]:
475
+ active = self._scope()
476
+ manifest = active.state_root / "module-coverage.md"
477
+ if not manifest.is_file() or manifest.is_symlink():
478
+ raise McpProtocolError(f"覆盖清单缺失或不安全: {manifest}")
479
+ return checkpoint_pipeline.load_manifest_units(self.root, manifest)
480
+
481
+ @staticmethod
482
+ def _coverage_bootstrap_gate(state: Mapping[str, object]) -> dict[str, object]:
483
+ return {
484
+ "status": "COVERAGE_BOOTSTRAP_REQUIRED",
485
+ "interactive_required": True,
486
+ "next_action": "PROMPT_USER",
487
+ "gate": "coverage_bootstrap",
488
+ "question": "覆盖清单尚未建立,是否运行引导创建?",
489
+ "multiple": False,
490
+ "options": [
491
+ {
492
+ "label": "运行引导创建",
493
+ "description": "由 BugX Supervisor 创建本生命周期的最小覆盖单元,然后自动重试启动",
494
+ "value": "bootstrap",
495
+ },
496
+ {
497
+ "label": "下次再说",
498
+ "description": "停止本轮启动,不创建或修改任何运行态清单",
499
+ "value": "later",
500
+ },
501
+ ],
502
+ "detail": str(state.get("detail") or "覆盖清单缺失"),
503
+ "path": state.get("path"),
504
+ }
505
+
506
+ def _consumption_ids(self) -> tuple[str, str]:
507
+ """Resolve the current Session/Round/Life/run for knowledge consumption.
508
+
509
+ The ledger must be able to audit which lifecycle and run actually
510
+ consumed a pattern/incident. Using a fixed ``mcp`` placeholder hides
511
+ the true Session/Round/Life/run and breaks the host's traceability
512
+ gate. We therefore bind to the authoritative project layout and, when
513
+ a Supervisor run exists, to its live ``run_id``.
514
+ """
515
+ lifecycle_id: str | None = None
516
+ run_id: str | None = None
517
+ # Primary lifecycle is the authoritative project current (Life).
518
+ try:
519
+ cur = bugx_paths.read_current(self.root)
520
+ lifecycle_id = str(cur.get("lifecycle_id") or cur.get("polling_id") or "")
521
+ if not run_id:
522
+ base_lifecycle = cur.get("lifecycle_id")
523
+ base_polling = cur.get("polling_id")
524
+ # PE-20261005-003: 诊断兜底与 Supervisor 生成侧同形(polling 限定)
525
+ if base_lifecycle and base_polling:
526
+ run_id = f"lifecycle-{base_polling}-{base_lifecycle}"
527
+ elif base_lifecycle or base_polling:
528
+ run_id = f"lifecycle-{base_lifecycle or base_polling}"
529
+ except Exception:
530
+ pass
531
+ # Prefer the live Supervisor run_id when a run exists; keep lifecycle
532
+ # as the current Life (not the polling Session) for ledger indexing.
533
+ try:
534
+ sup = self.get_supervisor()
535
+ st = sup.status()
536
+ rid = getattr(st, "run_id", None)
537
+ if isinstance(rid, str) and rid.strip():
538
+ run_id = rid.strip()
539
+ # If Supervisor has an explicit life_id, it is authoritative for
540
+ # the Life; otherwise keep the current lifecycle.
541
+ lid = getattr(st, "life_id", None)
542
+ if isinstance(lid, str) and lid.strip():
543
+ lifecycle_id = lid.strip()
544
+ except Exception:
545
+ pass
546
+ # Final fallback: use the scope's lifecycle when readable.
547
+ if not lifecycle_id or not run_id:
548
+ try:
549
+ sc = self._scope()
550
+ if not lifecycle_id:
551
+ lifecycle_id = sc.lifecycle_root.name
552
+ if not run_id:
553
+ # PE-20261005-003: 与 Supervisor 生成侧同形(polling 限定)
554
+ _polling_name = sc.lifecycle_root.parent.parent.name
555
+ run_id = (
556
+ f"lifecycle-{_polling_name}-{sc.lifecycle_root.name}"
557
+ if _polling_name.startswith("polling-")
558
+ else f"lifecycle-{sc.lifecycle_root.name}"
559
+ )
560
+ except Exception:
561
+ pass
562
+ lifecycle_id = (lifecycle_id or "unknown").strip() or "unknown"
563
+ run_id = (run_id or "unknown").strip() or "unknown"
564
+ # Never return the old placeholder; it would hide the real binding.
565
+ if lifecycle_id == "mcp":
566
+ lifecycle_id = "unknown"
567
+ if run_id == "mcp":
568
+ run_id = "unknown"
569
+ return lifecycle_id, run_id
570
+
571
+ def _request_token_renewal(self, *, reason: str, needed: int) -> dict[str, object]:
572
+ """Atomically account for a bounded token renewal in the active lifecycle."""
573
+ try:
574
+ with bugx_paths._project_lock(self.root):
575
+ scope = self._scope()
576
+ state_path = scope.state_root / "mcp-token-renewal.json"
577
+ try:
578
+ secure_atomic.reject_symlink_components(state_path)
579
+ except secure_atomic.AtomicWriteError as exc:
580
+ raise McpProtocolError(
581
+ f"动态续命状态路径不安全: {state_path}", code=-32602,
582
+ ) from exc
583
+
584
+ if state_path.exists():
585
+ if state_path.is_symlink() or not state_path.is_file():
586
+ raise McpProtocolError(
587
+ "动态续命状态损坏,拒绝重置", code=-32602,
588
+ )
589
+ try:
590
+ if state_path.stat().st_size > 65536:
591
+ raise ValueError("state too large")
592
+ state = json.loads(state_path.read_text(encoding="utf-8"))
593
+ except (OSError, UnicodeError, ValueError, json.JSONDecodeError) as exc:
594
+ raise McpProtocolError(
595
+ "动态续命状态损坏,拒绝重置", code=-32602,
596
+ ) from exc
597
+ else:
598
+ state = {
599
+ "schema_version": TOKEN_RENEWAL_STATE_VERSION,
600
+ "lifecycle_id": scope.lifecycle_root.name,
601
+ "renewals_used": 0,
602
+ "granted_tokens": 0,
603
+ "reason_digests": [],
604
+ }
605
+
606
+ if not isinstance(state, dict):
607
+ raise McpProtocolError("动态续命状态损坏,拒绝重置", code=-32602)
608
+ renewals_used = state.get("renewals_used")
609
+ granted_tokens = state.get("granted_tokens")
610
+ reason_digests = state.get("reason_digests")
611
+ if (
612
+ state.get("schema_version") != TOKEN_RENEWAL_STATE_VERSION
613
+ or state.get("lifecycle_id") != scope.lifecycle_root.name
614
+ or isinstance(renewals_used, bool)
615
+ or not isinstance(renewals_used, int)
616
+ or not 0 <= renewals_used <= TOKEN_MAX_RENEWALS
617
+ or isinstance(granted_tokens, bool)
618
+ or not isinstance(granted_tokens, int)
619
+ or not 0 <= granted_tokens <= TOKEN_RENEWAL_MAX_GRANT * TOKEN_MAX_RENEWALS
620
+ or TOKEN_BASE_BUDGET + granted_tokens > TOKEN_HARD_CEILING
621
+ or granted_tokens < renewals_used * TOKEN_NEEDED_MIN
622
+ or granted_tokens > renewals_used * TOKEN_RENEWAL_MAX_GRANT
623
+ or not isinstance(reason_digests, list)
624
+ or len(reason_digests) != renewals_used
625
+ or any(
626
+ not isinstance(item, str) or len(item) != 64
627
+ or any(char not in "0123456789abcdef" for char in item)
628
+ for item in reason_digests
629
+ )
630
+ ):
631
+ raise McpProtocolError("动态续命状态损坏,拒绝重置", code=-32602)
632
+
633
+ current_budget = TOKEN_BASE_BUDGET + granted_tokens
634
+ if renewals_used >= TOKEN_MAX_RENEWALS:
635
+ return {
636
+ "status": "ok",
637
+ "approved": False,
638
+ "granted_tokens": 0,
639
+ "renewals_used": renewals_used,
640
+ "renewals_remaining": 0,
641
+ "current_budget": current_budget,
642
+ }
643
+
644
+ grant = min(
645
+ needed,
646
+ TOKEN_RENEWAL_MAX_GRANT,
647
+ TOKEN_HARD_CEILING - current_budget,
648
+ )
649
+ if grant <= 0:
650
+ return {
651
+ "status": "ok",
652
+ "approved": False,
653
+ "granted_tokens": 0,
654
+ "renewals_used": renewals_used,
655
+ "renewals_remaining": 0,
656
+ "current_budget": current_budget,
657
+ }
658
+
659
+ state["renewals_used"] = renewals_used + 1
660
+ state["granted_tokens"] = granted_tokens + grant
661
+ state["reason_digests"] = [
662
+ *reason_digests,
663
+ hashlib.sha256(reason.encode("utf-8")).hexdigest(),
664
+ ]
665
+ secure_atomic.atomic_write_json(
666
+ state_path, state, mode=0o600, parent_mode=0o700,
667
+ )
668
+ return {
669
+ "status": "ok",
670
+ "approved": True,
671
+ "granted_tokens": grant,
672
+ "renewals_used": renewals_used + 1,
673
+ "renewals_remaining": TOKEN_MAX_RENEWALS - renewals_used - 1,
674
+ "current_budget": current_budget + grant,
675
+ }
676
+ except McpProtocolError:
677
+ raise
678
+ except (bugx_paths.LayoutError, OSError, secure_atomic.AtomicWriteError) as exc:
679
+ raise McpProtocolError(f"动态续命状态不可用: {exc}", code=-32602) from exc
680
+
681
+ def _host_channel_state(self) -> dict[str, object]:
682
+ """DOC-230 3.3:返回 host 通道可用性,供 status 内联给 worker 通道。
683
+
684
+ - 本进程就是 host → 必然可用;
685
+ - 否则读取 host 启动失败时落盘的冲突记录(带 TTL,避免陈旧误报);
686
+ - 无记录/记录过期 → `available=None`(**未观察到冲突**,不等于可用)。
687
+ """
688
+ if self.role == "host":
689
+ return {
690
+ "available": True, "blocked_by": None,
691
+ "idle_seconds": None, "how_to_unblock": None, "observed": True,
692
+ }
693
+ path = _host_channel_state_path(self._scope().state_root)
694
+ payload: object = None
695
+ try:
696
+ if path.is_file() and not path.is_symlink():
697
+ payload = json.loads(path.read_text(encoding="utf-8"))
698
+ except (OSError, UnicodeError, json.JSONDecodeError):
699
+ payload = None
700
+ if not isinstance(payload, Mapping):
701
+ return {
702
+ "available": None, "blocked_by": None,
703
+ "idle_seconds": None, "how_to_unblock": None, "observed": False,
704
+ }
705
+ observed_at = payload.get("observed_at")
706
+ ttl = payload.get("ttl_seconds")
707
+ fresh = (
708
+ isinstance(observed_at, (int, float)) and not isinstance(observed_at, bool)
709
+ and isinstance(ttl, (int, float)) and not isinstance(ttl, bool)
710
+ and (time.time() - float(observed_at)) <= float(ttl)
711
+ )
712
+ if not fresh:
713
+ return {
714
+ "available": None, "blocked_by": None,
715
+ "idle_seconds": None, "how_to_unblock": None,
716
+ "observed": False, "stale": True,
717
+ }
718
+ return {
719
+ "available": False,
720
+ "blocked_by": {
721
+ "holder_pid": payload.get("holder_pid"),
722
+ "holder_started_at": payload.get("holder_started_at"),
723
+ "observed_at": observed_at,
724
+ },
725
+ "idle_seconds": payload.get("holder_idle_seconds"),
726
+ "how_to_unblock": payload.get("how_to_unblock"),
727
+ "observed": True,
728
+ }
729
+
730
+ def _status_payload(self, supervisor: Any) -> dict[str, object]:
731
+ try:
732
+ snapshot = supervisor.status_with_gate()
733
+ except audit_supervisor.NoRunError:
734
+ return {
735
+ "status": "NO_RUN",
736
+ "next_action": "START_RUN",
737
+ # DOC-230 3.3:即使尚未 start,worker 通道也必须能判断自己
738
+ # 是否具备恢复能力(否则「静默降级」在这一刻最易发生)。
739
+ "host_channel": self._host_channel_state(),
740
+ "root": str(self.root),
741
+ }
742
+ state_payload = snapshot["state"]
743
+ gate = snapshot["parallel_gate"]
744
+ if isinstance(state_payload, dict):
745
+ state_payload = dict(state_payload)
746
+ for field, limit in (("history", 50), ("findings", 100), ("parallel_proof_history", 20)):
747
+ value = state_payload.get(field)
748
+ if isinstance(value, list) and len(value) > limit:
749
+ state_payload[field] = value[-limit:]
750
+ state_payload[f"{field}_truncated"] = True
751
+ # 控制面决策必须消费原始未压缩投影的完整 state 字典
752
+ action_val = next_action(state_payload, gate)
753
+ host_channel = self._host_channel_state()
754
+ chain_val = recovery_chain(
755
+ state_payload, gate, caller_role=self.role,
756
+ host_channel=host_channel.get("blocked_by"),
757
+ )
758
+ payload = project_state(state_payload)
759
+ payload["parallel_gate"] = gate
760
+ payload["next_action"] = action_val
761
+ payload["host_channel"] = host_channel
762
+ payload["recovery_chain"] = chain_val
763
+ payload["root"] = str(self.root)
764
+ return payload
765
+
766
+ def _budget(self, arguments: Mapping[str, object]):
767
+ allow_serial = bool_argument(arguments, "allow_serial", False)
768
+ serial_reason = arguments.get("serial_reason")
769
+ if serial_reason is not None and not isinstance(serial_reason, str):
770
+ raise McpProtocolError("serial_reason 必须是字符串或 null")
771
+ require_confirmation = bool_argument(arguments, "require_confirmation", True)
772
+ if not require_confirmation:
773
+ raise McpProtocolError(
774
+ "Supervisor MCP 强制启用 Finding confirmation;"
775
+ "require_confirmation 只能为 true"
776
+ )
777
+ try:
778
+ # Resolve the adaptive concurrency pair once. RunBudget's default
779
+ # factories otherwise resolve the host again while constructing the
780
+ # ceiling, so a config/environment change between the two reads can
781
+ # produce an inconsistent budget (and makes the protocol hard to
782
+ # test deterministically).
783
+ system_concurrency, system_ceiling = (
784
+ audit_supervisor.resolve_system_concurrency()
785
+ )
786
+ return audit_supervisor.RunBudget(
787
+ max_rounds=number_argument(arguments, "max_rounds", 10, integer=True),
788
+ max_wall_seconds=number_argument(arguments, "max_wall_seconds", 3600.0),
789
+ max_round_wall_seconds=number_argument(
790
+ arguments, "max_round_wall_seconds", 1800.0,
791
+ ),
792
+ max_tool_calls=number_argument(
793
+ arguments, "max_tool_calls", 1000, integer=True,
794
+ ),
795
+ max_cost_units=number_argument(
796
+ arguments, "max_cost_units", 10000.0,
797
+ ),
798
+ max_concurrency=number_argument(
799
+ arguments, "max_concurrency",
800
+ system_concurrency,
801
+ integer=True,
802
+ ),
803
+ max_concurrency_ceiling=system_ceiling,
804
+ require_parallel=not allow_serial,
805
+ serial_reason=serial_reason,
806
+ require_confirmation=require_confirmation,
807
+ )
808
+ except (TypeError, ValueError) as exc:
809
+ raise McpProtocolError(f"budget 参数无效: {exc}") from exc
810
+
811
+ def _require_role(
812
+ self, arguments: Mapping[str, object], tool_name: str, *allowed: str,
813
+ ) -> str:
814
+ """Enforce both the declared role and this MCP channel's role.
815
+
816
+ A caller-supplied ``caller_role`` is not an identity proof. The
817
+ actual boundary is the separately configured host/worker stdio
818
+ service, whose tools are filtered by role. The declaration remains
819
+ required as an explicit protocol assertion and audit field.
820
+
821
+ DOC-230 3.6:``_TOOL_ROLES`` 是角色归属的**单一真源**。handler 声明的
822
+ 允许角色必须与工具表一致;否则会重现「worker 通道列出工具、调用却必拒」
823
+ 的虚假可用性(BX-ENGINE-16)。此处 fail-closed 报错,把漂移暴露在第一次
824
+ 调用而不是用户排障时。
825
+ """
826
+ declared_roles = _TOOL_ROLES.get(tool_name)
827
+ if declared_roles is not None and set(allowed) != set(declared_roles):
828
+ raise McpProtocolError(
829
+ f"{tool_name} 角色声明与工具表不一致:"
830
+ f"handler={sorted(allowed)} table={sorted(declared_roles)}"
831
+ )
832
+ role = arguments.get("caller_role")
833
+ if not role and self.role in set(allowed):
834
+ role = self.role
835
+ if not isinstance(role, str) or role not in set(allowed):
836
+ raise McpProtocolError(
837
+ f"{tool_name} 需要 caller_role={('/'.join(allowed))}"
838
+ )
839
+ if role != self.role:
840
+ raise McpProtocolError(
841
+ f"{tool_name} 不允许在 {self.role} MCP 通道中以 {role} 身份调用"
842
+ )
843
+ return role
844
+
845
+ def call(self, name: str, arguments: Mapping[str, object]) -> dict[str, object]:
846
+ if not isinstance(arguments, Mapping):
847
+ raise McpProtocolError("tools/call arguments 必须是对象", code=-32602)
848
+ # Generic bounded check for all tool arguments (depth/keys/size)
849
+ if len(arguments) > 200:
850
+ raise McpProtocolError("arguments 键过多", code=-32602)
851
+ check_json_depth_and_keys(arguments)
852
+ # DOC-230 3.1 层 2 / 3.2:stdin 服务场景下把每次工具调用记为通道活动,
853
+ # 并统计 inflight,使空闲自退既不误退"正在执行"的调用,也能在被遗弃时
854
+ # 主动让位。非 stdio 场景(activity 为 None)行为完全不变。
855
+ activity = self.activity
856
+ if activity is not None:
857
+ activity.enter()
858
+ activity.touch(worker_id=arguments.get("worker_id"))
859
+ try:
860
+ return self._call_locked(name, arguments)
861
+ finally:
862
+ if activity is not None:
863
+ activity.leave()
864
+
865
+ def _call_locked(self, name: str, arguments: Mapping[str, object]) -> dict[str, object]:
866
+ def _resolve_tool_name(tool_name: str) -> str:
867
+ if tool_name in _TOOL_ROLES:
868
+ return tool_name
869
+ candidates = [
870
+ f"bugx_supervisor_{tool_name}",
871
+ f"bugx_supervisor_worker_{tool_name}",
872
+ ]
873
+ for candidate in candidates:
874
+ if candidate in _TOOL_ROLES:
875
+ return candidate
876
+ return tool_name
877
+
878
+ resolved_name = _resolve_tool_name(name)
879
+ allowed_roles = _TOOL_ROLES.get(resolved_name)
880
+ if allowed_roles is None:
881
+ raise McpProtocolError(_i18n_exc("mcp.unknown_tool", f"未知工具: {name}", name=name))
882
+ name = resolved_name
883
+ call_arguments = dict(arguments)
884
+ if self.role not in allowed_roles:
885
+ declared_role = call_arguments.get("caller_role") or self.role
886
+ target_channel = "bugx-supervisor-worker" if "worker" in allowed_roles else "bugx-supervisor"
887
+ required_role_desc = next(iter(allowed_roles)) if allowed_roles in (_HOST_ONLY, _WORKER_ONLY) else "/".join(sorted(allowed_roles))
888
+ raise McpProtocolError(
889
+ f"{name} 需要 caller_role={required_role_desc} 且不允许在 {self.role} MCP 通道中以 {declared_role!r} 身份调用;"
890
+ f"请切换至 MCP 服务通道 '{target_channel}'"
891
+ )
892
+ if allowed_roles in (_HOST_ONLY, _WORKER_ONLY):
893
+ required_role = next(iter(allowed_roles))
894
+ # The stdio server itself is the role boundary.
895
+ # If caller_role was omitted, directly infer it from required_role / self.role.
896
+ if not call_arguments.get("caller_role"):
897
+ call_arguments["caller_role"] = required_role
898
+ elif call_arguments.get("caller_role") != required_role:
899
+ raise McpProtocolError(f"{name} 需要 caller_role={required_role}")
900
+ if self.role == "host":
901
+ # The daemon may have started before CLI pre created runtime.json;
902
+ # claim the live host on the first host request instead of waiting
903
+ # for the next periodic tick.
904
+ _host_session_heartbeat_once(self.root)
905
+ # The request may be the first request after a new polling scope was
906
+ # created. Refresh the role-bound proof before dispatching the tool.
907
+ self.refresh_session_proof()
908
+ self._touch_session_request()
909
+ try:
910
+ return HANDLER_REGISTRY[name](self, call_arguments)
911
+ finally:
912
+ self._touch_session_progress()
913
+
914
+ def _knowledge(self):
915
+ """延迟加载错题账本模块;让 worker 一条调用拿到经验卡。"""
916
+ module = getattr(self, "_knowledge_module", None)
917
+ if module is not None:
918
+ return module
919
+ from core.ledger import lesson_ledger
920
+
921
+ self._knowledge_module = lesson_ledger
922
+ return lesson_ledger
923
+
924
+ def _runtime_intelligence(self) -> list:
925
+ """只读读取 runtime 的 intelligence_history(缺省为空列表)。"""
926
+ try:
927
+ state = json.loads(
928
+ self._scope().runtime.read_text(encoding="utf-8"),
929
+ )
930
+ except (OSError, json.JSONDecodeError):
931
+ return []
932
+ history = state.get("intelligence_history")
933
+ return history if isinstance(history, list) else []
934
+
935
+ def read_resource(self, uri: str) -> dict[str, object]:
936
+ """只读读取 BugX 核心事实态 MCP Resource。"""
937
+ self.refresh_session_proof()
938
+ MAX_RESOURCE_BYTES = 262144
939
+ if uri == "bugx://state/status":
940
+ mime_type = "application/json"
941
+ try:
942
+ payload = self._status_payload(self.get_supervisor())
943
+ except audit_supervisor.NoRunError:
944
+ payload = {"status": "NO_RUN", "detail": "无正在运行的 Supervisor", "root": str(self.root)}
945
+ except McpProtocolError as exc:
946
+ payload = {"status": "NOT_INITIALIZED", "detail": str(exc), "root": str(self.root)}
947
+ text = json.dumps(payload, ensure_ascii=False, indent=2)
948
+ elif uri == "bugx://state/coverage" or uri.startswith("bugx://state/coverage?"):
949
+ mime_type = "application/json"
950
+ try:
951
+ st = self.get_supervisor().status()
952
+ query = parse_qs(urlparse(uri).query)
953
+ offset = max(0, int(query.get("offset", [0])[0]))
954
+ limit = min(500, max(1, int(query.get("limit", [200])[0])))
955
+ items = sorted(st.coverage.items())
956
+ page = dict(items[offset:offset + limit])
957
+ payload = {
958
+ "coverage": page,
959
+ "debt": st.coverage_debt,
960
+ "complete": st.coverage_complete,
961
+ "total_units": len(st.coverage),
962
+ "offset": offset,
963
+ "limit": limit,
964
+ "next_offset": offset + limit if offset + limit < len(items) else None,
965
+ }
966
+ except audit_supervisor.NoRunError:
967
+ payload = {"status": "NO_RUN", "detail": "无正在运行的 Supervisor"}
968
+ except (McpProtocolError, ValueError) as exc:
969
+ payload = {"status": "NOT_INITIALIZED", "detail": str(exc)}
970
+ text = json.dumps(payload, ensure_ascii=False, indent=2)
971
+ elif uri == "bugx://findings/recent":
972
+ mime_type = "application/json"
973
+ try:
974
+ st = self.get_supervisor().status()
975
+ payload = {
976
+ "status": "ok",
977
+ "findings_count": len(st.findings),
978
+ "findings": list(st.findings),
979
+ }
980
+ except audit_supervisor.NoRunError:
981
+ payload = {"status": "NO_RUN", "detail": "无正在运行的 Supervisor"}
982
+ except McpProtocolError as exc:
983
+ payload = {"status": "NOT_INITIALIZED", "detail": str(exc)}
984
+ text = json.dumps(payload, ensure_ascii=False, indent=2)
985
+ elif uri == "bugx://knowledge/mistakes":
986
+ mime_type = "text/markdown"
987
+ try:
988
+ scope = self._scope()
989
+ shared = knowledge_sources.retrieve_patterns(
990
+ self._knowledge(), scope.knowledge_seed,
991
+ scope.global_knowledge_seed, limit=10, runtime_only=True,
992
+ )
993
+ if scope.mistake_book.is_file():
994
+ text = scope.mistake_book.read_text(encoding="utf-8")
995
+ else:
996
+ text = "# BugX Mistakes & Anti-Patterns\n\n暂无错题记录。"
997
+ global_lessons = [
998
+ item for item in shared
999
+ if item.get("knowledge_source") == "global"
1000
+ ]
1001
+ if global_lessons:
1002
+ lines = [text.rstrip(), "", "# Shared Active Knowledge", ""]
1003
+ for l in global_lessons:
1004
+ title = l.get("title") or l.get("pattern_id") or "Lesson"
1005
+ lines.append(f"## {title}")
1006
+ if l.get("reflection"):
1007
+ lines.append(f"{l.get('reflection')}\n")
1008
+ text = "\n".join(lines)
1009
+ elif not scope.mistake_book.is_file() and shared:
1010
+ lines = ["# BugX Mistakes & Anti-Patterns", ""]
1011
+ for l in shared:
1012
+ title = l.get("title") or l.get("pattern_id") or "Lesson"
1013
+ lines.append(f"## {title}")
1014
+ if l.get("reflection"):
1015
+ lines.append(f"{l.get('reflection')}\n")
1016
+ text = "\n".join(lines)
1017
+ except Exception:
1018
+ text = "# BugX Mistakes & Anti-Patterns\n\n暂无错题记录。"
1019
+ elif uri == "bugx://profile/target":
1020
+ mime_type = "application/json"
1021
+ try:
1022
+ from core.runtime import project_profile
1023
+ profile = None
1024
+ try:
1025
+ profile = project_profile.load_project_profile(self._scope().knowledge_seed)
1026
+ except Exception:
1027
+ profile = None
1028
+ if not profile:
1029
+ profile = project_profile.detect_project_profile(self.root)
1030
+ text = json.dumps(profile, ensure_ascii=False, indent=2)
1031
+ except Exception as exc:
1032
+ text = json.dumps({"error": f"无法生成目标项目画像: {exc}"}, ensure_ascii=False, indent=2)
1033
+ else:
1034
+ raise McpProtocolError(f"未知或非法的 Resource URI: {uri}", code=-32602)
1035
+
1036
+ encoded = text.encode("utf-8")
1037
+ if len(encoded) > MAX_RESOURCE_BYTES:
1038
+ text = encoded[:MAX_RESOURCE_BYTES].decode("utf-8", errors="ignore") + "\n... [truncated]"
1039
+
1040
+ return {
1041
+ "contents": [
1042
+ {
1043
+ "uri": uri,
1044
+ "mimeType": mime_type,
1045
+ "text": text,
1046
+ }
1047
+ ]
1048
+ }
1049
+
1050
+ def get_prompt(self, name: str, arguments: Mapping[str, object]) -> dict[str, object]:
1051
+ """按阶段装配标准 MCP Prompt 工作流消息。"""
1052
+ prompt_map = {
1053
+ "bugx-audit-explore": ("explore", _i18n_prompt("mcp.explore_title", "BugX 勘察与代码单元初筛")),
1054
+ "bugx-fuzz-mutate": ("mutate", _i18n_prompt("mcp.mutate_title", "BugX 模糊测试与状态变异挖掘")),
1055
+ "bugx-repro-verify": ("repair", _i18n_prompt("mcp.repair_title", "BugX 最小复现与差分修复")),
1056
+ "bugx-gate-decision": ("gate", _i18n_prompt("mcp.gate_title", "BugX 会话启动与门禁裁决")),
1057
+ }
1058
+ if name not in prompt_map:
1059
+ raise McpProtocolError(_i18n_exc("mcp.unknown_prompt_template", f"未知 Prompt 模版: {name}", name=name), code=-32602)
1060
+ stage, desc = prompt_map[name]
1061
+ unit_id = arguments.get("unit_id")
1062
+ rule_name = arguments.get("rule")
1063
+ context = arguments.get("context")
1064
+ if context is not None and not isinstance(context, Mapping):
1065
+ raise McpProtocolError(_i18n_exc("mcp.context_must_be_object", "context 必须是对象"), code=-32602)
1066
+ from core.planning import prompt_harness
1067
+ try:
1068
+ content = prompt_harness.get_stage_prompt(stage, context=context, root=self.root)
1069
+ except (ValueError, FileNotFoundError) as exc:
1070
+ raise McpProtocolError(str(exc), code=-32602)
1071
+
1072
+ rule_slice = None
1073
+ if unit_id and isinstance(unit_id, str):
1074
+ rule_slice = prompt_harness.detect_unit_rule_slice(unit_id, root=self.root)
1075
+ elif rule_name and isinstance(rule_name, str):
1076
+ try:
1077
+ rule_content = prompt_harness.load_rule(rule_name, root=self.root)
1078
+ rule_slice = f"【专项规则 - {rule_name}】\n" + rule_content
1079
+ except (ValueError, FileNotFoundError):
1080
+ rule_slice = None
1081
+
1082
+ if rule_slice:
1083
+ content = f"{content}\n\n{rule_slice}"
1084
+
1085
+ return {
1086
+ "description": desc,
1087
+ "messages": [
1088
+ {
1089
+ "role": "user",
1090
+ "content": {
1091
+ "type": "text",
1092
+ "text": content,
1093
+ },
1094
+ }
1095
+ ],
1096
+ }
1097
+
1098
+
1099
+
1100
+
1101
+ try:
1102
+ import core.mcp_handlers.resource_prompt_table as _rpt
1103
+ import core.mcp_handlers.tool_table as _tt
1104
+ import core.mcp_handlers.rpc_server as _rpc
1105
+ except ImportError:
1106
+ import core.mcp_handlers.resource_prompt_table as _rpt
1107
+ import core.mcp_handlers.tool_table as _tt
1108
+ import core.mcp_handlers.rpc_server as _rpc
1109
+
1110
+ _resource_definitions = _rpt._resource_definitions
1111
+ _prompt_definitions = _rpt._prompt_definitions
1112
+
1113
+ _build_tool_table = _tt._build_tool_table
1114
+ _assert_tool_registry_consistent = _tt._assert_tool_registry_consistent
1115
+ _tool_definitions = _tt._tool_definitions
1116
+ _TOOL_TABLE = _tt._TOOL_TABLE
1117
+ _TOOL_ROLES = _tt._TOOL_ROLES
1118
+ _WORKER_CORE_TOOL_NAMES = _tt._WORKER_CORE_TOOL_NAMES
1119
+ HOST_TOOLS = _tt.HOST_TOOLS
1120
+ WORKER_TOOLS = _tt.WORKER_TOOLS
1121
+ READ_ONLY_TOOLS = _tt.READ_ONLY_TOOLS
1122
+
1123
+ _response = _rpc._response
1124
+ _rpc_error = _rpc._rpc_error
1125
+ _line_is_complete = _rpc._line_is_complete
1126
+ _safe_tool_call_summary = _rpc._safe_tool_call_summary
1127
+ serve = _rpc.serve
1128
+ _resolve_serve_root = _rpc._resolve_serve_root
1129
+ main = _rpc.main
1130
+
1131
+ _assert_tool_registry_consistent()
1132
+
1133
+ if __name__ == "__main__":
1134
+ raise SystemExit(main())