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,273 @@
1
+ """Validated, declarative UI rules stored in a project's DESIGN.md."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from core.probes.ui_storybook import STORY_ID
13
+ from core.probes.ui_tokens import TOKEN_FORMATS, load_mapped_tokens
14
+
15
+ STATES = ("loading", "error", "empty", "disabled")
16
+ IDENTIFIER = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}")
17
+ TOKEN = re.compile(r"--[a-zA-Z_][a-zA-Z0-9_-]{0,95}")
18
+ STYLE_PROPERTIES = frozenset({
19
+ "color", "background-color", "border-top-color", "outline-color",
20
+ "font-family", "font-size", "font-weight", "line-height", "letter-spacing",
21
+ "row-gap", "column-gap", "padding-top", "padding-right", "padding-bottom", "padding-left",
22
+ "margin-top", "margin-right", "margin-bottom", "margin-left",
23
+ "border-top-left-radius", "max-width", "min-height",
24
+ })
25
+ CONTRAST_PROPERTIES = frozenset({"background-color", "border-top-color", "outline-color"})
26
+ KEYBOARD_KEYS = frozenset({
27
+ "Tab", "Shift+Tab", "Enter", "Escape", "Space", "ArrowUp", "ArrowDown",
28
+ "ArrowLeft", "ArrowRight", "Home", "End",
29
+ })
30
+
31
+
32
+ class UIContractError(ValueError):
33
+ """Malformed UI audit input."""
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class UIContract:
38
+ source: str | None = None
39
+ sha256: str | None = None
40
+ markdown: str = ""
41
+ tokens: dict[str, str | None] | None = None
42
+ components: tuple[dict[str, Any], ...] = ()
43
+ contrast: tuple[dict[str, Any], ...] = ()
44
+ journeys: tuple[dict[str, Any], ...] = ()
45
+ reflow: tuple[dict[str, Any], ...] = ()
46
+ keyboard: tuple[dict[str, Any], ...] = ()
47
+ token_source: dict[str, Any] | None = None
48
+
49
+
50
+ def _object(value: Any, fields: set[str], where: str) -> dict:
51
+ if not isinstance(value, dict) or set(value) - fields:
52
+ raise UIContractError(f"{where}: expected an object with fields {sorted(fields)}")
53
+ return value
54
+
55
+
56
+ def _items(value: Any, limit: int, where: str) -> list:
57
+ if not isinstance(value, list) or len(value) > limit:
58
+ raise UIContractError(f"{where}: expected an array of at most {limit} entries")
59
+ return value
60
+
61
+
62
+ def _string(value: Any, where: str, limit: int = 256) -> str:
63
+ if not isinstance(value, str) or not value.strip() or len(value) > limit:
64
+ raise UIContractError(f"{where}: expected nonempty text of at most {limit} characters")
65
+ return value
66
+
67
+
68
+ def _identifiers(value: Any, limit: int, where: str) -> list[str]:
69
+ entries = _items(value, limit, where)
70
+ if any(not isinstance(name, str) or not IDENTIFIER.fullmatch(name) for name in entries):
71
+ raise UIContractError(f"{where}: invalid identifier")
72
+ if len(entries) != len(set(entries)):
73
+ raise UIContractError(f"{where}: duplicate identifier")
74
+ return entries
75
+
76
+
77
+ def _action(value: Any, where: str) -> dict:
78
+ if not isinstance(value, dict):
79
+ raise UIContractError(f"{where}: action must be an object")
80
+ kind = value.get("type")
81
+ extras = {
82
+ "click": set(), "fill": {"value"}, "press": {"key"},
83
+ "select_option": {"value"}, "wait_for": {"state"},
84
+ }
85
+ if not isinstance(kind, str) or kind not in extras:
86
+ raise UIContractError(f"{where}: unsupported action type")
87
+ _object(value, {"type", "selector"} | extras[kind], where)
88
+ if kind != "press" or "selector" in value:
89
+ _string(value.get("selector"), f"{where}.selector")
90
+ if kind in {"fill", "select_option"}:
91
+ if not isinstance(value.get("value"), str) or len(value["value"]) > 512:
92
+ raise UIContractError(f"{where}.value: expected text of at most 512 characters")
93
+ if kind == "press":
94
+ _string(value.get("key"), f"{where}.key", 48)
95
+ if kind == "wait_for" and value.get("state", "visible") not in ("visible", "hidden"):
96
+ raise UIContractError(f"{where}.state: expected visible or hidden")
97
+ return value
98
+
99
+
100
+ def _assertion(value: Any, where: str) -> dict:
101
+ item = _object(value, {"selector", "text", "attributes", "disabled", "visible"}, where)
102
+ _string(item.get("selector"), f"{where}.selector")
103
+ if "text" in item:
104
+ _string(item["text"], f"{where}.text")
105
+ for key in ("visible", "disabled"):
106
+ if key in item and type(item[key]) is not bool:
107
+ raise UIContractError(f"{where}.{key}: expected boolean")
108
+ if item.get("visible") is False and {"text", "attributes", "disabled"} & item.keys():
109
+ raise UIContractError(f"{where}: hidden assertions cannot also inspect content")
110
+ if "attributes" in item:
111
+ attrs = item["attributes"]
112
+ if not isinstance(attrs, dict) or not attrs or len(attrs) > 8:
113
+ raise UIContractError(f"{where}.attributes: expected 1–8 attribute checks")
114
+ for name, expected in attrs.items():
115
+ if not re.fullmatch(r"(?:aria-[a-z-]+|role|data-[a-z0-9-]+)", name):
116
+ raise UIContractError(f"{where}.attributes: unsupported attribute {name}")
117
+ _string(expected, f"{where}.attributes.{name}")
118
+ return item
119
+
120
+
121
+ def _rows(value: Any, kind: str, limit: int, fields: set[str]) -> tuple[dict, ...]:
122
+ rows = tuple(_object(item, fields | {"id"}, kind) for item in _items(value, limit, kind))
123
+ _identifiers([item.get("id") for item in rows], limit, f"{kind}.id")
124
+ return rows
125
+
126
+
127
+ def _journey_target(row: dict, where: str) -> None:
128
+ if "story" in row:
129
+ if "path" in row or not STORY_ID.fullmatch(_string(row["story"], f"{where}.story", 192)):
130
+ raise UIContractError(f"{where}: story must be a Storybook ID and cannot be combined with path")
131
+ return
132
+ path = _string(row.get("path", "/"), f"{where}.path", 512)
133
+ if not path.startswith("/") or path.startswith("//") or "\\" in path or any(
134
+ ord(ch) < 33 for ch in path
135
+ ):
136
+ raise UIContractError(f"{where}.path: expected an origin-relative URL")
137
+
138
+
139
+ def _validate(data: Any) -> dict[str, Any]:
140
+ spec = _object(
141
+ data, {"version", "tokens", "token_source", "components", "contrast", "journeys", "reflow", "keyboard"},
142
+ "bugx-ui",
143
+ )
144
+ if type(spec.get("version")) is not int or spec["version"] != 1:
145
+ raise UIContractError("bugx-ui.version: expected 1")
146
+ tokens = spec.get("tokens", {})
147
+ if not isinstance(tokens, dict) or len(tokens) > 64:
148
+ raise UIContractError("tokens: expected up to 64 CSS custom properties")
149
+ for key, value in tokens.items():
150
+ if not TOKEN.fullmatch(key):
151
+ raise UIContractError(f"invalid CSS token name: {key}")
152
+ if value is not None:
153
+ _string(value, f"tokens.{key}")
154
+ source = None
155
+ if "token_source" in spec:
156
+ source = _object(spec["token_source"], {"file", "format", "map"}, "token_source")
157
+ _string(source.get("file"), "token_source.file", 512)
158
+ if source.get("format") not in TOKEN_FORMATS:
159
+ raise UIContractError(f"token_source.format: expected one of {TOKEN_FORMATS}")
160
+ mapping = source.get("map")
161
+ if not isinstance(mapping, dict) or not mapping or len(mapping) + len(tokens) > 64:
162
+ raise UIContractError("token_source.map: expected mapped CSS tokens within the 64 token limit")
163
+ if mapping.keys() & tokens.keys():
164
+ raise UIContractError("token_source.map and inline tokens must have disjoint names")
165
+ for key, reference in mapping.items():
166
+ if not TOKEN.fullmatch(key):
167
+ raise UIContractError(f"invalid mapped CSS token name: {key}")
168
+ _string(reference, f"token_source.map.{key}", 192)
169
+
170
+ components = _rows(spec.get("components", []), "components", 32,
171
+ {"selector", "styles", "align", "tolerance_px", "profiles"})
172
+ for item in components:
173
+ _string(item.get("selector"), "components.selector")
174
+ styles = _object(item.get("styles", {}), STYLE_PROPERTIES, "components.styles")
175
+ for prop, expected in styles.items():
176
+ _string(expected, f"components.styles.{prop}")
177
+ if expected.startswith("--") and not TOKEN.fullmatch(expected):
178
+ raise UIContractError(f"invalid token reference: {expected}")
179
+ if "align" in item and item["align"] not in ("left", "top", "right", "center-x"):
180
+ raise UIContractError("components.align: expected left, top, right, or center-x")
181
+ if not styles and "align" not in item:
182
+ raise UIContractError("components: styles or align is required")
183
+ tolerance = item.get("tolerance_px", 2)
184
+ if type(tolerance) not in (int, float) or not 0 <= tolerance <= 20:
185
+ raise UIContractError("components.tolerance_px: expected 0–20")
186
+ _identifiers(item.get("profiles", []), 12, "components.profiles")
187
+
188
+ contrast = _rows(spec.get("contrast", []), "contrast", 12,
189
+ {"selector", "property", "against", "focus"})
190
+ for item in contrast:
191
+ _string(item.get("selector"), "contrast.selector")
192
+ if item.get("property") not in sorted(CONTRAST_PROPERTIES):
193
+ raise UIContractError(f"contrast.property: expected one of {sorted(CONTRAST_PROPERTIES)}")
194
+ if item.get("against", "parent") not in ("self", "parent"):
195
+ raise UIContractError("contrast.against: expected self or parent")
196
+ if item["property"] == "background-color" and item.get("against") == "self":
197
+ raise UIContractError("contrast: background-color must be compared to the parent")
198
+ if "focus" in item and type(item["focus"]) is not bool:
199
+ raise UIContractError("contrast.focus: expected boolean")
200
+
201
+ reflow = _rows(spec.get("reflow", []), "reflow", 20, {"selector", "interactive"})
202
+ for item in reflow:
203
+ _string(item.get("selector"), "reflow.selector")
204
+ if "interactive" in item and type(item["interactive"]) is not bool:
205
+ raise UIContractError("reflow.interactive: expected boolean")
206
+
207
+ journeys = _rows(spec.get("journeys", []), "journeys", 12,
208
+ {"state", "path", "story", "actions", "expect"})
209
+ for item in journeys:
210
+ if item.get("state") not in STATES:
211
+ raise UIContractError(f"journeys.state: expected one of {STATES}")
212
+ _journey_target(item, "journeys")
213
+ for step in _items(item.get("actions", []), 8, "journeys.actions"):
214
+ _action(step, "journeys.actions")
215
+ assertions = [_assertion(check, "journeys.expect")
216
+ for check in _items(item.get("expect"), 8, "journeys.expect")]
217
+ if not any(check.keys() & {"text", "attributes", "disabled"} for check in assertions):
218
+ raise UIContractError("journeys.expect: provide a text, attribute or disabled assertion")
219
+ if item["state"] == "disabled" and not any(check.get("disabled") is True for check in assertions):
220
+ raise UIContractError("disabled journeys must assert disabled: true")
221
+ keyboard = _rows(spec.get("keyboard", []), "keyboard", 8, {"path", "story", "steps"})
222
+ for item in keyboard:
223
+ _journey_target(item, "keyboard")
224
+ steps = _items(item.get("steps"), 20, "keyboard.steps")
225
+ if not steps:
226
+ raise UIContractError("keyboard.steps: at least one step is required")
227
+ for step in steps:
228
+ step = _object(step, {"key", "focus", "indicator"}, "keyboard.steps")
229
+ if _string(step.get("key"), "keyboard.steps.key") not in KEYBOARD_KEYS:
230
+ raise UIContractError("keyboard.steps.key: unsupported navigation key")
231
+ _string(step.get("focus"), "keyboard.steps.focus")
232
+ if "indicator" in step:
233
+ _string(step["indicator"], "keyboard.steps.indicator")
234
+ return dict(tokens=tokens, components=components, contrast=contrast, journeys=journeys,
235
+ reflow=reflow, keyboard=keyboard, token_source=source)
236
+
237
+
238
+ def _unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
239
+ result = {}
240
+ for key, value in pairs:
241
+ if key in result:
242
+ raise UIContractError(f"duplicate bugx-ui key: {key}")
243
+ result[key] = value
244
+ return result
245
+
246
+
247
+ def load_ui_contract(root: Path, design: Path | None = None) -> UIContract:
248
+ """Load at most one bugx-ui JSON fence. Plain Markdown is a visual reference."""
249
+ path = root / (design if design is not None else Path("DESIGN.md"))
250
+ if design is None and not path.exists():
251
+ return UIContract()
252
+ with path.open("rb") as stream:
253
+ raw = stream.read(128 * 1024 + 1)
254
+ if len(raw) > 128 * 1024:
255
+ raise UIContractError("DESIGN.md exceeds 128 KiB")
256
+ markdown = raw.decode("utf-8")
257
+ starts = list(re.finditer(r"(?m)^[ \t]{0,3}" + chr(96) * 3 + r"bugx-ui[ \t]*\r?$", markdown))
258
+ if len(starts) > 1:
259
+ raise UIContractError("DESIGN.md must contain at most one bugx-ui block")
260
+ rules = {}
261
+ if starts:
262
+ rest = markdown[starts[0].end():]
263
+ end = re.search(r"(?m)^[ \t]{0,3}" + chr(96) * 3 + r"[ \t]*\r?$", rest)
264
+ if end is None:
265
+ raise UIContractError("unclosed bugx-ui fence")
266
+ try:
267
+ rules = _validate(json.loads(rest[:end.start()], object_pairs_hook=_unique))
268
+ except json.JSONDecodeError as exc:
269
+ raise UIContractError(f"invalid bugx-ui JSON at line {exc.lineno}: {exc.msg}") from exc
270
+ if rules.get("token_source"):
271
+ imported, provenance = load_mapped_tokens(root, rules["token_source"])
272
+ rules.update(tokens={**rules["tokens"], **imported}, token_source=provenance)
273
+ return UIContract(str(path.resolve()), hashlib.sha256(raw).hexdigest(), markdown, **rules)
@@ -0,0 +1,212 @@
1
+ """Summarize and verify Web UI audit receipts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from pathlib import Path
9
+ from uuid import uuid4
10
+
11
+ from core.probes.ui_accessibility import AXE_SHA256, AXE_VERSION
12
+ from core.probes.ui_contract import STATES
13
+ from core.probes.ui_storybook import STORY_ROOT, verify_story_url
14
+ from core.secure_atomic import atomic_write_json
15
+
16
+ MANIFEST_SCHEMA = "bugx.ui-audit.v3"
17
+ EVIDENCE_SCHEMA = "bugx.ui-evidence.v1"
18
+ CASE_GROUPS = ("captures", "journeys", "keyboard_journeys")
19
+ STATUSES = ("FAIL", "BLOCKED", "UNVERIFIED", "PASS")
20
+ PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
21
+
22
+
23
+ def combine_status(statuses: list[str]) -> str:
24
+ if not statuses or any(status not in STATUSES for status in statuses):
25
+ return "UNVERIFIED"
26
+ return next(value for value in STATUSES if value in statuses)
27
+
28
+
29
+ def _check(status: str, group: str, message: str) -> dict:
30
+ return {"status": status, "evidence": f"manifest.json#{group}", "message": message}
31
+
32
+
33
+ def summarize_ui(manifest: dict) -> dict:
34
+ """Derive audit statuses from the recorded browser observations."""
35
+ captures = manifest["captures"]
36
+ journeys = manifest["journeys"]
37
+ keyboard = manifest["keyboard_journeys"]
38
+ rules = manifest["design_rules"]
39
+ inspected = [row["inspection"] for row in captures if row["status"] == "PASS"]
40
+ availability = [row["status"] for row in captures if row["status"] != "PASS"]
41
+ contrasts = [row["text_contrast"]["status"] for row in inspected]
42
+ contrasts.extend(check["status"] for row in inspected for check in row["non_text_contrast"])
43
+ if not rules["contrast"]:
44
+ contrasts.append("UNVERIFIED")
45
+ layouts = [check["status"] for row in inspected for check in row["anchors"]]
46
+ layouts.extend("FAIL" if row["horizontal_overflow_px"] > 1 else "PASS" for row in inspected)
47
+ if not rules["reflow"]:
48
+ layouts.append("UNVERIFIED")
49
+ states = {
50
+ state: combine_status([row["status"] for row in journeys if row["state"] == state])
51
+ for state in STATES
52
+ }
53
+ a11y = []
54
+ for row in captures + journeys + keyboard:
55
+ if row["status"] == "BLOCKED":
56
+ a11y.append("BLOCKED")
57
+ else:
58
+ a11y.append(row["inspection"]["axe"]["status"])
59
+ if not row["evidence"]["accessibility"]["snapshot"]:
60
+ a11y.append("UNVERIFIED")
61
+ checks = {
62
+ "keyboard-focus": _check(
63
+ combine_status([row["status"] for row in keyboard]), "keyboard_journeys",
64
+ "Declared keyboard traversal, focused target and visible indicator changes."),
65
+ "aria-tree": _check(combine_status(a11y), "captures",
66
+ "ARIA snapshots and automated axe-core rules in rendered cases."),
67
+ "contrast": _check(combine_status(availability + contrasts), "captures",
68
+ "Viewport text and declared control/focus color pairs."),
69
+ "reflow-zoom": _check(combine_status(availability + layouts), "captures",
70
+ "Breakpoints, native 200%/400% zoom, overflow and declared anchors."),
71
+ "state-feedback": _check(combine_status(list(states.values())), "journeys",
72
+ "Declared loading, error, empty and disabled journeys."),
73
+ }
74
+ design = combine_status(availability + [
75
+ row["status"] for item in inspected for row in item["tokens"] + item["components"]
76
+ ])
77
+ return {
78
+ "status": combine_status([design, *(row["status"] for row in checks.values())]),
79
+ "design_system": {"status": design, "path": rules["path"], "sha256": rules["sha256"],
80
+ **({"token_source": rules["token_source"]} if rules.get("token_source") else {})},
81
+ "state_status": states,
82
+ "dynamic_evidence": {"checks": checks},
83
+ }
84
+
85
+
86
+ def make_manifest(*, root: Path, url: str, theme: str, rules: dict, planned: dict,
87
+ captures: list[dict], journeys: list[dict], keyboard: list[dict]) -> dict:
88
+ manifest = {
89
+ "schema_version": MANIFEST_SCHEMA, "run_id": uuid4().hex, "project_root": str(root.resolve()),
90
+ "url": url, "theme": theme, "design_rules": rules, "planned_cases": planned,
91
+ "captures": captures, "journeys": journeys, "keyboard_journeys": keyboard,
92
+ }
93
+ return {**manifest, **summarize_ui(manifest)}
94
+
95
+
96
+ def _bounded_bytes(path: Path, maximum: int) -> bytes:
97
+ if not path.is_file():
98
+ raise ValueError(f"expected an evidence file: {path.name}")
99
+ with path.open("rb") as stream:
100
+ data = stream.read(maximum + 1)
101
+ if len(data) > maximum:
102
+ raise ValueError(f"evidence file exceeds size limit: {path.name}")
103
+ return data
104
+
105
+
106
+ def _artifact_path(directory: Path, raw: str) -> Path:
107
+ if not isinstance(raw, str):
108
+ raise ValueError("evidence artifact path must be text")
109
+ path = directory / raw
110
+ resolved = path.resolve(strict=True)
111
+ if not resolved.is_relative_to(directory) or path != resolved:
112
+ raise ValueError("evidence artifact must be inside the receipt directory without symlinks")
113
+ return resolved
114
+
115
+
116
+ def screenshot_bytes(directory: Path, record: dict) -> bytes:
117
+ """Read a confined PNG and verify its recorded content hash."""
118
+ path = _artifact_path(directory.resolve(), record["path"])
119
+ data = _bounded_bytes(path, 20 * 1024 * 1024)
120
+ if not data.startswith(PNG_MAGIC) or hashlib.sha256(data).hexdigest() != record["sha256"]:
121
+ raise ValueError(f"invalid screenshot or SHA-256 mismatch: {path.name}")
122
+ return data
123
+
124
+
125
+ def _verify_cases(manifest: dict, directory: Path) -> None:
126
+ if not manifest["captures"]:
127
+ raise ValueError("UI manifest has no viewport captures")
128
+ names = set()
129
+ for group in CASE_GROUPS:
130
+ cases = manifest[group]
131
+ if not isinstance(cases, list) or len(cases) > 32:
132
+ raise ValueError(f"invalid UI case list: {group}")
133
+ if [case["name"] for case in cases] != manifest["planned_cases"][group]:
134
+ raise ValueError(f"UI case plan and receipts differ: {group}")
135
+ for case in cases:
136
+ if case["name"] in names or case["status"] not in STATUSES:
137
+ raise ValueError("duplicate UI case or invalid status")
138
+ names.add(case["name"])
139
+ if case["status"] == "BLOCKED":
140
+ continue
141
+ width, height = (case["viewport"][key] for key in ("width", "height"))
142
+ if type(width) is not int or type(height) is not int or min(width, height) <= 0:
143
+ raise ValueError(f"invalid viewport: {case['name']}")
144
+ if not case["url"] or not case["browser"]["version"]:
145
+ raise ValueError(f"missing browser identity: {case['name']}")
146
+ record, = case["evidence"]["screenshots"]
147
+ image = screenshot_bytes(directory, record)
148
+ size = tuple(int.from_bytes(image[index:index + 4], "big") for index in (16, 20))
149
+ if len(image) < 24 or size != (width, height):
150
+ raise ValueError(f"PNG and browser viewport dimensions disagree: {case['name']}")
151
+ inspection = case["inspection"]
152
+ axe = inspection["axe"]
153
+ if "story" in case:
154
+ verify_story_url(case["url"], case["story"])
155
+ if axe.get("scope") != STORY_ROOT:
156
+ raise ValueError(f"axe-core scope does not match Storybook canvas: {case['name']}")
157
+ if axe["version"] != AXE_VERSION or axe["sha256"] != AXE_SHA256:
158
+ raise ValueError(f"unrecognized axe-core receipt: {case['name']}")
159
+ if axe["status"] != "BLOCKED":
160
+ expected_axe = "FAIL" if axe["violations"] else (
161
+ "UNVERIFIED" if axe["incomplete"] or not axe["passed_rules"] else "PASS"
162
+ )
163
+ if axe["status"] != expected_axe:
164
+ raise ValueError(f"axe-core outcome and observations disagree: {case['name']}")
165
+ if group == "keyboard_journeys":
166
+ steps = [step["status"] for step in inspection["steps"]]
167
+ if len(steps) != inspection["planned_steps"]:
168
+ steps.append("UNVERIFIED")
169
+ if case["status"] != combine_status(steps):
170
+ raise ValueError(f"keyboard outcome and steps disagree: {case['name']}")
171
+ elif group == "journeys":
172
+ assertions = inspection["assertions"]
173
+ expected = "PASS" if assertions and all(row["passed"] is True for row in assertions) else "FAIL"
174
+ if case["status"] != expected:
175
+ raise ValueError(f"state outcome and assertions disagree: {case['name']}")
176
+
177
+
178
+ def write_ui_evidence(directory: Path, manifest: dict) -> None:
179
+ """Publish one hashed manifest and its companion evidence reference."""
180
+ directory = directory.resolve()
181
+ _verify_cases(manifest, directory)
182
+ path = directory / "manifest.json"
183
+ atomic_write_json(path, manifest)
184
+ atomic_write_json(directory / "dynamic-evidence.json", {
185
+ "schema_version": EVIDENCE_SCHEMA, "run_id": manifest["run_id"],
186
+ "manifest": path.name, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
187
+ })
188
+
189
+
190
+ def load_ui_evidence(evidence: Path, root: Path) -> dict:
191
+ """Verify the exact manifest, project, case coverage and screenshot digests."""
192
+ directory = evidence.parent.resolve()
193
+ reference = json.loads(_bounded_bytes(evidence, 32 * 1024))
194
+ if (not isinstance(reference, dict) or reference.get("schema_version") != EVIDENCE_SCHEMA
195
+ or reference.get("manifest") != "manifest.json"):
196
+ raise ValueError("dynamic evidence must be a versioned UI manifest reference")
197
+ path = _artifact_path(directory, reference["manifest"])
198
+ raw = _bounded_bytes(path, 32 * 1024 * 1024)
199
+ if hashlib.sha256(raw).hexdigest() != reference.get("sha256"):
200
+ raise ValueError("UI manifest SHA-256 mismatch")
201
+ manifest = json.loads(raw)
202
+ run_id = manifest.get("run_id")
203
+ if (manifest.get("schema_version") != MANIFEST_SCHEMA or not isinstance(run_id, str)
204
+ or not re.fullmatch(r"[0-9a-f]{32}", run_id) or reference.get("run_id") != run_id):
205
+ raise ValueError("UI run identity mismatch")
206
+ if manifest.get("project_root") != str(root.resolve()):
207
+ raise ValueError("UI evidence is for a different project root")
208
+ _verify_cases(manifest, directory)
209
+ verified = summarize_ui(manifest)["dynamic_evidence"]
210
+ if verified != manifest.get("dynamic_evidence"):
211
+ raise ValueError("UI check summary disagrees with browser observations")
212
+ return verified["checks"]