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,1393 @@
1
+ #!/usr/bin/env python3
2
+ """BugX 统一诊断日志。
3
+
4
+ 日志是排查安装、宿主调用和运行异常的辅助记录,不替代生命周期事件、结论或
5
+ 证据文件。已初始化的项目写入项目 ``.bugx/logs/bugx.jsonl``;尚未初始化的
6
+ 目录回退到用户级 ``~/.bugx/logs/projects/<project_id>/bugx.jsonl``。
7
+
8
+ 回退是必需的:``.bugx/logs/`` 由项目布局初始化器创建(DOC-001 §5.8),而
9
+ 诊断日志是**每个命令**(包括 ``doctor``/``hosts`` 这类纯只读命令)都会产生
10
+ 的副作用。若由日志引导来创建 ``<root>/.bugx``,任何在普通目录里的读操作都会
11
+ 凭空造出一个"有 .bugx 但没有 manifest"的半初始化状态,并把该目录的
12
+ ``git status`` 弄脏(BugX 不管理 ``.gitignore``)。采用标准库 logging,支持
13
+ JSONL、等级过滤、有限轮转和敏感字段脱敏。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import contextvars
19
+ import datetime as dt
20
+ from contextlib import contextmanager
21
+ import hashlib
22
+ import json
23
+ import logging
24
+ import time
25
+ from logging.handlers import RotatingFileHandler
26
+ import os
27
+ from pathlib import Path
28
+ import re
29
+ import statistics
30
+ import sys
31
+ import time
32
+ from typing import Any
33
+ import uuid
34
+
35
+ try:
36
+ import fcntl
37
+ except ImportError: # pragma: no cover - Windows has no fcntl.
38
+ fcntl = None # type: ignore[assignment]
39
+
40
+ try:
41
+ import msvcrt
42
+ except ImportError: # pragma: no cover - POSIX has no msvcrt.
43
+ msvcrt = None # type: ignore[assignment]
44
+
45
+ LOG_SCHEMA_VERSION = 2
46
+ _CORRELATION_CACHE: dict[str, Any] = {}
47
+ LOG_DIR_NAME = "logs"
48
+ LOG_FILE_NAME = "bugx.jsonl"
49
+ # 未初始化目录的日志回退根。默认 ``~/.bugx/logs``,与 ``BUGX_GLOBAL_CACHE_ROOT``
50
+ # / ``BUGX_GLOBAL_TELEMETRY_ROOT`` 同属"用户级、可被测试隔离"的一类覆盖点。
51
+ GLOBAL_LOG_ROOT_ENV = "BUGX_GLOBAL_LOG_ROOT"
52
+ GLOBAL_LOG_PROJECTS_DIR = "projects"
53
+ MAX_BYTES = 5 * 1024 * 1024
54
+ BACKUP_COUNT = 3
55
+ LOGGER_NAME = "bugx"
56
+ _SCOPED_SYNC_EXPORT: contextvars.ContextVar[bool] = contextvars.ContextVar(
57
+ "bugx_scoped_sync_export", default=False,
58
+ )
59
+ _CONTEXT_ENV = {
60
+ "trace_id": "BUGX_TRACE_ID",
61
+ "run_id": "BUGX_RUN_ID",
62
+ "lifecycle_id": "BUGX_LIFECYCLE_ID",
63
+ "round": "BUGX_ROUND",
64
+ "worker_id": "BUGX_WORKER_ID",
65
+ "finding_id": "BUGX_FINDING_ID",
66
+ "incident_id": "BUGX_INCIDENT_ID",
67
+ }
68
+
69
+ _SECRET_KEY = re.compile(
70
+ r"(?:token|password|passwd|secret|api[_-]?key|access[_-]?key|cookie|authorization"
71
+ r"|credential|private[_-]?key|auth)",
72
+ re.IGNORECASE,
73
+ )
74
+ # LLM 阶段统计与预算字段排除在敏感鉴权 Token 脱敏之外 (DOC-042)
75
+ _METRIC_TOKEN_KEY = re.compile(
76
+ r"(?:^|[_-])(?:tokens?_consumed|tokens?_budget|tokens?_breakdown|tokens?_count"
77
+ r"|prompt_tokens|completion_tokens|total_tokens|diff_tokens|actual_tokens"
78
+ r"|budget_tokens|tokens)$",
79
+ re.IGNORECASE,
80
+ )
81
+ # 值侧匹配允许引号包裹(token="abc" / secret='xyz'),引号计入前缀组,
82
+ # 结束引号保留在输出中,脱敏后仍是合法的引用片段。
83
+ _SECRET_VALUE = re.compile(
84
+ r"(?i)(bearer\s+|basic\s+|(?:token|password|passwd|secret|api[_-]?key|cookie"
85
+ r"|credential|private[_-]?key|auth)\s*[=:]\s*[\"']?)[^\s,;\"']+",
86
+ )
87
+ # 无 key 上下文的超长疑似 token(JWT / base64 私钥片段等)整段脱敏。
88
+ _LONG_TOKEN = re.compile(r"[A-Za-z0-9_-]{80,}")
89
+
90
+
91
+ def is_initialized_project(root: Path) -> bool:
92
+ """Return whether ``root`` already carries a BugX project manifest.
93
+
94
+ ``.bugx/logs/`` belongs to the project layout and is created by the layout
95
+ initializer (``bugx init`` / ``bugx install``, DOC-001 §5.8). A directory
96
+ without ``.bugx/manifest.json`` has no project runtime to record evidence
97
+ in, so the diagnostic logger must not be the thing that creates one.
98
+ """
99
+ manifest = Path(root).resolve() / ".bugx" / "manifest.json"
100
+ return manifest.is_file() and not manifest.is_symlink()
101
+
102
+
103
+ def global_log_root() -> Path:
104
+ """Return the per-user fallback log root without creating it."""
105
+ override = os.environ.get(GLOBAL_LOG_ROOT_ENV)
106
+ if override:
107
+ return Path(override).expanduser()
108
+ return Path.home() / ".bugx" / LOG_DIR_NAME
109
+
110
+
111
+ def project_log_id(root: Path) -> str:
112
+ """Return the stable per-project key used to isolate fallback logs.
113
+
114
+ Mirrors ``bugx_paths._project_id`` so a fallback log can be traced back to
115
+ its directory without reading that directory's (absent) manifest.
116
+ """
117
+ return hashlib.sha256(str(Path(root).resolve()).encode("utf-8")).hexdigest()[:16]
118
+
119
+
120
+ def global_log_path(root: Path) -> Path:
121
+ """Return the fallback log path for a directory that is not a project."""
122
+ return (
123
+ global_log_root()
124
+ / GLOBAL_LOG_PROJECTS_DIR
125
+ / project_log_id(root)
126
+ / LOG_FILE_NAME
127
+ )
128
+
129
+
130
+ def log_path(root: Path, *, project_scoped: bool | None = None) -> Path:
131
+ """Return the diagnostic log path without creating anything.
132
+
133
+ Initialized projects keep the documented ``<root>/.bugx/logs/bugx.jsonl``
134
+ location. Anything else falls back to the per-user store so that running a
135
+ read-only command from an arbitrary directory stays observationally
136
+ read-only instead of manufacturing project state.
137
+ """
138
+ root = Path(root).resolve()
139
+ if project_scoped is None:
140
+ project_scoped = is_initialized_project(root)
141
+ if project_scoped:
142
+ return root / ".bugx" / LOG_DIR_NAME / LOG_FILE_NAME
143
+ return global_log_path(root)
144
+
145
+
146
+ def _private_dir_chain(outer: Path, inner: Path, *, label: str) -> Path:
147
+ """Create every level from ``outer`` down to ``inner`` as a 0700 directory.
148
+
149
+ ``outer`` is the BugX-owned root (``<root>/.bugx`` or ``~/.bugx/logs``), so
150
+ an intermediate ``projects/<project_id>`` step cannot be left world
151
+ readable. Every level is checked for symlinks first: a linked component
152
+ could redirect the log outside the intended tree (SEC-14).
153
+ """
154
+ try:
155
+ relative = inner.relative_to(outer)
156
+ except ValueError:
157
+ raise ValueError(f"{label}日志目录必须位于 {outer} 之内: {inner}") from None
158
+ chain = [outer]
159
+ for part in relative.parts:
160
+ chain.append(chain[-1] / part)
161
+ for candidate in chain:
162
+ if candidate.is_symlink() or (candidate.exists() and not candidate.is_dir()):
163
+ raise ValueError(f"拒绝写入不安全的{label}日志目录: {candidate}")
164
+ for candidate in chain:
165
+ candidate.mkdir(mode=0o700, exist_ok=True)
166
+ os.chmod(candidate, 0o700)
167
+ return inner
168
+
169
+
170
+ DEFAULT_SLOW_THRESHOLD_SECONDS = 30.0
171
+ _TRACEPARENT_RE = re.compile(
172
+ r"^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$", re.IGNORECASE
173
+ )
174
+
175
+
176
+ def parse_traceparent(raw: str | None) -> dict[str, str] | None:
177
+ """Parse a W3C traceparent header string into constituent fields.
178
+
179
+ Conforms to W3C TraceContext Level 1:
180
+ - Version 'ff' is rejected as invalid;
181
+ - All-zero trace_id or parent_id are rejected as invalid;
182
+ - Returns lower-case hex values if valid, else None.
183
+ """
184
+ if not raw or not isinstance(raw, str):
185
+ return None
186
+ raw = raw.strip()
187
+ match = _TRACEPARENT_RE.match(raw)
188
+ if not match:
189
+ return None
190
+ version, trace_id, parent_id, flags = match.groups()
191
+ if version.lower() == "ff":
192
+ return None
193
+ if trace_id == "0" * 32:
194
+ return None
195
+ if parent_id == "0" * 16:
196
+ return None
197
+ return {
198
+ "version": version.lower(),
199
+ "trace_id": trace_id.lower(),
200
+ "parent_id": parent_id.lower(),
201
+ "trace_flags": flags.lower(),
202
+ }
203
+
204
+
205
+ def generate_traceparent(trace_id: str | None = None, parent_id: str | None = None,
206
+ flags: str = "01") -> str:
207
+ """Generate a standard W3C traceparent header string."""
208
+ clean_trace = trace_id.lower() if trace_id and len(trace_id) == 32 else uuid.uuid4().hex
209
+ clean_parent = parent_id.lower() if parent_id and len(parent_id) == 16 else uuid.uuid4().hex[:16]
210
+ return f"00-{clean_trace}-{clean_parent}-{flags}"
211
+
212
+
213
+ def safe_value(value: Any, *, key: str = "") -> Any:
214
+ if key and _SECRET_KEY.search(key) and not _METRIC_TOKEN_KEY.search(key):
215
+ return "[REDACTED]"
216
+ if isinstance(value, dict):
217
+ return {str(k): safe_value(v, key=str(k)) for k, v in value.items()}
218
+ if isinstance(value, (list, tuple, set)):
219
+ return [safe_value(item, key=key) for item in value]
220
+ if isinstance(value, Path):
221
+ return str(value)
222
+ if isinstance(value, str):
223
+ redacted = _SECRET_VALUE.sub(r"\1[REDACTED]", value)
224
+ return _LONG_TOKEN.sub("[REDACTED]", redacted)
225
+ if value is None or isinstance(value, (bool, int, float)):
226
+ return value
227
+ return str(value)
228
+
229
+
230
+ class _JsonFormatter(logging.Formatter):
231
+ def format(self, record: logging.LogRecord) -> str:
232
+ timestamp = dt.datetime.fromtimestamp(
233
+ record.created, tz=dt.timezone.utc,
234
+ ).isoformat(timespec="milliseconds").replace("+00:00", "Z")
235
+ payload: dict[str, Any] = {
236
+ "schema_version": LOG_SCHEMA_VERSION,
237
+ "timestamp": timestamp,
238
+ "level": record.levelname,
239
+ "logger": record.name,
240
+ "event": getattr(record, "bugx_event", "log"),
241
+ "message": record.getMessage(),
242
+ "pid": record.process,
243
+ }
244
+ try:
245
+ from core.infra import build_info
246
+ payload["build_id"] = build_info.get_build_id()
247
+ except Exception:
248
+ pass
249
+ fields = getattr(record, "bugx_fields", {})
250
+ if isinstance(fields, dict):
251
+ payload.update(safe_value(fields))
252
+ if record.exc_info:
253
+ payload["exception"] = safe_value(self.formatException(record.exc_info))
254
+ return json.dumps(safe_value(payload), ensure_ascii=False, separators=(",", ":"))
255
+
256
+
257
+ class _OtlpHttpHandler(logging.Handler):
258
+ """Asynchronous HTTP exporter to push spans to OTLP endpoint (e.g. Arize Phoenix / Langfuse)."""
259
+
260
+ def __init__(self, endpoint: str) -> None:
261
+ super().__init__()
262
+ self.endpoint = endpoint
263
+ import urllib.request
264
+ self._request_mod = urllib.request
265
+
266
+ def emit(self, record: logging.LogRecord) -> None:
267
+ fields = getattr(record, "bugx_fields", {})
268
+ if not isinstance(fields, dict):
269
+ return
270
+ trace_id = fields.get("trace_id")
271
+ span_id = fields.get("span_id")
272
+ if not trace_id or not span_id:
273
+ return
274
+
275
+ # A reusable launcher scope restores cwd/env before returning. Finish
276
+ # exports in that scope so their proxy/config reads cannot cross the
277
+ # restoration boundary. The existing request timeout is not a DNS or
278
+ # total wall-clock guarantee.
279
+ if _SCOPED_SYNC_EXPORT.get():
280
+ self._send_otlp(record, fields, trace_id, span_id)
281
+ return
282
+
283
+ # 异步线程发送,绝不阻塞主控或工具调用
284
+ import threading
285
+ t = threading.Thread(
286
+ target=self._send_otlp,
287
+ args=(record, fields, trace_id, span_id),
288
+ daemon=True,
289
+ )
290
+ t.start()
291
+
292
+ def _send_otlp(self, record: logging.LogRecord, fields: dict[str, Any], trace_id: str, span_id: str) -> None:
293
+ try:
294
+ start_time_ns = int(record.created * 1e9)
295
+ duration_ms = fields.get("duration_ms") or (float(fields.get("duration_seconds", 0)) * 1000)
296
+ end_time_ns = start_time_ns + int(float(duration_ms) * 1e6)
297
+ clean_trace = str(trace_id).lower().replace("-", "").zfill(32)[-32:]
298
+ clean_span = str(span_id).lower().replace("-", "").zfill(16)[-16:]
299
+ parent_id = fields.get("parent_span_id")
300
+ clean_parent = str(parent_id).lower().replace("-", "").zfill(16)[-16:] if parent_id else ""
301
+
302
+ attrs = []
303
+ for k, v in fields.items():
304
+ if k in {"trace_id", "span_id", "parent_span_id", "traceparent"}:
305
+ continue
306
+ attrs.append({
307
+ "key": str(k),
308
+ "value": {"stringValue": str(safe_value(v))},
309
+ })
310
+
311
+ event_name = getattr(record, "bugx_event", "log")
312
+ span = {
313
+ "traceId": clean_trace,
314
+ "spanId": clean_span,
315
+ "name": f"bugx.{event_name}",
316
+ "kind": 1, # SPAN_KIND_INTERNAL
317
+ "startTimeUnixNano": str(start_time_ns),
318
+ "endTimeUnixNano": str(end_time_ns),
319
+ "attributes": attrs,
320
+ "status": {"code": 2 if record.levelno >= logging.ERROR else 1},
321
+ }
322
+ if clean_parent:
323
+ span["parentSpanId"] = clean_parent
324
+
325
+ otlp_payload = {
326
+ "resourceSpans": [{
327
+ "resource": {
328
+ "attributes": [{
329
+ "key": "service.name",
330
+ "value": {"stringValue": "bugx"},
331
+ }],
332
+ },
333
+ "scopeSpans": [{
334
+ "scope": {"name": "bugx.tracer", "version": "1.0.0"},
335
+ "spans": [span],
336
+ }],
337
+ }],
338
+ }
339
+ body = json.dumps(otlp_payload).encode("utf-8")
340
+ req = self._request_mod.Request(
341
+ self.endpoint,
342
+ data=body,
343
+ headers={"Content-Type": "application/json"},
344
+ method="POST",
345
+ )
346
+ kwargs: dict[str, Any] = {"timeout": 2.0}
347
+ if self.endpoint.startswith("https://"):
348
+ try:
349
+ from core.infra.client_metadata import tls_context
350
+ kwargs["context"] = tls_context(base_url=self.endpoint)
351
+ except Exception:
352
+ pass
353
+ with self._request_mod.urlopen(req, **kwargs) as resp:
354
+ pass
355
+ except Exception:
356
+ pass
357
+
358
+
359
+ class _SecureRotatingFileHandler(RotatingFileHandler):
360
+ """Private rotating handler with a process-wide rollover lock."""
361
+
362
+ def __init__(self, filename, *args, **kwargs): # type: ignore[no-untyped-def]
363
+ super().__init__(filename, *args, **kwargs)
364
+ self._bugx_lock_path = Path(f"{self.baseFilename}.lock")
365
+ if self._bugx_lock_path.is_symlink():
366
+ raise ValueError(f"拒绝使用符号链接日志锁: {self._bugx_lock_path}")
367
+ deadline = time.monotonic() + 10.0
368
+ while True:
369
+ try:
370
+ self._bugx_lock_path.touch(mode=0o600, exist_ok=True)
371
+ os.chmod(self._bugx_lock_path, 0o600)
372
+ self._bugx_lock_stream = self._bugx_lock_path.open("a+b")
373
+ break
374
+ except OSError:
375
+ if time.monotonic() >= deadline:
376
+ self._bugx_lock_stream = None # degrade gracefully
377
+ break
378
+ time.sleep(0.02)
379
+
380
+ @contextmanager
381
+ def _process_lock(self):
382
+ if self._bugx_lock_stream is None:
383
+ yield
384
+ return
385
+ if fcntl is not None:
386
+ deadline = time.monotonic() + 10.0
387
+ lock_mode = fcntl.LOCK_EX | getattr(fcntl, "LOCK_NB", 0)
388
+ while True:
389
+ try:
390
+ fcntl.flock(self._bugx_lock_stream.fileno(), lock_mode)
391
+ break
392
+ except OSError:
393
+ if time.monotonic() >= deadline:
394
+ raise
395
+ time.sleep(0.05)
396
+ try:
397
+ yield
398
+ finally:
399
+ fcntl.flock(self._bugx_lock_stream.fileno(), fcntl.LOCK_UN)
400
+ return
401
+ if msvcrt is not None:
402
+ # ``LK_LOCK`` can surface a sharing violation as PermissionError
403
+ # on Windows when another BugX process is rotating the same log.
404
+ # Use the non-blocking primitive and own the bounded wait here so
405
+ # a transient peer never crashes the install command.
406
+ deadline = time.monotonic() + 10.0
407
+ lock_mode = getattr(msvcrt, "LK_NBLCK", None)
408
+ if lock_mode is None: # pragma: no cover - old msvcrt fallback.
409
+ lock_mode = msvcrt.LK_LOCK
410
+ while True:
411
+ self._bugx_lock_stream.seek(0)
412
+ try:
413
+ msvcrt.locking(
414
+ self._bugx_lock_stream.fileno(), lock_mode, 1,
415
+ )
416
+ break
417
+ except OSError:
418
+ if time.monotonic() >= deadline:
419
+ raise
420
+ time.sleep(0.05)
421
+ try:
422
+ yield
423
+ finally:
424
+ self._bugx_lock_stream.seek(0)
425
+ msvcrt.locking(
426
+ self._bugx_lock_stream.fileno(), msvcrt.LK_UNLCK, 1,
427
+ )
428
+ return
429
+ yield
430
+
431
+ def _open(self): # type: ignore[no-untyped-def]
432
+ stream = super()._open()
433
+ try:
434
+ os.chmod(self.baseFilename, 0o600)
435
+ except OSError:
436
+ pass
437
+ return stream
438
+
439
+ def _write_jsonl_record(self, record: logging.LogRecord) -> str | None:
440
+ """Write and flush one record, returning its event ID only on success.
441
+
442
+ ``RotatingFileHandler.emit`` intentionally routes formatter and I/O
443
+ errors through ``handleError``. That behavior is useful for ordinary
444
+ diagnostics, but it cannot serve as an acknowledgement for post gates:
445
+ callers need to distinguish a flushed JSONL row from a silently dropped
446
+ one. Keep the handler's rollover policy and process lock, while making
447
+ the formatter/write/flush/close result explicit.
448
+ """
449
+ event_fields = getattr(record, "bugx_fields", {})
450
+ event_id = event_fields.get("event_id") if isinstance(event_fields, dict) else None
451
+
452
+ # Closing the previous descriptor while holding the process lock keeps
453
+ # another process from rotating a file that this process still has open.
454
+ if self.stream is not None:
455
+ previous_stream = self.stream
456
+ self.stream = None
457
+ previous_stream.close()
458
+
459
+ try:
460
+ if self.shouldRollover(record):
461
+ self.doRollover()
462
+ if self.stream is None:
463
+ self.stream = self._open()
464
+ rendered = self.format(record)
465
+ line = rendered + self.terminator
466
+ written = self.stream.write(line)
467
+ if written != len(line):
468
+ raise OSError("short JSONL write")
469
+ self.stream.flush()
470
+ return event_id if isinstance(event_id, str) and event_id else None
471
+ finally:
472
+ if self.stream is not None:
473
+ stream = self.stream
474
+ self.stream = None
475
+ stream.close()
476
+
477
+ def emit(self, record: logging.LogRecord) -> None:
478
+ # Handler.lock covers threads. The lock file also covers independent CLI,
479
+ # MCP, and worker processes sharing one project log during rollover.
480
+ # A successful acknowledgement is attached to this LogRecord only after
481
+ # the exact event_id has been formatted, written, flushed, and closed.
482
+ event_fields = getattr(record, "bugx_fields", {})
483
+ event_id = event_fields.get("event_id") if isinstance(event_fields, dict) else None
484
+ try:
485
+ with self._process_lock():
486
+ acknowledged_id = self._write_jsonl_record(record)
487
+ except Exception:
488
+ # Do not call logging.Handler.handleError here: it may print event
489
+ # contents or an I/O traceback to stderr. log_event observes the
490
+ # missing acknowledgement and returns False to its caller.
491
+ setattr(record, "_bugx_jsonl_error_event_id", event_id)
492
+ return
493
+ if isinstance(event_id, str) and acknowledged_id == event_id:
494
+ setattr(record, "_bugx_jsonl_ack_event_id", acknowledged_id)
495
+ else:
496
+ setattr(record, "_bugx_jsonl_error_event_id", event_id)
497
+
498
+ def close(self) -> None:
499
+ try:
500
+ self._bugx_lock_stream.close()
501
+ except AttributeError:
502
+ pass
503
+ super().close()
504
+
505
+
506
+ def _is_within(candidate: Path, base: Path) -> bool:
507
+ """Return whether ``candidate`` sits under ``base`` (real-path boundary)."""
508
+ try:
509
+ candidate.relative_to(base.resolve())
510
+ except ValueError:
511
+ return False
512
+ return True
513
+
514
+
515
+ def close_handlers_for_root(root: Path) -> int:
516
+ """Close the diagnostic handlers owned by ``root`` and return the count.
517
+
518
+ One root can own two locations: the project log under ``<root>/.bugx`` and
519
+ the per-user fallback used while the project is not initialized yet.
520
+ Callers that delete or replace either tree (install rollback, reset,
521
+ uninstall) must release these handles first: on Windows an open handle
522
+ makes ``unlink``/``rmtree`` fail with WinError 32, masking the real error.
523
+ POSIX is unaffected but closing early is harmless.
524
+ """
525
+ resolved_root = Path(root).expanduser().resolve()
526
+ bases = (resolved_root / ".bugx", global_log_path(resolved_root).parent)
527
+ closed = 0
528
+ logger = logging.getLogger(LOGGER_NAME)
529
+ for handler in list(logger.handlers):
530
+ handler_path = getattr(handler, "_bugx_log_path", None)
531
+ if not handler_path:
532
+ continue
533
+ # 真实路径边界判断:字符串 startswith 会误命中 <root>/.bugx-evil 等同级前缀
534
+ candidate = Path(str(handler_path).replace("/", os.sep)).resolve()
535
+ if not any(_is_within(candidate, base) for base in bases):
536
+ continue
537
+ try:
538
+ handler.close()
539
+ except OSError:
540
+ pass
541
+ finally:
542
+ logger.removeHandler(handler)
543
+ closed += 1
544
+ return closed
545
+
546
+
547
+ @contextmanager
548
+ def isolated_logger_scope():
549
+ """Preserve the embedding process's BugX logger for one serialized call.
550
+
551
+ ``configure`` replaces the shared logger's context and closes old handlers.
552
+ Detach them before an in-process launcher invocation so its configuration
553
+ cannot close the host's files or send sandbox events to the host's log.
554
+ The caller must serialize calls that configure this process-global logger.
555
+ Nested scopes preserve the outer scope's handlers and context in the same
556
+ way. Handlers created in this scope are closed on every exit path, including
557
+ exporters which do not have a ``_bugx_log_path``. Scope-owned exports finish
558
+ synchronously, before the runtime scope restores cwd/environment; outside
559
+ this context the normal CLI exporter remains asynchronous.
560
+ """
561
+ logger = logging.getLogger(LOGGER_NAME)
562
+ handlers = list(logger.handlers)
563
+ level, propagate, disabled = logger.level, logger.propagate, logger.disabled
564
+ missing = object()
565
+ context = getattr(logger, "_bugx_context", missing)
566
+ export_token = _SCOPED_SYNC_EXPORT.set(True)
567
+ try:
568
+ for handler in handlers:
569
+ logger.removeHandler(handler)
570
+ try:
571
+ yield logger
572
+ finally:
573
+ for handler in list(logger.handlers):
574
+ logger.removeHandler(handler)
575
+ if handler not in handlers:
576
+ try:
577
+ handler.close()
578
+ except OSError:
579
+ pass
580
+ for handler in handlers:
581
+ logger.addHandler(handler)
582
+ logger.setLevel(level)
583
+ logger.propagate = propagate
584
+ logger.disabled = disabled
585
+ if context is missing:
586
+ if hasattr(logger, "_bugx_context"):
587
+ delattr(logger, "_bugx_context")
588
+ else:
589
+ logger._bugx_context = context # type: ignore[attr-defined]
590
+ finally:
591
+ _SCOPED_SYNC_EXPORT.reset(export_token)
592
+
593
+
594
+ def _level(value: str | int | None) -> int:
595
+ if value is None:
596
+ value = os.environ.get("BUGX_LOG_LEVEL", "INFO")
597
+ if isinstance(value, int):
598
+ return value
599
+ normalized = str(value).upper()
600
+ # ``getLevelNamesMapping`` was added after the oldest Python runtime still
601
+ # used by existing BugX projects. Keep the logger usable on 3.9/3.10 so
602
+ # a compatibility issue cannot hide the actual pre/status failure.
603
+ mapping = getattr(logging, "getLevelNamesMapping", None)
604
+ level_map = mapping() if mapping is not None else {
605
+ name: number for name, number in logging._nameToLevel.items()
606
+ }
607
+ level = level_map.get(normalized)
608
+ if not isinstance(level, int):
609
+ raise ValueError(f"无效日志等级: {value!r}(可选 DEBUG/INFO/WARNING/ERROR)")
610
+ return level
611
+
612
+
613
+ def configure(root: Path, *, command: str | None = None,
614
+ level: str | int | None = None,
615
+ trace_id: str | None = None,
616
+ project_scoped: bool | None = None) -> logging.Logger:
617
+ """Configure and return the BugX logger for one project root.
618
+
619
+ ``project_scoped`` forces the log into ``<root>/.bugx/logs`` (``True``) or
620
+ into the per-user fallback (``False``). The default ``None`` decides by
621
+ project state alone — deliberately the same rule as :func:`log_path`, so a
622
+ reader can never look somewhere the writer did not write. A directory
623
+ without ``.bugx/manifest.json`` falls back, because logging is a side
624
+ effect of every command and must never be what creates ``<root>/.bugx``.
625
+
626
+ Consequence: the invocation that *creates* the project (``bugx init`` /
627
+ ``bugx install``) still logs to the fallback, since the manifest does not
628
+ exist yet when logging is configured. The project log then starts with the
629
+ next command; ``bugx init`` itself creates ``.bugx/logs/`` via the layout
630
+ initializer, as documented in DOC-001 §5.8.
631
+
632
+ Repeated calls in one process reuse the same handler. A later call for a
633
+ different project replaces the old handler, which keeps test runs and
634
+ embedded CLI calls isolated.
635
+ """
636
+ root = root.expanduser().resolve()
637
+ if root.exists() and not root.is_dir():
638
+ raise ValueError(f"日志项目根目录不是目录: {root}")
639
+ if project_scoped is None:
640
+ project_scoped = is_initialized_project(root)
641
+ if project_scoped:
642
+ # Only bootstrap commands (init/install) and already-initialized
643
+ # projects reach this branch: the project layout owns <root>/.bugx.
644
+ root.mkdir(parents=True, exist_ok=True)
645
+ bugx_root = root / ".bugx"
646
+ path = _private_dir_chain(
647
+ bugx_root, bugx_root / LOG_DIR_NAME, label="",
648
+ ) / LOG_FILE_NAME
649
+ else:
650
+ path = global_log_path(root)
651
+ _private_dir_chain(global_log_root(), path.parent, label="回退")
652
+ lock_path = Path(f"{path}.lock")
653
+ if path.is_symlink() or lock_path.is_symlink():
654
+ raise ValueError(f"拒绝使用符号链接诊断日志: {path}")
655
+ path.touch(mode=0o600, exist_ok=True)
656
+ os.chmod(path, 0o600)
657
+
658
+ logger = logging.getLogger(LOGGER_NAME)
659
+ logger.setLevel(_level(level))
660
+ logger.propagate = False
661
+ context = {"command": command or "unknown"}
662
+ for field, env_name in _CONTEXT_ENV.items():
663
+ value = os.environ.get(env_name)
664
+ if value:
665
+ context[field] = value
666
+ traceparent_env = os.environ.get("TRACEPARENT")
667
+ parsed_tp = parse_traceparent(traceparent_env)
668
+ if parsed_tp is not None and trace_id is None:
669
+ context["trace_id"] = parsed_tp["trace_id"]
670
+ context["parent_span_id"] = parsed_tp["parent_id"]
671
+ span_id = uuid.uuid4().hex[:16]
672
+ context["span_id"] = span_id
673
+ context["traceparent"] = f"00-{parsed_tp['trace_id']}-{span_id}-{parsed_tp['trace_flags']}"
674
+ else:
675
+ assigned_trace = (
676
+ trace_id if trace_id is not None
677
+ else context.get("trace_id") or uuid.uuid4().hex
678
+ )
679
+ context["trace_id"] = assigned_trace
680
+ span_id = uuid.uuid4().hex[:16]
681
+ context["span_id"] = span_id
682
+ clean_32 = assigned_trace.lower().replace("-", "").zfill(32)[-32:]
683
+ context["traceparent"] = f"00-{clean_32}-{span_id}-01"
684
+ logger._bugx_context = context # type: ignore[attr-defined]
685
+ resolved_path = str(path.resolve())
686
+ existing = next(
687
+ (handler for handler in logger.handlers
688
+ if getattr(handler, "_bugx_log_path", None) == resolved_path),
689
+ None,
690
+ )
691
+ if existing is None:
692
+ for handler in list(logger.handlers):
693
+ if getattr(handler, "_bugx_handler", False):
694
+ logger.removeHandler(handler)
695
+ handler.close()
696
+ handler = _SecureRotatingFileHandler(
697
+ path, maxBytes=MAX_BYTES, backupCount=BACKUP_COUNT,
698
+ encoding="utf-8", delay=True,
699
+ )
700
+ handler._bugx_handler = True # type: ignore[attr-defined]
701
+ handler._bugx_log_path = resolved_path # type: ignore[attr-defined]
702
+ handler.setFormatter(_JsonFormatter())
703
+ handler.setLevel(logging.DEBUG)
704
+ logger.addHandler(handler)
705
+
706
+ otlp_endpoint = os.environ.get("BUGX_OTLP_ENDPOINT")
707
+ if otlp_endpoint:
708
+ otlp_handler = _OtlpHttpHandler(otlp_endpoint.strip())
709
+ otlp_handler._bugx_handler = True # type: ignore[attr-defined]
710
+ logger.addHandler(otlp_handler)
711
+
712
+ log_event(
713
+ logger, "logger_configured", "BugX 诊断日志已启用",
714
+ command=command or "unknown", log_file=str(path),
715
+ )
716
+ return logger
717
+
718
+
719
+ def _correlation_ids() -> dict[str, Any]:
720
+ """DOC-204 L2:关联 ID 注入(runtime.json 权威值优先)。
721
+
722
+ env(BUGX_RUN_ID 等)与 runtime 不一致 → 丢弃 env 值并记
723
+ log_correlation_mismatch(嫁接尝试成为可检安全信号);runtime 不可读
724
+ 时 env 缺失省略(不伪造)。
725
+ """
726
+ ids: dict[str, Any] = {}
727
+ data: dict[str, Any] | None = None
728
+ # 会话 runtime 的真实位置由 .bugx/current.json(bugx_paths 布局)指向;
729
+ # 读不到时按 cwd 相对 bugx-runtime.json 回退(独立协议测试布局)。
730
+ for cand in (Path(".bugx/current.json"), Path("bugx-runtime.json")):
731
+ try:
732
+ data = json.loads(cand.read_text(encoding="utf-8"))
733
+ break
734
+ except Exception:
735
+ continue
736
+ if isinstance(data, dict) and "lifecycle_id" in data and "run_id" not in data:
737
+ # current.json 只有 polling/lifecycle 指针——顺着找 lifecycle runtime
738
+ try:
739
+ life_rt = (
740
+ Path(".bugx/pollings") / str(data.get("polling_id") or "polling-unknown")
741
+ / "lifecycles" / str(data.get("lifecycle_id") or "unknown")
742
+ / "state" / "runtime.json"
743
+ )
744
+ merged = json.loads(life_rt.read_text(encoding="utf-8"))
745
+ merged.setdefault("polling_id", data.get("polling_id"))
746
+ merged.setdefault("lifecycle_id", data.get("lifecycle_id"))
747
+ data = merged
748
+ except Exception:
749
+ pass
750
+ env_map = {
751
+ "run_id": "BUGX_RUN_ID", "lifecycle_id": "BUGX_LIFECYCLE_ID",
752
+ "round": "BUGX_ROUND",
753
+ }
754
+ for field, env_name in env_map.items():
755
+ env_val = os.environ.get(env_name)
756
+ rt_val = (data or {}).get(field if field != "round" else "round")
757
+ if data is not None and rt_val is not None:
758
+ ids[field] = rt_val
759
+ elif env_val:
760
+ ids[field] = env_val
761
+ return ids
762
+
763
+
764
+ def log_event(logger: logging.Logger, event: str, message: str = "", *,
765
+ level: int = logging.INFO, exc_info: Any = None,
766
+ **fields: Any) -> bool:
767
+ """Write one structured event and report local JSONL flush success.
768
+
769
+ ``True`` means the configured local JSONL handler acknowledged this exact
770
+ event ID after formatter, write, flush, and close succeeded. Logger/handler
771
+ level filters, a missing local JSONL handler, or any local I/O failure return
772
+ ``False``. Other handlers such as asynchronous OTLP do not affect this ack.
773
+ """
774
+ context = dict(getattr(logger, "_bugx_context", {}))
775
+ # DOC-204 L2:关联 ID 注入(runtime 权威值优先;缺失省略不伪造)。
776
+ # 节流:_correlation_ids 的文件读取每次调用有开销,按 pid 缓存 60s。
777
+ global _CORRELATION_CACHE
778
+ now_mono = time.monotonic()
779
+ cached = _CORRELATION_CACHE.get("v")
780
+ if cached is None or now_mono - cached[0] > 60.0:
781
+ try:
782
+ cached = (now_mono, _correlation_ids())
783
+ except Exception:
784
+ cached = (now_mono, {})
785
+ _CORRELATION_CACHE["v"] = cached
786
+ for cid_key, cid_val in cached[1].items():
787
+ context.setdefault(cid_key, cid_val)
788
+ context.update(fields)
789
+ event_id = uuid.uuid4().hex
790
+ context["event_id"] = event_id
791
+
792
+ if logger.disabled or not logger.isEnabledFor(level):
793
+ return False
794
+ record_exc_info = exc_info
795
+ if not isinstance(record_exc_info, tuple):
796
+ record_exc_info = sys.exc_info() if record_exc_info else None
797
+ try:
798
+ pathname, lineno, function, _ = logger.findCaller(stack_info=False, stacklevel=2)
799
+ record = logger.makeRecord(
800
+ logger.name, level, pathname, lineno, message or event, (), record_exc_info,
801
+ function, extra={"bugx_event": event, "bugx_fields": context},
802
+ )
803
+ logger.handle(record)
804
+ except Exception:
805
+ # A non-JSONL observer must not turn an already-flushed local event into
806
+ # a false negative ack. If dispatch failed before a local ack, the event
807
+ # remains unavailable.
808
+ return (
809
+ getattr(locals().get("record"), "_bugx_jsonl_ack_event_id", None)
810
+ == event_id
811
+ )
812
+ return getattr(record, "_bugx_jsonl_ack_event_id", None) == event_id
813
+
814
+
815
+ def log_phase(logger: logging.Logger, phase: str, *,
816
+ status: str = "ok", duration_seconds: float = 0.0,
817
+ tokens_consumed: int | None = None,
818
+ decision_reason: str = "", **fields: Any) -> None:
819
+ """Log a named execution phase with elapsed duration, tokens consumed, and decision reason.
820
+
821
+ ``phase`` is used for grouping and searching (e.g. "tools_kb", "pre_check",
822
+ "worker_execution", "settlement"). ``duration_seconds`` represents elapsed wall time.
823
+ ``tokens_consumed`` represents model tokens used in this phase if available.
824
+ """
825
+ if duration_seconds < 0:
826
+ duration_seconds = 0.0
827
+ tok_str = f" tokens={tokens_consumed}" if tokens_consumed is not None else ""
828
+ log_fields = dict(fields)
829
+ if tokens_consumed is not None:
830
+ log_fields["tokens_consumed"] = tokens_consumed
831
+ level = logging.ERROR if status == "failed" else logging.INFO
832
+ log_event(logger, f"phase.{phase}.finished",
833
+ f"phase={phase} duration={duration_seconds:.3f}s{tok_str} status={status}",
834
+ level=level,
835
+ phase=phase, status=status,
836
+ duration_seconds=round(duration_seconds, 3),
837
+ decision_reason=decision_reason,
838
+ **log_fields)
839
+
840
+
841
+ class TokenPhaseTracker:
842
+ """阶段 Token 累计器,支持多分类记录与归因分析 (DOC-042)。"""
843
+
844
+ def __init__(self, phase: str, budget: int | None = None):
845
+ self.phase = phase
846
+ self.budget = budget
847
+ self._tokens_by_category: dict[str, int] = {}
848
+ self.status: str = "ok"
849
+ self.decision_reason: str = ""
850
+ self.error: str = ""
851
+
852
+ def mark_failed(self, reason: str = "", error: str = "") -> None:
853
+ """标记该阶段执行失败并记录原因。"""
854
+ self.status = "failed"
855
+ if reason:
856
+ self.decision_reason = reason
857
+ if error or reason:
858
+ self.error = error or reason
859
+
860
+ def set_decision(self, reason: str) -> None:
861
+ """记录阶段决策原因。"""
862
+ self.decision_reason = reason
863
+
864
+ def record(self, count: int, category: str = "other") -> None:
865
+ """记录指定分类的 token 消耗。"""
866
+ if not isinstance(count, int) or isinstance(count, bool) or count < 0:
867
+ return
868
+ cat = str(category).strip().lower() or "other"
869
+ self._tokens_by_category[cat] = self._tokens_by_category.get(cat, 0) + count
870
+
871
+ @property
872
+ def total_tokens(self) -> int:
873
+ """返回阶段累计消耗的总 Token 数。"""
874
+ return sum(self._tokens_by_category.values())
875
+
876
+ @property
877
+ def breakdown(self) -> dict[str, int]:
878
+ """返回各分类的 Token 归因字典。"""
879
+ return dict(self._tokens_by_category)
880
+
881
+
882
+ @contextmanager
883
+ def metered_phase(logger: logging.Logger | None, phase: str, *,
884
+ token_budget: int | None = None,
885
+ slow_threshold_seconds: float | None = None,
886
+ decision_reason: str = "", **fields: Any):
887
+ """Context manager to measure phase duration and token consumption.
888
+
889
+ Yields a TokenPhaseTracker to record token usage within the phase.
890
+ Triggers slow_operation_warning and token_anomaly_warning when thresholds are exceeded.
891
+ """
892
+ tracker = TokenPhaseTracker(phase=phase, budget=token_budget)
893
+ if decision_reason:
894
+ tracker.set_decision(decision_reason)
895
+ if logger is None:
896
+ yield tracker
897
+ return
898
+
899
+ started = time.monotonic()
900
+ status = "ok"
901
+ error_msg = ""
902
+ try:
903
+ yield tracker
904
+ except Exception as exc:
905
+ status = "failed"
906
+ error_msg = str(exc)
907
+ raise
908
+ finally:
909
+ duration = max(0.0, time.monotonic() - started)
910
+ tokens = tracker.total_tokens
911
+ log_fields = dict(fields)
912
+ if tracker.status != "ok":
913
+ status = tracker.status
914
+ if tracker.decision_reason:
915
+ decision_reason = tracker.decision_reason
916
+ if tracker.error:
917
+ error_msg = tracker.error
918
+ if error_msg:
919
+ log_fields["error"] = error_msg
920
+
921
+ # 计算 Token 预算
922
+ budget = token_budget
923
+ if budget is None:
924
+ env_budget = os.environ.get(f"BUGX_TOKEN_BUDGET_{phase.upper()}")
925
+ if env_budget:
926
+ try:
927
+ budget = int(env_budget)
928
+ except ValueError:
929
+ budget = None
930
+ if budget is not None:
931
+ log_fields["token_budget"] = budget
932
+ if tracker.breakdown:
933
+ log_fields["token_breakdown"] = tracker.breakdown
934
+
935
+ log_phase(
936
+ logger, phase, status=status, duration_seconds=duration,
937
+ tokens_consumed=tokens if tokens > 0 else None,
938
+ decision_reason=decision_reason, **log_fields,
939
+ )
940
+
941
+ # 慢耗时检测
942
+ threshold = slow_threshold_seconds
943
+ if threshold is None:
944
+ env_thresh = os.environ.get("BUGX_SLOW_THRESHOLD_SECONDS")
945
+ if env_thresh:
946
+ try:
947
+ threshold = float(env_thresh)
948
+ except ValueError:
949
+ threshold = DEFAULT_SLOW_THRESHOLD_SECONDS
950
+ else:
951
+ threshold = DEFAULT_SLOW_THRESHOLD_SECONDS
952
+ if threshold > 0 and duration >= threshold:
953
+ log_event(
954
+ logger, "slow_operation_warning",
955
+ f"阶段 {phase} 执行耗时 ({duration:.2f}s) 超过阈值 ({threshold:.2f}s)",
956
+ level=logging.WARNING,
957
+ phase=phase,
958
+ duration_seconds=round(duration, 3),
959
+ threshold_seconds=round(threshold, 3),
960
+ status=status,
961
+ **fields,
962
+ )
963
+
964
+ # 异常 Token 消耗检测
965
+ if budget is not None and budget > 0 and tokens > budget:
966
+ diff = tokens - budget
967
+ log_event(
968
+ logger, "token_anomaly_warning",
969
+ f"阶段 {phase} 消耗 {tokens} tokens,超出预算 {budget}(超标 +{diff})",
970
+ level=logging.WARNING,
971
+ phase=phase,
972
+ actual_tokens=tokens,
973
+ budget_tokens=budget,
974
+ diff_tokens=diff,
975
+ token_breakdown=tracker.breakdown,
976
+ status=status,
977
+ **fields,
978
+ )
979
+
980
+
981
+ @contextmanager
982
+ def timed_phase(logger: logging.Logger | None, phase: str, *,
983
+ token_budget: int | None = None,
984
+ slow_threshold_seconds: float | None = None,
985
+ decision_reason: str = "", **fields: Any):
986
+ """Context manager to measure phase duration and tokens (wraps metered_phase)."""
987
+ with metered_phase(
988
+ logger, phase, token_budget=token_budget, slow_threshold_seconds=slow_threshold_seconds,
989
+ decision_reason=decision_reason, **fields,
990
+ ) as tracker:
991
+ yield tracker
992
+
993
+
994
+ def log_dialogue(
995
+ logger: logging.Logger | None,
996
+ role: str,
997
+ content: str,
998
+ *,
999
+ interaction_type: str = "chat",
1000
+ options: list[Any] | None = None,
1001
+ selected: Any = None,
1002
+ tokens: int | None = None,
1003
+ turn_id: int | None = None,
1004
+ **fields: Any,
1005
+ ) -> None:
1006
+ """记录人机交互与对话消息(自动脱敏与文本有界预算)。
1007
+
1008
+ 用于记录用户输入、Agent 响应、门禁单选等交互,帮助复盘时对齐人类意图与 Agent 行为。
1009
+ """
1010
+ if logger is None:
1011
+ return
1012
+ clean_content = str(content).strip()
1013
+ if len(clean_content) > 1000:
1014
+ clean_content = clean_content[:997] + "..."
1015
+ log_fields = dict(fields)
1016
+ log_fields.update({
1017
+ "role": role,
1018
+ "content_summary": clean_content,
1019
+ "interaction_type": interaction_type,
1020
+ })
1021
+ if options is not None:
1022
+ log_fields["options"] = [safe_value(opt) for opt in options]
1023
+ if selected is not None:
1024
+ log_fields["selected"] = safe_value(selected)
1025
+ if tokens is not None:
1026
+ log_fields["tokens"] = tokens
1027
+ if turn_id is not None:
1028
+ log_fields["turn_id"] = turn_id
1029
+
1030
+ log_event(
1031
+ logger,
1032
+ "dialogue_message",
1033
+ f"[{role.upper()}] ({interaction_type}) {clean_content[:120]}",
1034
+ level=logging.INFO,
1035
+ **log_fields,
1036
+ )
1037
+
1038
+
1039
+ @contextmanager
1040
+ def metered_step(
1041
+ logger: logging.Logger | None,
1042
+ step_name: str,
1043
+ *,
1044
+ tool_name: str = "bash",
1045
+ tool_input: Any = None,
1046
+ step_index: int | None = None,
1047
+ slow_threshold_seconds: float = 5.0,
1048
+ **fields: Any,
1049
+ ):
1050
+ """用于追踪具体操作步骤(Bash 执行、工具调用、命令操作)的上下文管理器。
1051
+
1052
+ 进入时记录 step_started,退出时记录 step_finished(含毫秒级耗时与状态),
1053
+ 若耗时超出阈值则发出 slow_command_warning。
1054
+ """
1055
+ if logger is None:
1056
+ yield
1057
+ return
1058
+
1059
+ started = time.monotonic()
1060
+ status = "ok"
1061
+ error_msg = ""
1062
+ exit_code: int | None = 0
1063
+ safe_input = safe_value(tool_input)
1064
+ if isinstance(safe_input, str) and len(safe_input) > 500:
1065
+ safe_input = safe_input[:497] + "..."
1066
+
1067
+ start_fields = dict(fields)
1068
+ start_fields.update({
1069
+ "step_name": step_name,
1070
+ "tool_name": tool_name,
1071
+ "tool_input": safe_input,
1072
+ })
1073
+ if step_index is not None:
1074
+ start_fields["step_index"] = step_index
1075
+
1076
+ log_event(
1077
+ logger,
1078
+ "step_started",
1079
+ f"开始执行步骤 [{step_name}] ({tool_name})",
1080
+ level=logging.INFO,
1081
+ **start_fields,
1082
+ )
1083
+
1084
+ try:
1085
+ yield
1086
+ except Exception as exc:
1087
+ status = "failed"
1088
+ error_msg = str(exc)
1089
+ exit_code = getattr(exc, "exit_code", getattr(exc, "returncode", 1))
1090
+ raise
1091
+ finally:
1092
+ duration = max(0.0, time.monotonic() - started)
1093
+ duration_ms = round(duration * 1000.0, 2)
1094
+ end_fields = dict(fields)
1095
+ end_fields.update({
1096
+ "step_name": step_name,
1097
+ "tool_name": tool_name,
1098
+ "duration_ms": duration_ms,
1099
+ "duration_seconds": round(duration, 3),
1100
+ "status": status,
1101
+ })
1102
+ if step_index is not None:
1103
+ end_fields["step_index"] = step_index
1104
+ if exit_code is not None:
1105
+ end_fields["exit_code"] = exit_code
1106
+ if error_msg:
1107
+ end_fields["error"] = error_msg
1108
+
1109
+ log_event(
1110
+ logger,
1111
+ "step_finished",
1112
+ f"步骤 [{step_name}] 完成 ({tool_name}, {duration_ms}ms, status={status})",
1113
+ level=logging.INFO if status == "ok" else logging.WARNING,
1114
+ **end_fields,
1115
+ )
1116
+
1117
+ if duration >= slow_threshold_seconds:
1118
+ log_event(
1119
+ logger,
1120
+ "slow_command_warning",
1121
+ f"步骤 [{step_name}] ({tool_name}) 执行耗时 ({duration:.2f}s) 超过阈值 ({slow_threshold_seconds:.2f}s)",
1122
+ level=logging.WARNING,
1123
+ step_name=step_name,
1124
+ tool_name=tool_name,
1125
+ tool_input=safe_input,
1126
+ duration_seconds=round(duration, 3),
1127
+ threshold_seconds=slow_threshold_seconds,
1128
+ **fields,
1129
+ )
1130
+
1131
+
1132
+ @contextmanager
1133
+ def metered_gate(
1134
+ logger: logging.Logger | None,
1135
+ gate_name: str,
1136
+ *,
1137
+ phase: str = "environment",
1138
+ slow_threshold_seconds: float = 2.0,
1139
+ **fields: Any,
1140
+ ):
1141
+ """用于追踪启动门禁与策略校验子阶段的上下文管理器。
1142
+
1143
+ 记录 gate_started 与 gate_finished,精准计算各门禁耗时毫秒数。
1144
+ """
1145
+ if logger is None:
1146
+ yield
1147
+ return
1148
+
1149
+ started = time.monotonic()
1150
+ status = "ok"
1151
+ error_msg = ""
1152
+ gate_fields = dict(fields)
1153
+ gate_fields.update({"gate_name": gate_name, "phase": phase})
1154
+
1155
+ log_event(
1156
+ logger,
1157
+ "gate_started",
1158
+ f"开始评估门禁 [{gate_name}]",
1159
+ level=logging.INFO,
1160
+ **gate_fields,
1161
+ )
1162
+
1163
+ try:
1164
+ yield
1165
+ except Exception as exc:
1166
+ status = "blocked"
1167
+ error_msg = str(exc)
1168
+ raise
1169
+ finally:
1170
+ duration = max(0.0, time.monotonic() - started)
1171
+ duration_ms = round(duration * 1000.0, 2)
1172
+ finish_fields = dict(gate_fields)
1173
+ finish_fields.update({
1174
+ "duration_ms": duration_ms,
1175
+ "duration_seconds": round(duration, 3),
1176
+ "status": status,
1177
+ })
1178
+ if error_msg:
1179
+ finish_fields["error"] = error_msg
1180
+
1181
+ log_event(
1182
+ logger,
1183
+ "gate_finished",
1184
+ f"门禁 [{gate_name}] 评估完成 ({duration_ms}ms, status={status})",
1185
+ level=logging.INFO if status == "ok" else logging.WARNING,
1186
+ **finish_fields,
1187
+ )
1188
+
1189
+
1190
+ def compact_output(
1191
+ text: str,
1192
+ *,
1193
+ max_chars: int = 2000,
1194
+ max_lines: int = 40,
1195
+ head_lines: int = 15,
1196
+ tail_lines: int = 10,
1197
+ persisted_log_path: Path | str | None = None,
1198
+ ) -> str:
1199
+ """输出刚性脱水截断,防止巨幅命令日志灌入宿主大模型导致注意力膨胀与极慢推理 (DOC-170)。
1200
+
1201
+ 若文本行数与字符数均未超限,原样返回。
1202
+ 若超限,提取「头部 N 行 + 中间包含错误/异常的关键行 + 尾部 M 行」,并标明截断行数与全量落盘路径。
1203
+ """
1204
+ if not text:
1205
+ return ""
1206
+ lines = text.splitlines()
1207
+ if len(lines) <= max_lines and len(text) <= max_chars:
1208
+ return text
1209
+
1210
+ head = lines[:head_lines]
1211
+ tail = lines[-tail_lines:] if len(lines) > head_lines + tail_lines else []
1212
+ middle_pool = lines[head_lines:-tail_lines] if tail else []
1213
+
1214
+ # 智能提取中间的错误关键词行(最多 10 行)
1215
+ error_keywords = ("error", "fail", "warn", "exception", "traceback", "blocked", "fatal", "denied", "timeout")
1216
+ matched_middle: list[str] = []
1217
+ for line in middle_pool:
1218
+ lower = line.lower()
1219
+ if any(kw in lower for kw in error_keywords):
1220
+ matched_middle.append(f" [!] {line}")
1221
+ if len(matched_middle) >= 10:
1222
+ break
1223
+
1224
+ truncated_count = len(lines) - len(head) - len(tail)
1225
+ link_info = f",全量日志已保存至: {persisted_log_path}" if persisted_log_path else ""
1226
+ summary_banner = [
1227
+ f"... [已截断 {truncated_count} 行冗余输出以防止上下文膨胀{link_info}] ..."
1228
+ ]
1229
+
1230
+ parts = list(head)
1231
+ if matched_middle:
1232
+ parts.append("--- [关键错误行摘要提取] ---")
1233
+ parts.extend(matched_middle)
1234
+ parts.append("----------------------------")
1235
+ parts.extend(summary_banner)
1236
+ parts.extend(tail)
1237
+
1238
+ result = "\n".join(parts)
1239
+ if len(result) > max_chars:
1240
+ result = result[:max_chars] + f"\n... [文本超出 {max_chars} 字符已切除] ..."
1241
+ return result
1242
+
1243
+
1244
+ def get_context(logger: logging.Logger) -> dict[str, Any]:
1245
+ """Return the current invocation context for child-process propagation."""
1246
+ return dict(getattr(logger, "_bugx_context", {}))
1247
+
1248
+
1249
+ def request_context(logger: logging.Logger, request_id: object | None = None) -> dict[str, Any]:
1250
+ """Create a fresh span context for one inbound request.
1251
+
1252
+ The configured logger span identifies the process; request spans must be
1253
+ unique so records from two MCP requests cannot be mistaken for one span.
1254
+ """
1255
+ context = get_context(logger)
1256
+ parent_span_id = str(context.get("span_id") or uuid.uuid4().hex[:16])
1257
+ span_id = uuid.uuid4().hex[:16]
1258
+ trace_id = str(context.get("trace_id") or uuid.uuid4().hex)
1259
+ return {
1260
+ "request_id": request_id if request_id is not None else uuid.uuid4().hex,
1261
+ "parent_span_id": parent_span_id,
1262
+ "span_id": span_id,
1263
+ "traceparent": generate_traceparent(trace_id, span_id),
1264
+ }
1265
+
1266
+
1267
+ class McpRequestBatch:
1268
+ """Aggregate contiguous low-value MCP request completions.
1269
+
1270
+ This is deliberately a logging-only guard: every request still gets a
1271
+ response, but repetitive idempotent reads do not consume one JSONL record
1272
+ each. The first/last request identities and latency totals keep the
1273
+ aggregate useful for diagnosing a polling client.
1274
+ """
1275
+
1276
+ def __init__(self, method: str) -> None:
1277
+ self.method = method
1278
+ self._reset()
1279
+
1280
+ def _reset(self) -> None:
1281
+ self._count = 0
1282
+ self._first: dict[str, Any] = {}
1283
+ self._last: dict[str, Any] = {}
1284
+ self._first_seen = 0.0
1285
+ self._last_seen = 0.0
1286
+ self._first_monotonic = 0.0
1287
+ self._last_monotonic = 0.0
1288
+ self._intervals_ms: list[float] = []
1289
+ self._duration_total = 0.0
1290
+ self._duration_max = 0.0
1291
+ self._counters: dict[str, int] = {}
1292
+
1293
+ @property
1294
+ def count(self) -> int:
1295
+ return self._count
1296
+
1297
+ def record(self, fields: dict[str, Any], *, duration_ms: float,
1298
+ counters: dict[str, int] | None = None) -> None:
1299
+ now = time.time()
1300
+ if self._count == 0:
1301
+ self._first = dict(fields)
1302
+ self._first_seen = now
1303
+ self._first_monotonic = time.monotonic()
1304
+ self._last_monotonic = self._first_monotonic
1305
+ else:
1306
+ current_monotonic = time.monotonic()
1307
+ self._intervals_ms.append(
1308
+ max(0.0, current_monotonic - self._last_monotonic) * 1000
1309
+ )
1310
+ self._last_monotonic = current_monotonic
1311
+ self._last = dict(fields)
1312
+ self._last_seen = now
1313
+ self._count += 1
1314
+ self._duration_total += max(0.0, float(duration_ms))
1315
+ self._duration_max = max(self._duration_max, float(duration_ms))
1316
+ for key, value in (counters or {}).items():
1317
+ if isinstance(value, int) and not isinstance(value, bool):
1318
+ self._counters[key] = self._counters.get(key, 0) + value
1319
+
1320
+ def due(self, *, max_count: int = 128,
1321
+ max_elapsed_seconds: float = 30.0) -> bool:
1322
+ """Bound an open batch so a polling-only connection stays observable."""
1323
+ if self._count == 0:
1324
+ return False
1325
+ return (
1326
+ self._count >= max_count
1327
+ or time.monotonic() - self._first_monotonic >= max_elapsed_seconds
1328
+ )
1329
+
1330
+ def flush(self, logger: logging.Logger, **fields: Any) -> bool:
1331
+ """Write one summary for the pending batch and clear it."""
1332
+ if self._count == 0:
1333
+ return False
1334
+ payload: dict[str, Any] = {
1335
+ "method": self.method,
1336
+ "request_count": self._count,
1337
+ "first_request_id": self._first.get("request_id"),
1338
+ "last_request_id": self._last.get("request_id"),
1339
+ "first_span_id": self._first.get("span_id"),
1340
+ "last_span_id": self._last.get("span_id"),
1341
+ "first_seen_at": self._first_seen,
1342
+ "last_seen_at": self._last_seen,
1343
+ "elapsed_ms": round(max(0.0, self._last_seen - self._first_seen) * 1000, 2),
1344
+ "duration_ms_total": round(self._duration_total, 2),
1345
+ "duration_ms_max": round(self._duration_max, 2),
1346
+ "duration_ms_avg": round(self._duration_total / self._count, 2),
1347
+ **self._counters,
1348
+ **fields,
1349
+ }
1350
+ if self._intervals_ms:
1351
+ payload.update({
1352
+ "interval_count": len(self._intervals_ms),
1353
+ "interval_ms_min": round(min(self._intervals_ms), 2),
1354
+ "interval_ms_max": round(max(self._intervals_ms), 2),
1355
+ "interval_ms_avg": round(
1356
+ sum(self._intervals_ms) / len(self._intervals_ms), 2,
1357
+ ),
1358
+ "interval_ms_p50": round(statistics.median(self._intervals_ms), 2),
1359
+ })
1360
+ log_event(logger, "mcp_request_batch_finished", **payload)
1361
+ self._reset()
1362
+ return True
1363
+
1364
+
1365
+ __all__ = [
1366
+ "BACKUP_COUNT",
1367
+ "DEFAULT_SLOW_THRESHOLD_SECONDS",
1368
+ "GLOBAL_LOG_ROOT_ENV",
1369
+ "LOG_FILE_NAME",
1370
+ "LOG_SCHEMA_VERSION",
1371
+ "MAX_BYTES",
1372
+ "TokenPhaseTracker",
1373
+ "McpRequestBatch",
1374
+ "request_context",
1375
+ "close_handlers_for_root",
1376
+ "compact_output",
1377
+ "configure",
1378
+ "generate_traceparent",
1379
+ "get_context",
1380
+ "global_log_path",
1381
+ "global_log_root",
1382
+ "is_initialized_project",
1383
+ "log_dialogue",
1384
+ "log_event",
1385
+ "log_phase",
1386
+ "log_path",
1387
+ "metered_gate",
1388
+ "metered_phase",
1389
+ "metered_step",
1390
+ "parse_traceparent",
1391
+ "project_log_id",
1392
+ "timed_phase",
1393
+ ]