bugx-cli 0.1.0 → 0.1.2

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 (338) hide show
  1. package/README.md +193 -185
  2. package/core/README.md +2 -2
  3. package/core/agent/README.md +2 -1
  4. package/core/agent/agent_artifacts.py +8 -6
  5. package/core/agent/agent_eval.py +136 -54
  6. package/core/agent/agent_execution.py +218 -52
  7. package/core/agent/agent_orchestrator.py +14 -8
  8. package/core/agent/agent_targets.py +8 -2
  9. package/core/agent/feature_baseline.py +150 -0
  10. package/core/assets/README.md +3 -2
  11. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  12. package/core/assets/axe-core/LICENSE.txt +362 -0
  13. package/core/assets/axe-core/UPSTREAM.md +10 -0
  14. package/core/assets/axe-core/axe.min.js +12 -0
  15. package/core/assets/bugx-hero-en.svg +74 -0
  16. package/core/assets/bugx-hero-zh.svg +74 -0
  17. package/core/assets/bugx-social-preview.svg +71 -0
  18. package/core/assets/bugx-wechat-group.png +0 -0
  19. package/core/assets/codex.png +0 -0
  20. package/core/assets/dsh.png +0 -0
  21. package/core/assets/webui-chatgpt.jpg +0 -0
  22. package/core/assets/webui-session.jpg +0 -0
  23. package/core/assets/webui-skills.jpg +0 -0
  24. package/core/assets/webui-studio.jpg +0 -0
  25. package/core/assets/webui-zcode.jpg +0 -0
  26. package/core/assets/zcode.png +0 -0
  27. package/core/audit_packs/README.md +2 -0
  28. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  29. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  30. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  31. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  32. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  33. package/core/audit_packs/pitfalls/python_web.json +82 -0
  34. package/core/autonomous_cve/SPEC.md +1 -1
  35. package/core/autonomous_cve/attack_graph_store.py +152 -106
  36. package/core/autonomous_cve/behavior_graph.py +8 -2
  37. package/core/autonomous_cve/verifier.py +4 -1
  38. package/core/bugx.md +1 -1
  39. package/core/bugx_paths.py +43 -8
  40. package/core/cli-help.txt +66 -0
  41. package/core/cloud_sync/SPEC.md +1 -1
  42. package/core/cloud_sync/cloud_client.py +81 -11
  43. package/core/cloud_sync/cloud_onboard.py +42 -1
  44. package/core/cloud_sync/consent.py +33 -3
  45. package/core/cloud_sync/flywheel_client.py +186 -15
  46. package/core/cloud_sync/network_transport.py +24 -3
  47. package/core/cloud_sync/sensitive_filter.py +2 -2
  48. package/core/cloud_sync/sync_push.py +12 -10
  49. package/core/contracts/AGENT_GUIDE.md +6 -9
  50. package/core/contracts/README.md +2 -2
  51. package/core/contracts/bugx-runtime-contract.md +1 -1
  52. package/core/contracts/bugx-worker.md +1 -1
  53. package/core/contracts/engine_gap_contracts.py +86 -3
  54. package/core/coverage/coverage_discovery.py +599 -29
  55. package/core/coverage/coverage_evidence.py +47 -0
  56. package/core/coverage/coverage_forensics.py +9 -0
  57. package/core/coverage/coverage_validate.py +6 -1
  58. package/core/dev_harness/SPEC.md +1 -1
  59. package/core/engine-integrity.json +670 -442
  60. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  61. package/core/fuzzing/differential_oracle.py +562 -27
  62. package/core/fuzzing/fuzz_input.py +109 -6
  63. package/core/fuzzing/stateful_fuzzer.py +72 -0
  64. package/core/governance/secret_redactor.py +22 -10
  65. package/core/host_acp/SPEC.md +1 -1
  66. package/core/host_acp/__init__.py +4 -4
  67. package/core/host_acp/claude.py +59 -1
  68. package/core/host_acp/cline.py +64 -1
  69. package/core/host_acp/codex.py +56 -1
  70. package/core/host_acp/dsh.py +59 -1
  71. package/core/host_acp/opencode.py +56 -1
  72. package/core/host_acp/pi.py +59 -1
  73. package/core/host_acp/zcode.py +59 -1
  74. package/core/host_runtime/SPEC.md +1 -1
  75. package/core/host_runtime/adapters.py +1 -1
  76. package/core/host_runtime/cline.py +13 -0
  77. package/core/host_runtime/host_evaluators.py +44 -4
  78. package/core/host_runtime/host_probe.py +1 -1
  79. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  80. package/core/host_runtime/host_registry.py +15 -8
  81. package/core/host_runtime/mcp_registry_gate.py +12 -1
  82. package/core/host_runtime/pi.py +102 -0
  83. package/core/host_runtime/provider_facts.py +66 -0
  84. package/core/hosts/SPEC.md +1 -1
  85. package/core/hosts/__init__.py +6 -2
  86. package/core/hosts/_dsh_usage.py +1 -1
  87. package/core/hosts/base.py +32 -4
  88. package/core/hosts/claude.py +55 -0
  89. package/core/hosts/cline.py +6 -2
  90. package/core/hosts/codex.py +58 -0
  91. package/core/hosts/dsh.py +9 -1
  92. package/core/hosts/opencode.py +6 -6
  93. package/core/hosts/pi.py +159 -2
  94. package/core/infra/README.md +4 -2
  95. package/core/infra/__init__.py +2 -0
  96. package/core/infra/build_info.py +22 -3
  97. package/core/infra/client_metadata.py +1 -1
  98. package/core/infra/json_utils.py +22 -0
  99. package/core/launch_phases/README.md +6 -3
  100. package/core/launch_phases/SPEC.md +1 -1
  101. package/core/launch_phases/common.py +21 -2
  102. package/core/launch_phases/finding_confirm_phase.py +170 -5
  103. package/core/launch_phases/finding_settlement.py +188 -1
  104. package/core/launch_phases/judge_phase.py +69 -12
  105. package/core/launch_phases/orchestrator_controls.py +11 -7
  106. package/core/launch_phases/post_coverage_sync.py +9 -2
  107. package/core/launch_phases/post_phase.py +144 -8
  108. package/core/launch_phases/post_receipt.py +12 -1
  109. package/core/launch_phases/pre_phase.py +3 -3
  110. package/core/launch_phases/pre_recon_scout.py +66 -36
  111. package/core/launch_phases/pre_state_builder.py +23 -176
  112. package/core/launch_phases/report_sharing.py +3 -7
  113. package/core/launch_phases/round_orchestrator.py +129 -58
  114. package/core/launch_phases/semantic_recon.py +545 -0
  115. package/core/launch_phases/session_runtime.py +56 -9
  116. package/core/launch_phases/startup_gates.py +36 -8
  117. package/core/launch_phases/startup_interaction.py +68 -12
  118. package/core/launch_phases/startup_version_gate.py +13 -3
  119. package/core/launch_phases/supervisor_bridge.py +46 -17
  120. package/core/launch_phases/supervisor_coverage.py +8 -2
  121. package/core/launch_phases/supervisor_degraded.py +1 -9
  122. package/core/launch_phases/verify_loop.py +767 -0
  123. package/core/launch_phases/worker_barriers.py +15 -5
  124. package/core/launch_phases/worker_orchestrator.py +105 -25
  125. package/core/launch_phases/worker_prior.py +115 -0
  126. package/core/ledger/README.md +2 -1
  127. package/core/ledger/SPEC.md +1 -1
  128. package/core/ledger/_facade.py +2 -1
  129. package/core/ledger/archive_ops.py +60 -2
  130. package/core/ledger/cli.py +6 -1
  131. package/core/ledger/export_ops.py +6 -1
  132. package/core/ledger/finding_confirmation.py +48 -6
  133. package/core/ledger/finding_lifecycle.py +428 -5
  134. package/core/ledger/finding_verification.py +555 -10
  135. package/core/ledger/fp_ledger.py +255 -0
  136. package/core/ledger/incidents.py +10 -4
  137. package/core/ledger/patterns.py +10 -7
  138. package/core/ledger/receipt_contract.py +17 -1
  139. package/core/ledger/sync_ops.py +21 -16
  140. package/core/ledger/tool_experience.py +2 -1
  141. package/core/ledger/verify_life.py +88 -17
  142. package/core/locales/en-US.json +2 -2
  143. package/core/locales/zh-CN.json +2 -2
  144. package/core/mcp_handlers/SPEC.md +1 -1
  145. package/core/mcp_handlers/base.py +23 -3
  146. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  147. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  148. package/core/mcp_handlers/rpc_server.py +6 -1
  149. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  150. package/core/mcp_handlers/tool_table.py +15 -0
  151. package/core/mcp_runtime_support/environment.py +0 -38
  152. package/core/mcp_runtime_support/verifier.py +0 -52
  153. package/core/metadata.txt +2 -3
  154. package/core/planning/README.md +2 -1
  155. package/core/planning/domain_router.py +4 -2
  156. package/core/planning/dynamic_flow_analyzer.py +219 -14
  157. package/core/planning/judge_pipeline.py +87 -4
  158. package/core/planning/prompt_harness.py +57 -15
  159. package/core/planning/prompt_policy_engine.py +386 -0
  160. package/core/planning/spec_harvester.py +4 -4
  161. package/core/probes/INTERFACE.md +11 -1
  162. package/core/probes/SPEC.md +11 -1
  163. package/core/probes/__init__.py +46 -40
  164. package/core/probes/android_probe.py +177 -9
  165. package/core/probes/codebase_memory_probe.py +57 -0
  166. package/core/probes/desktop_probe.py +104 -0
  167. package/core/probes/differential_probe.py +99 -21
  168. package/core/probes/efficiency_probe.py +64 -0
  169. package/core/probes/ios_binary_probe.py +105 -1
  170. package/core/probes/memory_probe.py +66 -0
  171. package/core/probes/miniprogram_probe.py +75 -13
  172. package/core/probes/mobile_probe.py +215 -30
  173. package/core/probes/native_probe.py +88 -0
  174. package/core/probes/openwiki_probe.py +70 -0
  175. package/core/probes/pattern_probe.py +106 -0
  176. package/core/probes/platform_probe.py +81 -0
  177. package/core/probes/probe_registry.py +108 -7
  178. package/core/probes/sast_fixture_corpus.py +340 -0
  179. package/core/probes/sast_probe.py +553 -52
  180. package/core/probes/sast_rules.py +668 -28
  181. package/core/probes/sca_scanner.py +48 -0
  182. package/core/probes/ui_accessibility.py +149 -0
  183. package/core/probes/ui_audit.py +513 -0
  184. package/core/probes/ui_contract.py +273 -0
  185. package/core/probes/ui_evidence.py +212 -0
  186. package/core/probes/ui_measurements.py +314 -0
  187. package/core/probes/ui_repair.py +250 -0
  188. package/core/probes/ui_review.py +133 -0
  189. package/core/probes/ui_storybook.py +107 -0
  190. package/core/probes/ui_tokens.py +185 -0
  191. package/core/probes/ui_visual_diff.py +131 -0
  192. package/core/probes/web_probe.py +373 -18
  193. package/core/project_profiler/SPEC.md +1 -1
  194. package/core/project_profiler/arbitrator.py +6 -1
  195. package/core/project_profiler/detector.py +8 -1
  196. package/core/project_profiler/strategy.py +51 -15
  197. package/core/prompts/README.md +4 -2
  198. package/core/prompts/command_routing_en.md +2 -2
  199. package/core/prompts/command_routing_zh.md +2 -2
  200. package/core/prompts/policies/prompt_policies.json +101 -0
  201. package/core/prompts/stages/stage_repair.md +1 -1
  202. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  203. package/core/prompts/stages/stage_verify.md +44 -0
  204. package/core/repair/README.md +1 -1
  205. package/core/repair/l7_repair_loop.py +1 -4
  206. package/core/repair/rsi_fixer.py +4 -4
  207. package/core/repair/rsi_loop.py +1 -3
  208. package/core/repair/rsi_repair.py +7 -7
  209. package/core/repair/rsi_scope.py +27 -8
  210. package/core/report_engine/SPEC.md +1 -1
  211. package/core/report_engine/attestation.py +8 -4
  212. package/core/report_engine/finding_report.py +2 -1
  213. package/core/report_engine/models.py +7 -9
  214. package/core/report_engine/report_share.py +0 -8
  215. package/core/report_engine/sast_bridge.py +2 -2
  216. package/core/report_engine/server.py +18 -8
  217. package/core/report_engine/web-conformance.md +123 -18
  218. package/core/report_engine/web_conformance.py +21 -52
  219. package/core/retrieval/README.md +2 -1
  220. package/core/retrieval/SPEC.md +1 -1
  221. package/core/retrieval/code_analyzer.py +50 -14
  222. package/core/retrieval/context_assembler.py +7 -1
  223. package/core/retrieval/knowledge_sync.py +108 -14
  224. package/core/retrieval/pitfall_packs.py +277 -0
  225. package/core/retrieval/symbol_index.py +25 -6
  226. package/core/retrieval/universal_code_matcher.py +234 -49
  227. package/core/runtime/README.md +1 -1
  228. package/core/runtime/bugx_logging.py +78 -7
  229. package/core/runtime/fixture_solidify.py +5 -10
  230. package/core/runtime/global_telemetry.py +20 -0
  231. package/core/runtime/incident_eval.py +1 -1
  232. package/core/runtime/model_runner.py +4 -41
  233. package/core/runtime/platform_adapter.py +2 -2
  234. package/core/runtime/prep_validate.py +4 -2
  235. package/core/runtime/project_settings.py +2 -1
  236. package/core/runtime/scenario_eval.py +50 -8
  237. package/core/skills/bugx_docs_mcp_server.py +3 -1
  238. package/core/skills/bugx_mcp_server.py +29 -2
  239. package/core/skills/tools_kb.py +1 -1
  240. package/core/supervisor/README.md +1 -1
  241. package/core/supervisor/SPEC.md +1 -1
  242. package/core/supervisor/budget_governor.py +503 -9
  243. package/core/supervisor/checkpoint_pipeline.py +248 -6
  244. package/core/supervisor/checkpoint_sync.py +13 -0
  245. package/core/supervisor/claim_events.py +1 -1
  246. package/core/supervisor/finding_workflow.py +22 -5
  247. package/core/supervisor/lease_manager.py +1 -1
  248. package/core/supervisor/lifecycle_blocks.py +6 -1
  249. package/core/supervisor/rejection_remedies.py +52 -5
  250. package/core/supervisor/serial_authorization.py +48 -4
  251. package/core/supervisor/task_scheduler.py +2 -2
  252. package/core/supervisor/worker_checkpoint.py +8 -1
  253. package/core/supervisor/worker_runtime.py +8 -2
  254. package/core/supervisor_types/worker_claim.py +9 -0
  255. package/core/webui/README.md +1 -1
  256. package/core/webui/SPEC.md +2 -1
  257. package/core/webui/adapters/claude.py +5 -1
  258. package/core/webui/adapters/cline.py +10 -2
  259. package/core/webui/adapters/codex.py +5 -1
  260. package/core/webui/adapters/dsh.py +5 -1
  261. package/core/webui/docs_session_service.py +2 -2
  262. package/core/webui/mcp_inspector.py +11 -7
  263. package/core/webui/static/00-base.css +1060 -0
  264. package/core/webui/static/01-monitoring.css +802 -0
  265. package/core/webui/static/02-header-actions.css +321 -0
  266. package/core/webui/static/03-trigger-popover.css +697 -0
  267. package/core/webui/static/04-composer.css +628 -0
  268. package/core/webui/static/05-skills-center.css +878 -0
  269. package/core/webui/static/06-mcp-center.css +623 -0
  270. package/core/webui/static/07-skill-detail.css +265 -0
  271. package/core/webui/static/08-files-management.css +167 -0
  272. package/core/webui/static/09-files-center.css +386 -0
  273. package/core/webui/static/10-icons.css +105 -0
  274. package/core/webui/static/11-project-options.css +185 -0
  275. package/core/webui/static/12-profile-tab.css +383 -0
  276. package/core/webui/static/design-tokens.css +113 -0
  277. package/core/webui/static/index.html +14 -1
  278. package/core/webui/workspace_service.py +1 -1
  279. package/docs/07_distribution/01_README_NPM.md +193 -185
  280. package/ecosystem/integrations/README.md +1 -1
  281. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  282. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  283. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  284. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  285. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  286. package/ecosystem/integrations/opencode/opencode.json +23 -12
  287. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  288. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  289. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  290. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  291. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  292. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  293. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  294. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  295. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  296. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  297. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  298. package/interfaces/bin/bugx.js +37 -0
  299. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  300. package/interfaces/cli/bugx_cli/cli.py +172 -69
  301. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  302. package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
  303. package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
  304. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  305. package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
  306. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  307. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  308. package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
  309. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  310. package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
  311. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  312. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  313. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  314. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  315. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  316. package/interfaces/cli/bugx_cli/commands/system.py +524 -169
  317. package/interfaces/cli/bugx_cli/common.py +21 -15
  318. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  319. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  320. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  321. package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
  322. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  323. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  324. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  325. package/package.json +30 -15
  326. package/pyproject.toml +60 -9
  327. package/scripts/ensure-python.mjs +7 -7
  328. package/scripts/sync-version.mjs +10 -21
  329. package/scripts/test-npm-wrapper.mjs +1 -1
  330. package/core/assets/bugx-hero-cn.png +0 -0
  331. package/core/assets/bugx-hero-en.png +0 -0
  332. package/core/webui/static/project-settings.css +0 -6458
  333. package/docs/07_distribution/README.md +0 -16
  334. package/docs/README.md +0 -121
  335. package/interfaces/README.md +0 -143
  336. package/interfaces/bin/README.md +0 -35
  337. package/interfaces/cli/README.md +0 -90
  338. package/scripts/README.md +0 -118
