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.
- package/README.md +193 -185
- package/core/README.md +2 -2
- package/core/agent/README.md +2 -1
- package/core/agent/agent_artifacts.py +8 -6
- package/core/agent/agent_eval.py +136 -54
- package/core/agent/agent_execution.py +218 -52
- package/core/agent/agent_orchestrator.py +14 -8
- package/core/agent/agent_targets.py +8 -2
- package/core/agent/feature_baseline.py +150 -0
- package/core/assets/README.md +3 -2
- package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
- package/core/assets/axe-core/LICENSE.txt +362 -0
- package/core/assets/axe-core/UPSTREAM.md +10 -0
- package/core/assets/axe-core/axe.min.js +12 -0
- package/core/assets/bugx-hero-en.svg +74 -0
- package/core/assets/bugx-hero-zh.svg +74 -0
- package/core/assets/bugx-social-preview.svg +71 -0
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/assets/codex.png +0 -0
- package/core/assets/dsh.png +0 -0
- package/core/assets/webui-chatgpt.jpg +0 -0
- package/core/assets/webui-session.jpg +0 -0
- package/core/assets/webui-skills.jpg +0 -0
- package/core/assets/webui-studio.jpg +0 -0
- package/core/assets/webui-zcode.jpg +0 -0
- package/core/assets/zcode.png +0 -0
- package/core/audit_packs/README.md +2 -0
- package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
- package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
- package/core/audit_packs/pitfalls/go_backend.json +66 -0
- package/core/audit_packs/pitfalls/java_spring.json +64 -0
- package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
- package/core/audit_packs/pitfalls/python_web.json +82 -0
- package/core/autonomous_cve/SPEC.md +1 -1
- package/core/autonomous_cve/attack_graph_store.py +152 -106
- package/core/autonomous_cve/behavior_graph.py +8 -2
- package/core/autonomous_cve/verifier.py +4 -1
- package/core/bugx.md +1 -1
- package/core/bugx_paths.py +43 -8
- package/core/cli-help.txt +66 -0
- package/core/cloud_sync/SPEC.md +1 -1
- package/core/cloud_sync/cloud_client.py +81 -11
- package/core/cloud_sync/cloud_onboard.py +42 -1
- package/core/cloud_sync/consent.py +33 -3
- package/core/cloud_sync/flywheel_client.py +186 -15
- package/core/cloud_sync/network_transport.py +24 -3
- package/core/cloud_sync/sensitive_filter.py +2 -2
- package/core/cloud_sync/sync_push.py +12 -10
- package/core/contracts/AGENT_GUIDE.md +6 -9
- package/core/contracts/README.md +2 -2
- package/core/contracts/bugx-runtime-contract.md +1 -1
- package/core/contracts/bugx-worker.md +1 -1
- package/core/contracts/engine_gap_contracts.py +86 -3
- package/core/coverage/coverage_discovery.py +599 -29
- package/core/coverage/coverage_evidence.py +47 -0
- package/core/coverage/coverage_forensics.py +9 -0
- package/core/coverage/coverage_validate.py +6 -1
- package/core/dev_harness/SPEC.md +1 -1
- package/core/engine-integrity.json +670 -442
- package/core/fuzzing/concurrency_fuzzer.py +53 -0
- package/core/fuzzing/differential_oracle.py +562 -27
- package/core/fuzzing/fuzz_input.py +109 -6
- package/core/fuzzing/stateful_fuzzer.py +72 -0
- package/core/governance/secret_redactor.py +22 -10
- package/core/host_acp/SPEC.md +1 -1
- package/core/host_acp/__init__.py +4 -4
- package/core/host_acp/claude.py +59 -1
- package/core/host_acp/cline.py +64 -1
- package/core/host_acp/codex.py +56 -1
- package/core/host_acp/dsh.py +59 -1
- package/core/host_acp/opencode.py +56 -1
- package/core/host_acp/pi.py +59 -1
- package/core/host_acp/zcode.py +59 -1
- package/core/host_runtime/SPEC.md +1 -1
- package/core/host_runtime/adapters.py +1 -1
- package/core/host_runtime/cline.py +13 -0
- package/core/host_runtime/host_evaluators.py +44 -4
- package/core/host_runtime/host_probe.py +1 -1
- package/core/host_runtime/host_provider_arbitrator.py +116 -62
- package/core/host_runtime/host_registry.py +15 -8
- package/core/host_runtime/mcp_registry_gate.py +12 -1
- package/core/host_runtime/pi.py +102 -0
- package/core/host_runtime/provider_facts.py +66 -0
- package/core/hosts/SPEC.md +1 -1
- package/core/hosts/__init__.py +6 -2
- package/core/hosts/_dsh_usage.py +1 -1
- package/core/hosts/base.py +32 -4
- package/core/hosts/claude.py +55 -0
- package/core/hosts/cline.py +6 -2
- package/core/hosts/codex.py +58 -0
- package/core/hosts/dsh.py +9 -1
- package/core/hosts/opencode.py +6 -6
- package/core/hosts/pi.py +159 -2
- package/core/infra/README.md +4 -2
- package/core/infra/__init__.py +2 -0
- package/core/infra/build_info.py +22 -3
- package/core/infra/client_metadata.py +1 -1
- package/core/infra/json_utils.py +22 -0
- package/core/launch_phases/README.md +6 -3
- package/core/launch_phases/SPEC.md +1 -1
- package/core/launch_phases/common.py +21 -2
- package/core/launch_phases/finding_confirm_phase.py +170 -5
- package/core/launch_phases/finding_settlement.py +188 -1
- package/core/launch_phases/judge_phase.py +69 -12
- package/core/launch_phases/orchestrator_controls.py +11 -7
- package/core/launch_phases/post_coverage_sync.py +9 -2
- package/core/launch_phases/post_phase.py +144 -8
- package/core/launch_phases/post_receipt.py +12 -1
- package/core/launch_phases/pre_phase.py +3 -3
- package/core/launch_phases/pre_recon_scout.py +66 -36
- package/core/launch_phases/pre_state_builder.py +23 -176
- package/core/launch_phases/report_sharing.py +3 -7
- package/core/launch_phases/round_orchestrator.py +129 -58
- package/core/launch_phases/semantic_recon.py +545 -0
- package/core/launch_phases/session_runtime.py +56 -9
- package/core/launch_phases/startup_gates.py +36 -8
- package/core/launch_phases/startup_interaction.py +68 -12
- package/core/launch_phases/startup_version_gate.py +13 -3
- package/core/launch_phases/supervisor_bridge.py +46 -17
- package/core/launch_phases/supervisor_coverage.py +8 -2
- package/core/launch_phases/supervisor_degraded.py +1 -9
- package/core/launch_phases/verify_loop.py +767 -0
- package/core/launch_phases/worker_barriers.py +15 -5
- package/core/launch_phases/worker_orchestrator.py +105 -25
- package/core/launch_phases/worker_prior.py +115 -0
- package/core/ledger/README.md +2 -1
- package/core/ledger/SPEC.md +1 -1
- package/core/ledger/_facade.py +2 -1
- package/core/ledger/archive_ops.py +60 -2
- package/core/ledger/cli.py +6 -1
- package/core/ledger/export_ops.py +6 -1
- package/core/ledger/finding_confirmation.py +48 -6
- package/core/ledger/finding_lifecycle.py +428 -5
- package/core/ledger/finding_verification.py +555 -10
- package/core/ledger/fp_ledger.py +255 -0
- package/core/ledger/incidents.py +10 -4
- package/core/ledger/patterns.py +10 -7
- package/core/ledger/receipt_contract.py +17 -1
- package/core/ledger/sync_ops.py +21 -16
- package/core/ledger/tool_experience.py +2 -1
- package/core/ledger/verify_life.py +88 -17
- package/core/locales/en-US.json +2 -2
- package/core/locales/zh-CN.json +2 -2
- package/core/mcp_handlers/SPEC.md +1 -1
- package/core/mcp_handlers/base.py +23 -3
- package/core/mcp_handlers/channel_lifecycle.py +85 -30
- package/core/mcp_handlers/retrieval_handlers.py +11 -1
- package/core/mcp_handlers/rpc_server.py +6 -1
- package/core/mcp_handlers/supervisor_handlers.py +32 -6
- package/core/mcp_handlers/tool_table.py +15 -0
- package/core/mcp_runtime_support/environment.py +0 -38
- package/core/mcp_runtime_support/verifier.py +0 -52
- package/core/metadata.txt +2 -3
- package/core/planning/README.md +2 -1
- package/core/planning/domain_router.py +4 -2
- package/core/planning/dynamic_flow_analyzer.py +219 -14
- package/core/planning/judge_pipeline.py +87 -4
- package/core/planning/prompt_harness.py +57 -15
- package/core/planning/prompt_policy_engine.py +386 -0
- package/core/planning/spec_harvester.py +4 -4
- package/core/probes/INTERFACE.md +11 -1
- package/core/probes/SPEC.md +11 -1
- package/core/probes/__init__.py +46 -40
- package/core/probes/android_probe.py +177 -9
- package/core/probes/codebase_memory_probe.py +57 -0
- package/core/probes/desktop_probe.py +104 -0
- package/core/probes/differential_probe.py +99 -21
- package/core/probes/efficiency_probe.py +64 -0
- package/core/probes/ios_binary_probe.py +105 -1
- package/core/probes/memory_probe.py +66 -0
- package/core/probes/miniprogram_probe.py +75 -13
- package/core/probes/mobile_probe.py +215 -30
- package/core/probes/native_probe.py +88 -0
- package/core/probes/openwiki_probe.py +70 -0
- package/core/probes/pattern_probe.py +106 -0
- package/core/probes/platform_probe.py +81 -0
- package/core/probes/probe_registry.py +108 -7
- package/core/probes/sast_fixture_corpus.py +340 -0
- package/core/probes/sast_probe.py +553 -52
- package/core/probes/sast_rules.py +668 -28
- package/core/probes/sca_scanner.py +48 -0
- package/core/probes/ui_accessibility.py +149 -0
- package/core/probes/ui_audit.py +513 -0
- package/core/probes/ui_contract.py +273 -0
- package/core/probes/ui_evidence.py +212 -0
- package/core/probes/ui_measurements.py +314 -0
- package/core/probes/ui_repair.py +250 -0
- package/core/probes/ui_review.py +133 -0
- package/core/probes/ui_storybook.py +107 -0
- package/core/probes/ui_tokens.py +185 -0
- package/core/probes/ui_visual_diff.py +131 -0
- package/core/probes/web_probe.py +373 -18
- package/core/project_profiler/SPEC.md +1 -1
- package/core/project_profiler/arbitrator.py +6 -1
- package/core/project_profiler/detector.py +8 -1
- package/core/project_profiler/strategy.py +51 -15
- package/core/prompts/README.md +4 -2
- package/core/prompts/command_routing_en.md +2 -2
- package/core/prompts/command_routing_zh.md +2 -2
- package/core/prompts/policies/prompt_policies.json +101 -0
- package/core/prompts/stages/stage_repair.md +1 -1
- package/core/prompts/stages/stage_verify.defensive.md +42 -0
- package/core/prompts/stages/stage_verify.md +44 -0
- package/core/repair/README.md +1 -1
- package/core/repair/l7_repair_loop.py +1 -4
- package/core/repair/rsi_fixer.py +4 -4
- package/core/repair/rsi_loop.py +1 -3
- package/core/repair/rsi_repair.py +7 -7
- package/core/repair/rsi_scope.py +27 -8
- package/core/report_engine/SPEC.md +1 -1
- package/core/report_engine/attestation.py +8 -4
- package/core/report_engine/finding_report.py +2 -1
- package/core/report_engine/models.py +7 -9
- package/core/report_engine/report_share.py +0 -8
- package/core/report_engine/sast_bridge.py +2 -2
- package/core/report_engine/server.py +18 -8
- package/core/report_engine/web-conformance.md +123 -18
- package/core/report_engine/web_conformance.py +21 -52
- package/core/retrieval/README.md +2 -1
- package/core/retrieval/SPEC.md +1 -1
- package/core/retrieval/code_analyzer.py +50 -14
- package/core/retrieval/context_assembler.py +7 -1
- package/core/retrieval/knowledge_sync.py +108 -14
- package/core/retrieval/pitfall_packs.py +277 -0
- package/core/retrieval/symbol_index.py +25 -6
- package/core/retrieval/universal_code_matcher.py +234 -49
- package/core/runtime/README.md +1 -1
- package/core/runtime/bugx_logging.py +78 -7
- package/core/runtime/fixture_solidify.py +5 -10
- package/core/runtime/global_telemetry.py +20 -0
- package/core/runtime/incident_eval.py +1 -1
- package/core/runtime/model_runner.py +4 -41
- package/core/runtime/platform_adapter.py +2 -2
- package/core/runtime/prep_validate.py +4 -2
- package/core/runtime/project_settings.py +2 -1
- package/core/runtime/scenario_eval.py +50 -8
- package/core/skills/bugx_docs_mcp_server.py +3 -1
- package/core/skills/bugx_mcp_server.py +29 -2
- package/core/skills/tools_kb.py +1 -1
- package/core/supervisor/README.md +1 -1
- package/core/supervisor/SPEC.md +1 -1
- package/core/supervisor/budget_governor.py +503 -9
- package/core/supervisor/checkpoint_pipeline.py +248 -6
- package/core/supervisor/checkpoint_sync.py +13 -0
- package/core/supervisor/claim_events.py +1 -1
- package/core/supervisor/finding_workflow.py +22 -5
- package/core/supervisor/lease_manager.py +1 -1
- package/core/supervisor/lifecycle_blocks.py +6 -1
- package/core/supervisor/rejection_remedies.py +52 -5
- package/core/supervisor/serial_authorization.py +48 -4
- package/core/supervisor/task_scheduler.py +2 -2
- package/core/supervisor/worker_checkpoint.py +8 -1
- package/core/supervisor/worker_runtime.py +8 -2
- package/core/supervisor_types/worker_claim.py +9 -0
- package/core/webui/README.md +1 -1
- package/core/webui/SPEC.md +2 -1
- package/core/webui/adapters/claude.py +5 -1
- package/core/webui/adapters/cline.py +10 -2
- package/core/webui/adapters/codex.py +5 -1
- package/core/webui/adapters/dsh.py +5 -1
- package/core/webui/docs_session_service.py +2 -2
- package/core/webui/mcp_inspector.py +11 -7
- package/core/webui/static/00-base.css +1060 -0
- package/core/webui/static/01-monitoring.css +802 -0
- package/core/webui/static/02-header-actions.css +321 -0
- package/core/webui/static/03-trigger-popover.css +697 -0
- package/core/webui/static/04-composer.css +628 -0
- package/core/webui/static/05-skills-center.css +878 -0
- package/core/webui/static/06-mcp-center.css +623 -0
- package/core/webui/static/07-skill-detail.css +265 -0
- package/core/webui/static/08-files-management.css +167 -0
- package/core/webui/static/09-files-center.css +386 -0
- package/core/webui/static/10-icons.css +105 -0
- package/core/webui/static/11-project-options.css +185 -0
- package/core/webui/static/12-profile-tab.css +383 -0
- package/core/webui/static/design-tokens.css +113 -0
- package/core/webui/static/index.html +14 -1
- package/core/webui/workspace_service.py +1 -1
- package/docs/07_distribution/01_README_NPM.md +193 -185
- package/ecosystem/integrations/README.md +1 -1
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
- package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
- package/ecosystem/integrations/opencode/opencode.json +23 -12
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
- package/interfaces/bin/bugx.js +37 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -2
- package/interfaces/cli/bugx_cli/cli.py +172 -69
- package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
- package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
- package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
- package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
- package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
- package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
- package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
- package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
- package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
- package/interfaces/cli/bugx_cli/commands/project.py +6 -13
- package/interfaces/cli/bugx_cli/commands/report.py +2 -6
- package/interfaces/cli/bugx_cli/commands/system.py +524 -169
- package/interfaces/cli/bugx_cli/common.py +21 -15
- package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
- package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
- package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
- package/interfaces/cli/bugx_cli/infra/security.py +13 -6
- package/package.json +30 -15
- package/pyproject.toml +60 -9
- package/scripts/ensure-python.mjs +7 -7
- package/scripts/sync-version.mjs +10 -21
- package/scripts/test-npm-wrapper.mjs +1 -1
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/webui/static/project-settings.css +0 -6458
- package/docs/07_distribution/README.md +0 -16
- package/docs/README.md +0 -121
- package/interfaces/README.md +0 -143
- package/interfaces/bin/README.md +0 -35
- package/interfaces/cli/README.md +0 -90
- package/scripts/README.md +0 -118
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Audit a rendered Web UI against browser measurements and DESIGN.md."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
from importlib.util import find_spec
|
|
12
|
+
from multiprocessing import get_context
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
from urllib.parse import urljoin, urlsplit
|
|
16
|
+
|
|
17
|
+
if not __package__:
|
|
18
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
19
|
+
|
|
20
|
+
from core.probes.ui_accessibility import keyboard_journey, load_axe, scan_accessibility
|
|
21
|
+
from core.probes.ui_contract import IDENTIFIER, UIContract, UIContractError, load_ui_contract
|
|
22
|
+
from core.probes.ui_evidence import combine_status, make_manifest, write_ui_evidence
|
|
23
|
+
from core.probes.ui_measurements import CHECK_JOURNEY, MEASURE_UI
|
|
24
|
+
from core.probes.ui_repair import repair_tokens
|
|
25
|
+
from core.probes.ui_review import review_ui, validate_model_tag
|
|
26
|
+
from core.probes.ui_storybook import STORY_ROOT, StorybookError, StorybookIndex, read_storybook, wait_for_story
|
|
27
|
+
from core.probes.ui_visual_diff import compare_visual
|
|
28
|
+
from core.probes.web_probe import WebDynamicProbe
|
|
29
|
+
from core.secure_atomic import atomic_write_json
|
|
30
|
+
|
|
31
|
+
DEFAULT_VIEWPORTS = (
|
|
32
|
+
("desktop", 1440, 900), ("tablet", 768, 1024),
|
|
33
|
+
("mobile", 390, 844), ("landscape", 844, 390),
|
|
34
|
+
)
|
|
35
|
+
ZOOM_BASE = {"width": 1280, "height": 1024}
|
|
36
|
+
ZOOMS = (2, 4)
|
|
37
|
+
TIMEOUT_MS = 5000
|
|
38
|
+
# 浏览器冷启动(尤其带扩展的 persistent context 首次注册 service worker)
|
|
39
|
+
# 与本机的页面等待不是一个量级;共用 5s 会把启动慢误报成 zoom 用例 BLOCKED。
|
|
40
|
+
BROWSER_START_TIMEOUT_MS = 20000
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def origin(url: str) -> tuple[str, str, int]:
|
|
44
|
+
"""Return the canonical origin of an HTTP URL without embedded credentials."""
|
|
45
|
+
parsed = urlsplit(url)
|
|
46
|
+
if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username is not None:
|
|
47
|
+
raise UIContractError("expected an absolute HTTP(S) URL without credentials")
|
|
48
|
+
return parsed.scheme, parsed.hostname, parsed.port or (443 if parsed.scheme == "https" else 80)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _viewport(raw: str) -> tuple[str, int, int]:
|
|
52
|
+
try:
|
|
53
|
+
name, size = raw.split("=", 1)
|
|
54
|
+
width, height = map(int, size.lower().split("x", 1))
|
|
55
|
+
if IDENTIFIER.fullmatch(name) and not name.startswith(("zoom-", "journey-", "keyboard-")):
|
|
56
|
+
if 240 <= width <= 2560 and 240 <= height <= 1600:
|
|
57
|
+
return name, width, height
|
|
58
|
+
except ValueError:
|
|
59
|
+
pass
|
|
60
|
+
raise argparse.ArgumentTypeError("viewport must be NAME=WIDTHxHEIGHT, e.g. mobile=390x844")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _capture(
|
|
64
|
+
page: Any, name: str, url: str, directory: Path, browser_version: str,
|
|
65
|
+
*, axe: str, actions: list[dict] | None = None, after_navigation: Any = None,
|
|
66
|
+
inspect_page: Any = None, expect_origin: bool = False, masks: tuple[str, ...] = (),
|
|
67
|
+
story: dict | None = None,
|
|
68
|
+
) -> dict:
|
|
69
|
+
from playwright.sync_api import Error
|
|
70
|
+
|
|
71
|
+
def ready(current: Any) -> None:
|
|
72
|
+
if (expect_origin or story) and origin(current.url) != origin(url):
|
|
73
|
+
raise UIContractError("audit page navigated outside the configured origin")
|
|
74
|
+
if story:
|
|
75
|
+
wait_for_story(current, story, TIMEOUT_MS)
|
|
76
|
+
else:
|
|
77
|
+
current.locator("body").wait_for(state="visible", timeout=TIMEOUT_MS)
|
|
78
|
+
if after_navigation is not None:
|
|
79
|
+
after_navigation(current)
|
|
80
|
+
|
|
81
|
+
def inspect(current: Any) -> dict:
|
|
82
|
+
if (expect_origin or story) and origin(current.url) != origin(url):
|
|
83
|
+
raise UIContractError("audit action navigated outside the configured origin")
|
|
84
|
+
inspected = inspect_page(current) if inspect_page is not None else {}
|
|
85
|
+
if (expect_origin or story) and origin(current.url) != origin(url):
|
|
86
|
+
raise UIContractError("audit action navigated outside the configured origin")
|
|
87
|
+
if story:
|
|
88
|
+
wait_for_story(current, story, TIMEOUT_MS)
|
|
89
|
+
return {**inspected, "axe": scan_accessibility(current, axe, STORY_ROOT if story else None)}
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
raw = WebDynamicProbe.capture_browser_page(
|
|
93
|
+
page, url, actions=actions, timeout=TIMEOUT_MS / 1000,
|
|
94
|
+
screenshot_path=directory / f"{name}.png", screenshot_full_page=False,
|
|
95
|
+
screenshot_masks=masks,
|
|
96
|
+
browser_version=browser_version, after_navigation=ready, inspect_page=inspect,
|
|
97
|
+
)
|
|
98
|
+
except (Error, UIContractError, StorybookError) as exc:
|
|
99
|
+
return {"name": name, "status": "BLOCKED", "reason": str(exc).splitlines()[0][:400],
|
|
100
|
+
**({"story": story} if story else {})}
|
|
101
|
+
evidence = raw["evidence"]
|
|
102
|
+
# Keep browser diagnostics useful without retaining console messages or request URLs.
|
|
103
|
+
for key in ("console", "page_errors", "request_failures", "http_errors"):
|
|
104
|
+
evidence[f"{key}_count"] = len(evidence.pop(key))
|
|
105
|
+
status = raw["http_status"]
|
|
106
|
+
return {"name": name, "status": "PASS" if status and 200 <= status < 300 else "BLOCKED",
|
|
107
|
+
**raw, **({"story": story} if story else {})}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _measure(page: Any, name: str, contract: UIContract) -> dict:
|
|
111
|
+
from playwright.sync_api import TimeoutError
|
|
112
|
+
|
|
113
|
+
page.evaluate("() => Promise.race([document.fonts.ready, new Promise(r => setTimeout(r, 1000))])"
|
|
114
|
+
".then(() => undefined)")
|
|
115
|
+
details = page.evaluate(MEASURE_UI, {
|
|
116
|
+
"tokens": contract.tokens or {},
|
|
117
|
+
"components": [row for row in contract.components if not row.get("profiles") or name in row["profiles"]],
|
|
118
|
+
"contrast": list(contract.contrast), "reflow": list(contract.reflow),
|
|
119
|
+
})
|
|
120
|
+
actionable = [(rule, observed) for rule, observed in zip(contract.reflow, details["anchors"], strict=True)
|
|
121
|
+
if rule.get("interactive") and observed["status"] == "PASS"]
|
|
122
|
+
if not actionable:
|
|
123
|
+
return details
|
|
124
|
+
scroll = page.evaluate_handle("""selectors => {
|
|
125
|
+
const positions = new Map();
|
|
126
|
+
for (const selector of selectors) {
|
|
127
|
+
for (let node = document.querySelector(selector); node; node = node.parentElement) {
|
|
128
|
+
positions.set(node, [node.scrollLeft, node.scrollTop]);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return {x: scrollX, y: scrollY, positions};
|
|
132
|
+
}""", [rule["selector"] for rule, _ in actionable])
|
|
133
|
+
try:
|
|
134
|
+
for rule, observed in actionable:
|
|
135
|
+
try:
|
|
136
|
+
page.locator(rule["selector"]).click(trial=True, timeout=1200)
|
|
137
|
+
except TimeoutError:
|
|
138
|
+
observed.update(status="FAIL", reason="control failed Playwright actionability checks")
|
|
139
|
+
finally:
|
|
140
|
+
scroll.evaluate("""({x, y, positions}) => {
|
|
141
|
+
for (const [node, [left, top]] of positions)
|
|
142
|
+
node.scrollTo({left, top, behavior: 'instant'});
|
|
143
|
+
window.scrollTo({left: x, top: y, behavior: 'instant'});
|
|
144
|
+
}""")
|
|
145
|
+
scroll.dispose()
|
|
146
|
+
return details
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _zoom_extension(directory: Path) -> Path:
|
|
150
|
+
extension = directory / "extension"
|
|
151
|
+
extension.mkdir()
|
|
152
|
+
(extension / "manifest.json").write_text(json.dumps({
|
|
153
|
+
"manifest_version": 3, "name": "BugX audit page zoom", "version": "1.0",
|
|
154
|
+
"background": {"service_worker": "zoom.js"},
|
|
155
|
+
}), encoding="utf-8")
|
|
156
|
+
(extension / "zoom.js").write_text("chrome.runtime.onInstalled.addListener(() => {});\n",
|
|
157
|
+
encoding="utf-8")
|
|
158
|
+
return extension
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _zoom_capture(chromium: Any, extension: Path, profile: Path, factor: int, url: str,
|
|
162
|
+
directory: Path, contract: UIContract, theme: str, confined: bool,
|
|
163
|
+
axe: str, masks: tuple[str, ...], story: dict | None = None) -> dict:
|
|
164
|
+
from playwright.sync_api import Error
|
|
165
|
+
|
|
166
|
+
name = f"zoom-{factor * 100}"
|
|
167
|
+
try:
|
|
168
|
+
with chromium.launch_persistent_context(
|
|
169
|
+
str(profile), channel="chromium", headless=True, viewport=ZOOM_BASE,
|
|
170
|
+
color_scheme=theme, service_workers="block", timeout=BROWSER_START_TIMEOUT_MS,
|
|
171
|
+
args=[f"--disable-extensions-except={extension}", f"--load-extension={extension}"],
|
|
172
|
+
) as context:
|
|
173
|
+
worker = (context.service_workers[0] if context.service_workers else
|
|
174
|
+
context.wait_for_event("serviceworker", timeout=BROWSER_START_TIMEOUT_MS))
|
|
175
|
+
tab_id = worker.evaluate("""async () => {
|
|
176
|
+
const tabs = await chrome.tabs.query({});
|
|
177
|
+
if (tabs.length !== 1) throw new Error('Expected one isolated audit tab');
|
|
178
|
+
return tabs[0].id;
|
|
179
|
+
}""")
|
|
180
|
+
page = context.pages[0]
|
|
181
|
+
version = context.new_cdp_session(page).send("Browser.getVersion")["product"]
|
|
182
|
+
observed_factor = None
|
|
183
|
+
|
|
184
|
+
def zoom(current: Any) -> None:
|
|
185
|
+
nonlocal observed_factor
|
|
186
|
+
observed_factor = worker.evaluate("""async ({id, factor}) => {
|
|
187
|
+
await chrome.tabs.setZoomSettings(id, {mode: 'automatic', scope: 'per-tab'});
|
|
188
|
+
await chrome.tabs.setZoom(id, factor);
|
|
189
|
+
return chrome.tabs.getZoom(id);
|
|
190
|
+
}""", {"id": tab_id, "factor": factor})
|
|
191
|
+
if not math.isclose(observed_factor, factor):
|
|
192
|
+
raise UIContractError("Chromium did not apply the requested native zoom")
|
|
193
|
+
current.wait_for_function(
|
|
194
|
+
"""({width, height, factor}) =>
|
|
195
|
+
innerWidth === width && innerHeight === height &&
|
|
196
|
+
Math.abs(devicePixelRatio - factor) < 0.01""",
|
|
197
|
+
arg={"width": ZOOM_BASE["width"] // factor,
|
|
198
|
+
"height": ZOOM_BASE["height"] // factor, "factor": factor},
|
|
199
|
+
timeout=TIMEOUT_MS,
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
capture = _capture(
|
|
203
|
+
page, name, url, directory, version, axe=axe, actions=[{"type": "press", "key": "Tab"}],
|
|
204
|
+
after_navigation=zoom, inspect_page=lambda current: _measure(current, name, contract),
|
|
205
|
+
expect_origin=confined, masks=masks, story=story,
|
|
206
|
+
)
|
|
207
|
+
measured = capture.get("inspection", {}).get("viewport", {})
|
|
208
|
+
if capture["status"] == "PASS" and (
|
|
209
|
+
measured.get("width") != ZOOM_BASE["width"] // factor or
|
|
210
|
+
not math.isclose(measured.get("dpr", 0), factor, abs_tol=0.01)
|
|
211
|
+
):
|
|
212
|
+
capture.update(status="BLOCKED", reason="native zoom changed before capture")
|
|
213
|
+
return {**capture, "zoom": {"method": "chromium-tabs", "requested": factor,
|
|
214
|
+
"observed": observed_factor, "base_viewport": ZOOM_BASE}}
|
|
215
|
+
except Error as exc:
|
|
216
|
+
return {"name": name, "status": "BLOCKED", "reason": str(exc).splitlines()[0][:400]}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _journey(context: Any, url: str, directory: Path, version: str, rule: dict,
|
|
220
|
+
axe: str, masks: tuple[str, ...], *, keyboard: bool = False,
|
|
221
|
+
storybook: StorybookIndex | None = None, base_story: dict | None = None) -> dict:
|
|
222
|
+
from playwright.sync_api import TimeoutError
|
|
223
|
+
|
|
224
|
+
story = base_story
|
|
225
|
+
if "story" in rule:
|
|
226
|
+
if storybook is None:
|
|
227
|
+
raise UIContractError("story journeys require --storybook")
|
|
228
|
+
story = storybook.story(rule["story"])
|
|
229
|
+
elif "path" in rule:
|
|
230
|
+
story = None
|
|
231
|
+
target = story["preview_url"] if story else urljoin(url, rule.get("path", ""))
|
|
232
|
+
prefix = "keyboard" if keyboard else "journey"
|
|
233
|
+
name = f"{prefix}-{rule['id']}"
|
|
234
|
+
expected_origin = origin(target)
|
|
235
|
+
page = context.new_page()
|
|
236
|
+
|
|
237
|
+
def guard(route: Any) -> None:
|
|
238
|
+
request = route.request
|
|
239
|
+
if request.is_navigation_request() and request.frame == page.main_frame:
|
|
240
|
+
try:
|
|
241
|
+
same_origin = origin(request.url) == expected_origin
|
|
242
|
+
except ValueError:
|
|
243
|
+
same_origin = False
|
|
244
|
+
if not same_origin:
|
|
245
|
+
route.abort()
|
|
246
|
+
return
|
|
247
|
+
route.continue_()
|
|
248
|
+
|
|
249
|
+
page.route("**/*", guard)
|
|
250
|
+
|
|
251
|
+
def inspect(current: Any) -> dict:
|
|
252
|
+
if keyboard:
|
|
253
|
+
return keyboard_journey(current, rule["steps"])
|
|
254
|
+
checks = rule["expect"]
|
|
255
|
+
try:
|
|
256
|
+
result = current.wait_for_function(
|
|
257
|
+
f"(rules) => {{ const rows = ({CHECK_JOURNEY})(rules);"
|
|
258
|
+
" return rows.every(row => row.passed) ? rows : false; }",
|
|
259
|
+
arg=checks, timeout=2500,
|
|
260
|
+
)
|
|
261
|
+
return {"status": "PASS", "assertions": result.json_value()}
|
|
262
|
+
except TimeoutError:
|
|
263
|
+
return {"status": "FAIL", "assertions": current.evaluate(CHECK_JOURNEY, checks)}
|
|
264
|
+
|
|
265
|
+
actions = [{**action, "timeout": 2.5} for action in rule.get("actions", [])]
|
|
266
|
+
capture = _capture(page, name, target, directory, version, axe=axe, actions=actions, inspect_page=inspect,
|
|
267
|
+
expect_origin=True, masks=masks, story=story)
|
|
268
|
+
if capture["status"] == "PASS":
|
|
269
|
+
capture["status"] = capture["inspection"]["status"]
|
|
270
|
+
if not keyboard:
|
|
271
|
+
capture["state"] = rule["state"]
|
|
272
|
+
return capture
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def run_ui_audit(
|
|
276
|
+
url: str, directory: Path, viewports: tuple[tuple[str, int, int], ...],
|
|
277
|
+
contract: UIContract, *, root: Path, axe: str, theme: str,
|
|
278
|
+
run_journeys: bool, confined: bool = False, masks: tuple[str, ...] = (),
|
|
279
|
+
browser_temp: Path | None = None,
|
|
280
|
+
storybook: StorybookIndex | None = None, story_id: str | None = None,
|
|
281
|
+
) -> dict:
|
|
282
|
+
"""Render each viewport and journey in an isolated browser context."""
|
|
283
|
+
from playwright.sync_api import sync_playwright
|
|
284
|
+
|
|
285
|
+
captures: list[dict] = []
|
|
286
|
+
journeys: list[dict] = []
|
|
287
|
+
keyboard: list[dict] = []
|
|
288
|
+
state_plan = contract.journeys if run_journeys else ()
|
|
289
|
+
keyboard_plan = contract.keyboard if run_journeys else ()
|
|
290
|
+
story = storybook.story(story_id) if storybook is not None and story_id else None
|
|
291
|
+
with WebDynamicProbe.browser_slot(), sync_playwright() as playwright:
|
|
292
|
+
with playwright.chromium.launch(headless=True, timeout=BROWSER_START_TIMEOUT_MS) as browser:
|
|
293
|
+
for name, width, height in viewports:
|
|
294
|
+
with browser.new_context(
|
|
295
|
+
viewport={"width": width, "height": height}, color_scheme=theme, service_workers="block",
|
|
296
|
+
) as context:
|
|
297
|
+
captures.append(_capture(
|
|
298
|
+
context.new_page(), name, url, directory, browser.version, axe=axe,
|
|
299
|
+
actions=[{"type": "press", "key": "Tab"}], expect_origin=confined,
|
|
300
|
+
inspect_page=lambda page: _measure(page, name, contract), masks=masks, story=story,
|
|
301
|
+
))
|
|
302
|
+
for is_keyboard, plan, cases in (
|
|
303
|
+
(False, state_plan, journeys), (True, keyboard_plan, keyboard),
|
|
304
|
+
):
|
|
305
|
+
for rule in plan:
|
|
306
|
+
with browser.new_context(viewport=ZOOM_BASE, color_scheme=theme, service_workers="block") as context:
|
|
307
|
+
cases.append(_journey(context, url, directory, browser.version, rule,
|
|
308
|
+
axe, masks, keyboard=is_keyboard,
|
|
309
|
+
storybook=storybook, base_story=story))
|
|
310
|
+
with tempfile.TemporaryDirectory(prefix="bugx-ui-chromium-", dir=browser_temp) as temp:
|
|
311
|
+
zoom_root = Path(temp)
|
|
312
|
+
extension = _zoom_extension(zoom_root)
|
|
313
|
+
for factor in ZOOMS:
|
|
314
|
+
captures.append(_zoom_capture(playwright.chromium, extension, zoom_root / str(factor),
|
|
315
|
+
factor, url, directory, contract, theme, confined, axe, masks, story))
|
|
316
|
+
manifest = make_manifest(
|
|
317
|
+
root=root, url=url, theme=theme,
|
|
318
|
+
rules={"path": contract.source, "sha256": contract.sha256,
|
|
319
|
+
"contrast": bool(contract.contrast), "reflow": bool(contract.reflow),
|
|
320
|
+
"token_source": contract.token_source},
|
|
321
|
+
planned={
|
|
322
|
+
"captures": [name for name, _, _ in viewports] + [f"zoom-{factor * 100}" for factor in ZOOMS],
|
|
323
|
+
"journeys": [f"journey-{rule['id']}" for rule in state_plan],
|
|
324
|
+
"keyboard_journeys": [f"keyboard-{rule['id']}" for rule in keyboard_plan],
|
|
325
|
+
},
|
|
326
|
+
captures=captures, journeys=journeys, keyboard=keyboard,
|
|
327
|
+
)
|
|
328
|
+
if story:
|
|
329
|
+
manifest["storybook"] = story
|
|
330
|
+
return manifest
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _recheck_worker(receipt: Path, render_args: tuple, options: dict) -> None:
|
|
334
|
+
try:
|
|
335
|
+
result = {"manifest": run_ui_audit(*render_args, **options)}
|
|
336
|
+
except Exception as exc:
|
|
337
|
+
result = {"error": (str(exc) or type(exc).__name__).splitlines()[0][:400]}
|
|
338
|
+
atomic_write_json(receipt, result)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _bounded_recheck(render_args: tuple, options: dict, *, timeout: float = 35) -> dict:
|
|
342
|
+
"""Keep a browser hang in the read-only worker from holding a CSS transaction."""
|
|
343
|
+
with tempfile.TemporaryDirectory(prefix="bugx-ui-recheck-") as temporary:
|
|
344
|
+
directory = Path(temporary).resolve()
|
|
345
|
+
receipt = directory / "result.json"
|
|
346
|
+
process = get_context("spawn").Process(
|
|
347
|
+
target=_recheck_worker,
|
|
348
|
+
args=(receipt, render_args, {**options, "browser_temp": directory}),
|
|
349
|
+
)
|
|
350
|
+
process.start()
|
|
351
|
+
try:
|
|
352
|
+
process.join(timeout)
|
|
353
|
+
if process.is_alive():
|
|
354
|
+
raise TimeoutError(f"browser recheck exceeded {timeout:g} seconds")
|
|
355
|
+
if process.exitcode != 0 or not receipt.is_file():
|
|
356
|
+
raise RuntimeError(f"browser recheck exited without a receipt ({process.exitcode})")
|
|
357
|
+
result = json.loads(receipt.read_bytes())
|
|
358
|
+
if "error" in result:
|
|
359
|
+
raise RuntimeError(result["error"])
|
|
360
|
+
return result["manifest"]
|
|
361
|
+
finally:
|
|
362
|
+
if process.is_alive():
|
|
363
|
+
process.terminate()
|
|
364
|
+
process.join(2)
|
|
365
|
+
if process.is_alive():
|
|
366
|
+
process.kill()
|
|
367
|
+
process.join(2)
|
|
368
|
+
if process.is_alive():
|
|
369
|
+
raise RuntimeError("read-only browser recheck process could not be reaped")
|
|
370
|
+
process.close()
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _output_directory(path: Path | None) -> Path:
|
|
374
|
+
if path is None:
|
|
375
|
+
return Path(tempfile.mkdtemp(prefix="bugx-visual-audit-")).resolve()
|
|
376
|
+
result = path.expanduser().resolve()
|
|
377
|
+
result.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
378
|
+
if any(result.iterdir()):
|
|
379
|
+
raise UIContractError("--out-dir must be empty to preserve earlier evidence")
|
|
380
|
+
return result
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def main(argv: list[str] | None = None) -> int:
|
|
384
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
385
|
+
target = parser.add_mutually_exclusive_group(required=True)
|
|
386
|
+
target.add_argument("--url", help="target page URL")
|
|
387
|
+
target.add_argument("--storybook", help="running or published Storybook base URL")
|
|
388
|
+
story_mode = parser.add_mutually_exclusive_group()
|
|
389
|
+
story_mode.add_argument("--story", help="exact Storybook story ID to audit")
|
|
390
|
+
story_mode.add_argument("--list-stories", action="store_true", help="list renderable Storybook story IDs")
|
|
391
|
+
parser.add_argument("--root", type=Path, default=Path.cwd(), help="target project root")
|
|
392
|
+
parser.add_argument("--design", type=Path, help="design specification (default: root/DESIGN.md)")
|
|
393
|
+
parser.add_argument("--out-dir", type=Path, help="empty output directory (default: system temp)")
|
|
394
|
+
parser.add_argument("--viewport", action="append", type=_viewport, metavar="NAME=WIDTHxHEIGHT")
|
|
395
|
+
parser.add_argument("--color-scheme", choices=("light", "dark"), default="light")
|
|
396
|
+
parser.add_argument("--journeys", action="store_true", help="execute declared UI actions and assertions")
|
|
397
|
+
parser.add_argument("--vision-model", help="installed local Ollama vision model tag")
|
|
398
|
+
parser.add_argument("--vision-port", type=int, default=11434, help="local Ollama port")
|
|
399
|
+
parser.add_argument("--repair-css", type=Path, help="preview token edits to this project stylesheet")
|
|
400
|
+
parser.add_argument("--apply", action="store_true", help="apply and reverify the preview on a loopback page")
|
|
401
|
+
parser.add_argument("--reference-url", help="approved reference page or Storybook base URL")
|
|
402
|
+
parser.add_argument("--visual-mask", action="append", default=[], metavar="CSS_SELECTOR",
|
|
403
|
+
help="ignore the visible area of a dynamic element on both pages")
|
|
404
|
+
parser.add_argument("--visual-max-diff", type=float, metavar="FRACTION",
|
|
405
|
+
help="maximum fraction of changed pixels (default 0.001)")
|
|
406
|
+
parser.add_argument("--strict", action="store_true", help="return 2 for incomplete or failing rules")
|
|
407
|
+
args = parser.parse_args(argv)
|
|
408
|
+
try:
|
|
409
|
+
if bool(args.story or args.list_stories) != bool(args.storybook):
|
|
410
|
+
raise UIContractError("--storybook requires --story or --list-stories")
|
|
411
|
+
book = read_storybook(args.storybook) if args.storybook else None
|
|
412
|
+
if args.list_stories:
|
|
413
|
+
print(json.dumps({"status": "PASS", "index": book.index_url,
|
|
414
|
+
"index_version": book.version, "index_sha256": book.sha256,
|
|
415
|
+
"stories": list(book.stories.values())}, ensure_ascii=False, indent=2))
|
|
416
|
+
return 0
|
|
417
|
+
url = book.story(args.story)["preview_url"] if book else args.url
|
|
418
|
+
_, hostname, _ = origin(url)
|
|
419
|
+
if args.apply and (args.repair_css is None or hostname not in {"127.0.0.1", "::1", "localhost"}):
|
|
420
|
+
raise UIContractError("--apply requires --repair-css and a loopback URL")
|
|
421
|
+
if not 1 <= args.vision_port <= 65535:
|
|
422
|
+
raise UIContractError("--vision-port must be within 1–65535")
|
|
423
|
+
if args.vision_model is not None:
|
|
424
|
+
validate_model_tag(args.vision_model)
|
|
425
|
+
if args.reference_url is not None:
|
|
426
|
+
origin(args.reference_url)
|
|
427
|
+
if find_spec("PIL") is None:
|
|
428
|
+
raise UIContractError("visual comparison requires Pillow from the bugx-cli[ui] extra")
|
|
429
|
+
elif args.visual_mask or args.visual_max_diff is not None:
|
|
430
|
+
raise UIContractError("visual options require --reference-url")
|
|
431
|
+
masks = tuple(args.visual_mask)
|
|
432
|
+
if len(set(masks)) != len(masks) or len(masks) > 12 or any(
|
|
433
|
+
not selector.strip() or len(selector) > 256 for selector in masks
|
|
434
|
+
):
|
|
435
|
+
raise UIContractError("provide at most 12 unique, nonempty visual mask selectors")
|
|
436
|
+
limit = args.visual_max_diff if args.visual_max_diff is not None else 0.001
|
|
437
|
+
if not 0 <= limit <= 1:
|
|
438
|
+
raise UIContractError("--visual-max-diff must be within 0–1")
|
|
439
|
+
root = args.root.resolve(strict=True)
|
|
440
|
+
contract = load_ui_contract(root, args.design)
|
|
441
|
+
story_ids = {item["story"] for item in contract.journeys + contract.keyboard if "story" in item
|
|
442
|
+
and args.journeys}
|
|
443
|
+
if story_ids and book is None:
|
|
444
|
+
raise UIContractError("declared story journeys require --storybook")
|
|
445
|
+
for story_id in story_ids:
|
|
446
|
+
book.story(story_id)
|
|
447
|
+
reference_book = read_storybook(args.reference_url) if book and args.reference_url else None
|
|
448
|
+
reference_url = args.reference_url
|
|
449
|
+
if reference_book:
|
|
450
|
+
reference_url = reference_book.story(args.story)["preview_url"]
|
|
451
|
+
for story_id in story_ids:
|
|
452
|
+
reference_book.story(story_id)
|
|
453
|
+
axe = load_axe()
|
|
454
|
+
viewports = tuple(args.viewport or DEFAULT_VIEWPORTS)
|
|
455
|
+
names = {name for name, _, _ in viewports}
|
|
456
|
+
if len(names) != len(viewports) or len(names) > 8:
|
|
457
|
+
raise UIContractError("provide at most eight uniquely named viewports")
|
|
458
|
+
known = names | {f"zoom-{factor * 100}" for factor in ZOOMS}
|
|
459
|
+
for item in contract.components:
|
|
460
|
+
if set(item.get("profiles", [])) - known:
|
|
461
|
+
raise UIContractError(f"component {item['id']} references an unknown viewport")
|
|
462
|
+
directory = _output_directory(args.out_dir)
|
|
463
|
+
|
|
464
|
+
render_options = dict(root=root, axe=axe, theme=args.color_scheme, run_journeys=args.journeys,
|
|
465
|
+
confined=args.apply or reference_url is not None, masks=masks,
|
|
466
|
+
storybook=book, story_id=args.story)
|
|
467
|
+
|
|
468
|
+
reference = None
|
|
469
|
+
reference_dir = directory / "reference"
|
|
470
|
+
if reference_url is not None:
|
|
471
|
+
reference_dir.mkdir(mode=0o700)
|
|
472
|
+
reference = run_ui_audit(reference_url, reference_dir, viewports, contract,
|
|
473
|
+
**{**render_options, "storybook": reference_book})
|
|
474
|
+
write_ui_evidence(reference_dir, reference)
|
|
475
|
+
|
|
476
|
+
def scan(output: Path, *, recheck: bool = False) -> dict:
|
|
477
|
+
render_args = (url, output, viewports, contract)
|
|
478
|
+
result = (_bounded_recheck(render_args, render_options) if recheck
|
|
479
|
+
else run_ui_audit(*render_args, **render_options))
|
|
480
|
+
if reference is not None:
|
|
481
|
+
visual = compare_visual(reference, result, reference_dir, output, limit)
|
|
482
|
+
result.update(visual_regression=visual,
|
|
483
|
+
status=combine_status([result["status"], visual["status"]]))
|
|
484
|
+
return result
|
|
485
|
+
|
|
486
|
+
manifest = scan(directory)
|
|
487
|
+
if args.repair_css is not None:
|
|
488
|
+
atomic_write_json(directory / "before.json", manifest)
|
|
489
|
+
repair, verified = repair_tokens(root, args.repair_css, directory, contract, manifest,
|
|
490
|
+
apply=args.apply, verify=lambda output: scan(output, recheck=True))
|
|
491
|
+
manifest = {**(verified if verified is not None else manifest), "repair": repair}
|
|
492
|
+
manifest["visual_ai_review"] = review_ui(manifest["captures"], contract.markdown,
|
|
493
|
+
args.vision_model, args.vision_port)
|
|
494
|
+
write_ui_evidence(directory, manifest)
|
|
495
|
+
print(json.dumps({
|
|
496
|
+
"status": manifest["status"], "manifest": str(directory / "manifest.json"),
|
|
497
|
+
"dynamic_evidence": str(directory / "dynamic-evidence.json"),
|
|
498
|
+
"checks": manifest["dynamic_evidence"]["checks"], "design": manifest["design_system"],
|
|
499
|
+
"visual_review": manifest["visual_ai_review"]["status"], "repair": manifest.get("repair"),
|
|
500
|
+
"visual_regression": manifest.get("visual_regression", {}).get("status"),
|
|
501
|
+
"storybook": manifest.get("storybook"),
|
|
502
|
+
}, ensure_ascii=False, indent=2))
|
|
503
|
+
if manifest.get("repair", {}).get("status") in {"BLOCKED", "ROLLED_BACK", "RECOVERY_REQUIRED"}:
|
|
504
|
+
return 2
|
|
505
|
+
return 2 if args.strict and manifest["status"] != "PASS" else 0
|
|
506
|
+
except Exception as exc:
|
|
507
|
+
print(json.dumps({"status": "BLOCKED", "error": str(exc).splitlines()[0][:500]},
|
|
508
|
+
ensure_ascii=False), file=sys.stderr)
|
|
509
|
+
return 2
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
if __name__ == "__main__":
|
|
513
|
+
raise SystemExit(main())
|