@@ -0,0 +1,386 @@
1
+ #!/usr/bin/env python3
2
+ """core/planning/prompt_policy_engine.py — 声明式可配置提示词策略引擎(零 if-else 硬编码)。
3
+
4
+ 核心职责:
5
+ 1. 加载内置 ``core/prompts/policies/prompt_policies.json`` 并支持项目级
6
+ ``<root>/.bugx/prompt-policies.json`` 深度合并与环境变量 ``BUGX_PROMPT_POLICY`` 钉选;
7
+ 2. 按确定性优先级解析 Profile:
8
+ explicit_policy / BUGX_PROMPT_POLICY → reactive_triggers(如遇 cyber policy / Daybreak 拦截)
9
+ → routing_rules(按 priority 降序匹配 host / provider / model_patterns)→ default_profile (standard);
10
+ 3. 代码块保护型变换管线(``apply_policy``):只改写自然语言 prose 段落,物理保护 Markdown
11
+ 围栏代码块(```` ```...``` ````)与行内代码(`` `...` ``)及 CWE/技术机制符号零损坏;
12
+ 4. 严格 fail-closed:非法 JSON、无效正则、未知 profile、越界 ``stage_overrides`` 路径均抛出
13
+ ``PromptPolicyError``。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Any, Mapping, Sequence
24
+
25
+ DEFAULT_POLICIES_PATH = Path(__file__).resolve().parents[1] / "prompts" / "policies" / "prompt_policies.json"
26
+ PROMPTS_ROOT = Path(__file__).resolve().parents[1] / "prompts"
27
+ ENV_POLICY_KEY = "BUGX_PROMPT_POLICY"
28
+
29
+ # Split markdown into fenced code blocks, inline code spans, and normal prose segments.
30
+ _CODE_SEGMENT_RE = re.compile(r"(```[\s\S]*?```|`[^`\n]+`)")
31
+
32
+
33
+ class PromptPolicyError(ValueError):
34
+ """Raised when prompt policy configuration violates schema or safety constraints."""
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ResolvedPolicy:
39
+ name: str
40
+ reason: str
41
+ description: str
42
+ preamble: str
43
+ stage_overrides: Mapping[str, str]
44
+ lexicon_rewrites: tuple[tuple[re.Pattern[str], str], ...]
45
+ safe_repro_directive: str
46
+ matched_rule_id: str | None = None
47
+ triggered_by_error: bool = False
48
+
49
+ def is_passthrough(self) -> bool:
50
+ return (
51
+ not self.preamble
52
+ and not self.stage_overrides
53
+ and not self.lexicon_rewrites
54
+ and not self.safe_repro_directive
55
+ )
56
+
57
+ def to_metadata(self) -> dict[str, Any]:
58
+ return {
59
+ "name": self.name,
60
+ "reason": self.reason,
61
+ "matched_rule_id": self.matched_rule_id,
62
+ "triggered_by_error": self.triggered_by_error,
63
+ "has_stage_overrides": bool(self.stage_overrides),
64
+ "rewrite_count": len(self.lexicon_rewrites),
65
+ }
66
+
67
+
68
+ def _validate_stage_override_path(rel_path: str) -> str:
69
+ if not isinstance(rel_path, str) or not rel_path.strip():
70
+ raise PromptPolicyError("stage_overrides 路径必须为非空字符串")
71
+ cleaned = rel_path.replace("\\", "/").strip()
72
+ candidate = Path(cleaned)
73
+ if candidate.is_absolute() or ".." in candidate.parts:
74
+ raise PromptPolicyError(f"stage_overrides 禁止绝对路径或目录穿越: {rel_path}")
75
+ resolved_root = PROMPTS_ROOT.resolve()
76
+ cursor = resolved_root
77
+ for part in candidate.parts:
78
+ if part in {"", "."}:
79
+ continue
80
+ cursor = cursor / part
81
+ if cursor.is_symlink():
82
+ raise PromptPolicyError(f"stage_overrides 禁止符号链接组件: {rel_path}")
83
+ resolved = (resolved_root / candidate).resolve()
84
+ try:
85
+ resolved.relative_to(resolved_root)
86
+ except ValueError as exc:
87
+ raise PromptPolicyError(f"stage_overrides 越界 core/prompts/: {rel_path}") from exc
88
+ return cleaned
89
+
90
+
91
+ def _compile_pattern(pattern: object, label: str) -> re.Pattern[str]:
92
+ if not isinstance(pattern, str) or not pattern:
93
+ raise PromptPolicyError(f"{label} 正则必须是非空字符串")
94
+ try:
95
+ return re.compile(pattern)
96
+ except re.error as exc:
97
+ raise PromptPolicyError(f"{label} 正则编译失败 ({pattern!r}): {exc}") from exc
98
+
99
+
100
+ def _load_json_file(path: Path) -> dict[str, Any]:
101
+ try:
102
+ data = json.loads(path.read_text(encoding="utf-8"))
103
+ except (OSError, ValueError) as exc:
104
+ raise PromptPolicyError(f"无法读取策略配置 {path}: {exc}") from exc
105
+ if not isinstance(data, dict):
106
+ raise PromptPolicyError(f"策略配置必须是 JSON 对象: {path}")
107
+ return data
108
+
109
+
110
+ def _validate_config(config: Mapping[str, Any]) -> dict[str, Any]:
111
+ profiles = config.get("profiles")
112
+ if not isinstance(profiles, Mapping) or not profiles:
113
+ raise PromptPolicyError("策略配置缺少非空 profiles 对象")
114
+ default_profile = str(config.get("default_profile") or "standard").strip()
115
+ if default_profile not in profiles:
116
+ raise PromptPolicyError(f"default_profile={default_profile!r} 未在 profiles 中定义")
117
+
118
+ validated_profiles: dict[str, dict[str, Any]] = {}
119
+ for pname, pdef in profiles.items():
120
+ if not isinstance(pname, str) or not pname.strip() or not isinstance(pdef, Mapping):
121
+ raise PromptPolicyError(f"非法 profile 定义: {pname!r}")
122
+ raw_overrides = pdef.get("stage_overrides") or {}
123
+ if not isinstance(raw_overrides, Mapping):
124
+ raise PromptPolicyError(f"profile {pname}.stage_overrides 必须是对象")
125
+ overrides = {
126
+ str(k).strip().lower(): _validate_stage_override_path(str(v))
127
+ for k, v in raw_overrides.items()
128
+ if str(k).strip()
129
+ }
130
+ raw_rewrites = pdef.get("lexicon_rewrites") or []
131
+ if not isinstance(raw_rewrites, list):
132
+ raise PromptPolicyError(f"profile {pname}.lexicon_rewrites 必须是列表")
133
+ rewrites: list[dict[str, str]] = []
134
+ for idx, rw in enumerate(raw_rewrites):
135
+ if not isinstance(rw, Mapping):
136
+ raise PromptPolicyError(f"profile {pname}.lexicon_rewrites[{idx}] 必须是对象")
137
+ _compile_pattern(rw.get("pattern"), f"{pname}.lexicon_rewrites[{idx}]")
138
+ if not isinstance(rw.get("replace"), str):
139
+ raise PromptPolicyError(f"profile {pname}.lexicon_rewrites[{idx}].replace 必须是字符串")
140
+ rewrites.append({"pattern": str(rw["pattern"]), "replace": str(rw["replace"])})
141
+ validated_profiles[pname.strip()] = {
142
+ "description": str(pdef.get("description") or ""),
143
+ "preamble": str(pdef.get("preamble") or ""),
144
+ "stage_overrides": overrides,
145
+ "lexicon_rewrites": rewrites,
146
+ "safe_repro_directive": str(pdef.get("safe_repro_directive") or ""),
147
+ }
148
+
149
+ routing_rules: list[dict[str, Any]] = []
150
+ for idx, rule in enumerate(config.get("routing_rules") or ()):
151
+ if not isinstance(rule, Mapping):
152
+ raise PromptPolicyError(f"routing_rules[{idx}] 必须是对象")
153
+ target_profile = str(rule.get("profile") or "").strip()
154
+ if target_profile not in validated_profiles:
155
+ raise PromptPolicyError(f"routing_rules[{idx}] 引用未知 profile: {target_profile!r}")
156
+ match = rule.get("match") or {}
157
+ if not isinstance(match, Mapping):
158
+ raise PromptPolicyError(f"routing_rules[{idx}].match 必须是对象")
159
+ for m_idx, pat in enumerate(match.get("model_patterns") or ()):
160
+ _compile_pattern(pat, f"routing_rules[{idx}].model_patterns[{m_idx}]")
161
+ routing_rules.append({
162
+ "id": str(rule.get("id") or f"rule-{idx}"),
163
+ "priority": int(rule.get("priority") or 0),
164
+ "match": {
165
+ "hosts": [str(h).strip().lower() for h in (match.get("hosts") or ()) if str(h).strip()],
166
+ "providers": [str(p).strip().lower() for p in (match.get("providers") or ()) if str(p).strip()],
167
+ "model_patterns": [str(p) for p in (match.get("model_patterns") or ()) if str(p)],
168
+ },
169
+ "profile": target_profile,
170
+ })
171
+
172
+ reactive_triggers: list[dict[str, Any]] = []
173
+ for idx, trig in enumerate(config.get("reactive_triggers") or ()):
174
+ if not isinstance(trig, Mapping):
175
+ raise PromptPolicyError(f"reactive_triggers[{idx}] 必须是对象")
176
+ fb = str(trig.get("fallback_profile") or "").strip()
177
+ if fb not in validated_profiles:
178
+ raise PromptPolicyError(f"reactive_triggers[{idx}] 引用未知 fallback_profile: {fb!r}")
179
+ pats = trig.get("error_patterns") or []
180
+ if not isinstance(pats, list) or not pats:
181
+ raise PromptPolicyError(f"reactive_triggers[{idx}].error_patterns 必须是非空列表")
182
+ for p_idx, pat in enumerate(pats):
183
+ _compile_pattern(pat, f"reactive_triggers[{idx}].error_patterns[{p_idx}]")
184
+ reactive_triggers.append({
185
+ "id": str(trig.get("id") or f"trigger-{idx}"),
186
+ "error_patterns": [str(p) for p in pats],
187
+ "fallback_profile": fb,
188
+ })
189
+
190
+ return {
191
+ "schema_version": int(config.get("schema_version") or 1),
192
+ "default_profile": default_profile,
193
+ "profiles": validated_profiles,
194
+ "routing_rules": routing_rules,
195
+ "reactive_triggers": reactive_triggers,
196
+ }
197
+
198
+
199
+ def load_policy_config(
200
+ *,
201
+ root: Path | None = None,
202
+ builtin_path: Path | None = None,
203
+ ) -> dict[str, Any]:
204
+ """Load built-in policies and optionally merge project-level .bugx/prompt-policies.json."""
205
+ base_path = Path(builtin_path) if builtin_path is not None else DEFAULT_POLICIES_PATH
206
+ merged = _load_json_file(base_path)
207
+
208
+ if root is not None:
209
+ override_path = Path(root).resolve() / ".bugx" / "prompt-policies.json"
210
+ if override_path.is_file() and not override_path.is_symlink():
211
+ proj = _load_json_file(override_path)
212
+ if "default_profile" in proj:
213
+ merged["default_profile"] = proj["default_profile"]
214
+ if isinstance(proj.get("profiles"), Mapping):
215
+ combined_profiles = dict(merged.get("profiles") or {})
216
+ combined_profiles.update(proj["profiles"])
217
+ merged["profiles"] = combined_profiles
218
+ if isinstance(proj.get("routing_rules"), list):
219
+ merged["routing_rules"] = [*proj["routing_rules"], *(merged.get("routing_rules") or [])]
220
+ if isinstance(proj.get("reactive_triggers"), list):
221
+ merged["reactive_triggers"] = [*proj["reactive_triggers"], *(merged.get("reactive_triggers") or [])]
222
+
223
+ return _validate_config(merged)
224
+
225
+
226
+ def _build_resolved(
227
+ config: Mapping[str, Any],
228
+ profile_name: str,
229
+ *,
230
+ reason: str,
231
+ matched_rule_id: str | None = None,
232
+ triggered_by_error: bool = False,
233
+ ) -> ResolvedPolicy:
234
+ profiles = config["profiles"]
235
+ if profile_name not in profiles:
236
+ raise PromptPolicyError(f"请求的 prompt policy 未定义: {profile_name!r}")
237
+ pdef = profiles[profile_name]
238
+ compiled_rewrites = tuple(
239
+ (re.compile(rw["pattern"]), rw["replace"])
240
+ for rw in pdef["lexicon_rewrites"]
241
+ )
242
+ return ResolvedPolicy(
243
+ name=profile_name,
244
+ reason=reason,
245
+ description=pdef["description"],
246
+ preamble=pdef["preamble"],
247
+ stage_overrides=dict(pdef["stage_overrides"]),
248
+ lexicon_rewrites=compiled_rewrites,
249
+ safe_repro_directive=pdef["safe_repro_directive"],
250
+ matched_rule_id=matched_rule_id,
251
+ triggered_by_error=triggered_by_error,
252
+ )
253
+
254
+
255
+ def detect_policy_block(
256
+ error_text: str | None,
257
+ *,
258
+ root: Path | None = None,
259
+ config: Mapping[str, Any] | None = None,
260
+ ) -> dict[str, str] | None:
261
+ """Detect whether an upstream model/host error matches any configured reactive trigger."""
262
+ text = (error_text or "").strip()
263
+ if not text:
264
+ return None
265
+ cfg = _validate_config(config) if config is not None else load_policy_config(root=root)
266
+ for trig in cfg["reactive_triggers"]:
267
+ for pat in trig["error_patterns"]:
268
+ if re.search(pat, text):
269
+ return {
270
+ "trigger_id": trig["id"],
271
+ "fallback_profile": trig["fallback_profile"],
272
+ "matched_pattern": pat,
273
+ }
274
+ return None
275
+
276
+
277
+ def resolve_policy(
278
+ *,
279
+ host: str | None = None,
280
+ provider: str | None = None,
281
+ model: str | None = None,
282
+ last_error: str | None = None,
283
+ explicit_policy: str | None = None,
284
+ root: Path | None = None,
285
+ config: Mapping[str, Any] | None = None,
286
+ ) -> ResolvedPolicy:
287
+ """Resolve the active prompt policy profile without hardcoded host if-else branches."""
288
+ cfg = _validate_config(config) if config is not None else load_policy_config(root=root)
289
+
290
+ # 1. Explicit override (argument or BUGX_PROMPT_POLICY env var) has highest authority
291
+ chosen = (explicit_policy or os.environ.get(ENV_POLICY_KEY) or "").strip()
292
+ if chosen:
293
+ source = "explicit_arg" if explicit_policy else f"env:{ENV_POLICY_KEY}"
294
+ return _build_resolved(cfg, chosen, reason=source)
295
+
296
+ # 2. Reactive error trigger (e.g. OpenAI cyber policy / Daybreak block)
297
+ hit = detect_policy_block(last_error, config=cfg)
298
+ if hit is not None:
299
+ return _build_resolved(
300
+ cfg,
301
+ hit["fallback_profile"],
302
+ reason=f"reactive_trigger:{hit['trigger_id']}",
303
+ matched_rule_id=hit["trigger_id"],
304
+ triggered_by_error=True,
305
+ )
306
+
307
+ # 3. Declarative routing rules sorted by descending priority
308
+ norm_host = (host or "").strip().lower()
309
+ norm_provider = (provider or "").strip().lower()
310
+ norm_model = (model or "").strip()
311
+
312
+ sorted_rules = sorted(cfg["routing_rules"], key=lambda r: (-int(r["priority"]), r["id"]))
313
+ for rule in sorted_rules:
314
+ match = rule["match"]
315
+ host_hit = bool(norm_host and norm_host in match["hosts"])
316
+ prov_hit = bool(norm_provider and norm_provider in match["providers"])
317
+ model_hit = bool(
318
+ norm_model and any(re.search(pat, norm_model) for pat in match["model_patterns"])
319
+ )
320
+ if host_hit or prov_hit or model_hit:
321
+ return _build_resolved(
322
+ cfg,
323
+ rule["profile"],
324
+ reason=f"routing_rule:{rule['id']}",
325
+ matched_rule_id=rule["id"],
326
+ )
327
+
328
+ # 4. Default profile (standard -> zero-rewrite passthrough)
329
+ return _build_resolved(cfg, cfg["default_profile"], reason="default_profile")
330
+
331
+
332
+ def _rewrite_prose_preserving_code(
333
+ text: str,
334
+ rewrites: Sequence[tuple[re.Pattern[str], str]],
335
+ ) -> str:
336
+ """Apply lexicon rewrites strictly to prose segments; preserve fenced & inline code verbatim."""
337
+ if not text or not rewrites:
338
+ return text
339
+ segments = _CODE_SEGMENT_RE.split(text)
340
+ for idx in range(0, len(segments), 2): # even indices are non-code prose
341
+ seg = segments[idx]
342
+ for pattern, replacement in rewrites:
343
+ seg = pattern.sub(replacement, seg)
344
+ segments[idx] = seg
345
+ return "".join(segments)
346
+
347
+
348
+ def resolve_stage_override_relpath(policy: ResolvedPolicy, stage: str) -> str | None:
349
+ key = (stage or "").strip().lower()
350
+ return policy.stage_overrides.get(key)
351
+
352
+
353
+ def apply_policy(
354
+ text: str,
355
+ policy: ResolvedPolicy,
356
+ *,
357
+ include_preamble: bool = True,
358
+ include_safe_repro: bool = False,
359
+ ) -> str:
360
+ """Apply a resolved policy to prompt/guidance text with code-span protection."""
361
+ if policy.is_passthrough():
362
+ return text
363
+
364
+ transformed = _rewrite_prose_preserving_code(text, policy.lexicon_rewrites)
365
+ parts: list[str] = []
366
+ if include_preamble and policy.preamble:
367
+ if policy.preamble not in transformed:
368
+ parts.append(policy.preamble)
369
+ parts.append(transformed)
370
+ if include_safe_repro and policy.safe_repro_directive:
371
+ if policy.safe_repro_directive not in transformed:
372
+ parts.append(f"\n[Safe Repro Policy] {policy.safe_repro_directive}")
373
+ return "\n\n".join(parts) if len(parts) > 1 else parts[0]
374
+
375
+
376
+ __all__ = [
377
+ "DEFAULT_POLICIES_PATH",
378
+ "ENV_POLICY_KEY",
379
+ "PromptPolicyError",
380
+ "ResolvedPolicy",
381
+ "load_policy_config",
382
+ "detect_policy_block",
383
+ "resolve_policy",
384
+ "resolve_stage_override_relpath",
385
+ "apply_policy",
386
+ ]
@@ -301,10 +301,10 @@ def harvest_specification(project_root: Path) -> BusinessSpec:
301
301
  # 2. 扫描权威设计文档与 README
302
302
  doc_candidates = (
303
303
  "README.md",
304
- "docs/02_architecture/DESIGN_SPEC.md",
305
- "docs/02_architecture/ARCHITECTURE.md",
306
- "docs/02_architecture/BUGX_AUDIT_FLOW.md",
307
- "docs/03_ai/AI_REFERENCE.md",
304
+ "docs/02_architecture/02_DESIGN_SPEC.md",
305
+ "docs/02_architecture/01_ARCHITECTURE.md",
306
+ "docs/02_architecture/03_BUGX_AUDIT_FLOW.md",
307
+ "docs/03_ai/01_AI_REFERENCE.md",
308
308
  )
309
309
  for rel_path in doc_candidates:
310
310
  candidate = project_root / rel_path
@@ -42,9 +42,10 @@
42
42
  #### `class WebDynamicProbe(BaseProbe)` - Web 专属黑盒动态探针,支持 HTTP 原始发包与 Playwright 无头浏览器探针。
43
43
  - **Public Methods**:
44
44
  - `browser_slot(cls, timeout: float = 2.0)`
45
+ - `capture_browser_page(page: Any, url: str, *, browser_version: str, actions: Sequence[dict[str, Any]] | None = None, timeout: float = 10.0, screenshot_path: str | Path | None = None, screenshot_full_page: bool = True, screenshot_masks: Sequence[str] = (), wait_until: str = 'load', after_navigation: Callable[[Any], None] | None = None, inspect_page: Callable[[Any], Mapping[str, Any] | None] | None = None) -> dict[str, Any]`
45
46
  - `classify_http_response(cls, response_data: Mapping[str, Any], baseline_data: Mapping[str, Any] | None = None) -> dict[str, Any]`
46
47
  - `get_active_instances(cls) -> int`
47
- - `headless_browser_action(self, url: str, actions: Sequence[dict[str, Any]] | None = None, timeout: float = 10.0) -> dict[str, Any]`
48
+ - `headless_browser_action(self, url: str, actions: Sequence[dict[str, Any]] | None = None, timeout: float = 10.0, *, screenshot_path: str | Path | None = None, viewport: Mapping[str, int] | None = None) -> dict[str, Any]`
48
49
  - `http_raw_request(self, url: str, method: str = 'GET', headers: Mapping[str, str] | None = None, data: bytes | str | None = None, timeout: float = 10.0) -> dict[str, Any]`
49
50
  - `is_available(self) -> bool`
50
51
  - `probe_name(self) -> str`
@@ -70,4 +71,13 @@
70
71
  <!-- generated:end -->
71
72
 
72
73
  ## 3. Usage Examples & Defensive Patterns
74
+ The CLI registry exposes `bugx probe ui` through `ui_audit.py:main`. Rules are loaded by
75
+ `ui_contract.py`. `ui_accessibility.py` runs axe-core and keyboard steps,
76
+ `ui_evidence.py` verifies receipts, and `ui_visual_diff.py` compares reference captures.
77
+ `ui_storybook.py` resolves a deployed index and preview, and `ui_tokens.py` loads mapped
78
+ CSS values from project token JSON.
79
+ Browser measurements, model review and token repair remain internal to the CLI
80
+ implementation. Input, receipt and exit contracts are specified in
81
+ `core/report_engine/web-conformance.md`.
82
+
73
83
  Refer to `SPEC.md` for architectural context, event topologies, and failure domain mappings.
@@ -22,5 +22,15 @@ res = probe.execute_probe('http://localhost:8080')
22
22
  ```
23
23
 
24
24
  ## 5. Maintenance & Verification
25
- - Unit & regression tests for this package are registered in `tests/test_registry.json`.
25
+ - Verification is performed with short-lived tests outside the repository; no persistent `tests/` registry is retained.
26
+ - Validation runners and fixtures are process artifacts under `/tmp/bugx-tests-*`; they are
27
+ physically removed after the verification window and are not a repository interface.
28
+ - `capture_browser_page` is shared by `headless_browser_action` and `bugx probe ui`. The UI
29
+ audit owns its browser contexts, records native zoom, and adds computed style, layout and
30
+ explicit state and keyboard assertions to the same screenshot receipt. The packaged
31
+ axe-core bundle runs in the rendered context. The Web conformance reader verifies the
32
+ run identity, manifest, screenshot hashes and scoped outcomes.
33
+ - Storybook inputs bind the index digest and preview ID to each captured story. The
34
+ token importer resolves declared same-file aliases in project JSON and adds its file
35
+ digest and CSS mapping to the design receipt.
26
36
  - Changes to exported interfaces must be synchronized via `python3 scripts/gen_interface_spec.py --package core/probes --write`.
@@ -2,50 +2,22 @@
2
2
  """core/probes - 形态专属黑盒探针系统 (DOC-248 Dynamic Probes)。
3
3
 
4
4
  统一导出所有领域专属探针基类与实现类。
5
+
6
+ W-004 惰性化(耗时账本):本包历史上 eager import 全部 19 个探针模块
7
+ (含 playwright 链的 web_probe/differential_probe 等重型依赖),被引擎
8
+ 门禁链(launch_phases.common → governance → supervisor → coverage)
9
+ 连带 import,每次引擎启动固定支付 ~190ms。改为 PEP 562 模块级
10
+ __getattr__ 按需加载:BaseProbe(轻量基类)保持 eager(probe_registry
11
+ 注册面依赖),其余探针在首次属性访问时才 import——消费方三种形态
12
+ (from core.probes import X / from core.probes.X import Y / 子模块直
13
+ import)语义全部不变。
5
14
  """
6
15
 
7
16
  from __future__ import annotations
8
17
 
9
- try:
10
- from .base import BaseProbe
11
- from .web_probe import WebDynamicProbe
12
- from .android_probe import AndroidProbe
13
- from .miniprogram_probe import MiniProgramProbe
14
- from . import sast_probe
15
- from . import sast_rules
16
- from . import sca_scanner
17
- from . import desktop_probe
18
- from . import mobile_probe
19
- from . import native_probe
20
- from . import platform_probe
21
- from . import memory_probe
22
- from . import efficiency_probe
23
- from . import differential_probe
24
- from . import pattern_probe
25
- from . import ios_binary_probe
26
- from . import codebase_memory_probe
27
- from . import openwiki_probe
28
- from . import probe_registry
29
- except (ImportError, ValueError):
30
- from core.probes.base import BaseProbe
31
- from core.probes.web_probe import WebDynamicProbe
32
- from core.probes.android_probe import AndroidProbe
33
- from core.probes.miniprogram_probe import MiniProgramProbe
34
- from core.probes import sast_probe
35
- from core.probes import sast_rules
36
- from core.probes import sca_scanner
37
- from core.probes import desktop_probe
38
- from core.probes import mobile_probe
39
- from core.probes import native_probe
40
- from core.probes import platform_probe
41
- from core.probes import memory_probe
42
- from core.probes import efficiency_probe
43
- from core.probes import differential_probe
44
- from core.probes import pattern_probe
45
- from core.probes import ios_binary_probe
46
- from core.probes import codebase_memory_probe
47
- from core.probes import openwiki_probe
48
- from core.probes import probe_registry
18
+ from typing import Any
19
+
20
+ from .base import BaseProbe
49
21
 
50
22
  __all__ = [
51
23
  "BaseProbe",
@@ -68,3 +40,37 @@ __all__ = [
68
40
  "openwiki_probe",
69
41
  "probe_registry",
70
42
  ]
43
+
44
+ # 惰性成员 → 所属子模块(属性名与历史 eager 导出逐一对应,语义不变)
45
+ _LAZY_MEMBERS: dict[str, str] = {
46
+ "WebDynamicProbe": "web_probe",
47
+ "AndroidProbe": "android_probe",
48
+ "MiniProgramProbe": "miniprogram_probe",
49
+ "sast_probe": "sast_probe",
50
+ "sast_rules": "sast_rules",
51
+ "sca_scanner": "sca_scanner",
52
+ "desktop_probe": "desktop_probe",
53
+ "mobile_probe": "mobile_probe",
54
+ "native_probe": "native_probe",
55
+ "platform_probe": "platform_probe",
56
+ "memory_probe": "memory_probe",
57
+ "efficiency_probe": "efficiency_probe",
58
+ "differential_probe": "differential_probe",
59
+ "pattern_probe": "pattern_probe",
60
+ "ios_binary_probe": "ios_binary_probe",
61
+ "codebase_memory_probe": "codebase_memory_probe",
62
+ "openwiki_probe": "openwiki_probe",
63
+ "probe_registry": "probe_registry",
64
+ }
65
+
66
+
67
+ def __getattr__(name: str) -> Any:
68
+ """PEP 562 按需加载探针成员(W-004:消除门禁链 190ms eager 税)。"""
69
+ target = _LAZY_MEMBERS.get(name)
70
+ if target is None:
71
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
72
+ import importlib
73
+
74
+ module = importlib.import_module(f"{__name__}.{target}")
75
+ globals()[name] = module # 缓存:后续访问零开销
76
+ return module