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,314 @@
1
+ """Browser-side measurements for the Web UI audit."""
2
+
3
+ # The script receives validated data as an argument. Selectors and CSS values are
4
+ # never interpolated into JavaScript source.
5
+ MEASURE_UI = r"""
6
+ ({tokens, components, contrast, reflow}) => {
7
+ const root = document.documentElement;
8
+ const style = (node) => getComputedStyle(node);
9
+ const limit = 400;
10
+ const rect = (node) => node.getBoundingClientRect();
11
+ const visible = (node) => {
12
+ const {width, height} = rect(node);
13
+ return width > 0 && height > 0 && node.checkVisibility({
14
+ checkOpacity: true, checkVisibilityCSS: true,
15
+ });
16
+ };
17
+ const locator = (node) => {
18
+ const parts = [];
19
+ for (let el = node; el && el !== root; el = el.parentElement) {
20
+ if (el.id) {
21
+ const id = '#' + CSS.escape(el.id);
22
+ if (document.querySelectorAll(id).length === 1) {
23
+ parts.unshift(id);
24
+ break;
25
+ }
26
+ }
27
+ let position = 1;
28
+ for (let sib = el.previousElementSibling; sib; sib = sib.previousElementSibling) {
29
+ if (sib.localName === el.localName) position++;
30
+ }
31
+ parts.unshift(CSS.escape(el.localName) + ':nth-of-type(' + position + ')');
32
+ }
33
+ return parts.join(' > ') || 'html';
34
+ };
35
+ const round = (value) => Number(value.toFixed(3));
36
+ const measured = (id, status, detail) => ({id, status, ...detail});
37
+ const outcome = (rows) => rows.some((row) => row.status === 'FAIL') ? 'FAIL'
38
+ : !rows.length || rows.some((row) => row.status === 'UNVERIFIED') ? 'UNVERIFIED' : 'PASS';
39
+
40
+ const canvas = document.createElement('canvas').getContext('2d');
41
+ const rgba = (value) => {
42
+ if (!value || !CSS.supports('color', value) || /currentcolor|var\(/i.test(value)) return null;
43
+ // A wide-gamut canvas color is serialized as color(...). Limit WCAG
44
+ // arithmetic to colors the browser resolves to sRGB, without clamping.
45
+ canvas.fillStyle = '#010203';
46
+ canvas.fillStyle = value;
47
+ const normalized = canvas.fillStyle;
48
+ if (normalized === '#010203') {
49
+ canvas.fillStyle = '#040506';
50
+ canvas.fillStyle = value;
51
+ if (canvas.fillStyle === '#040506') return null;
52
+ }
53
+ if (/^#[0-9a-f]{6}$/i.test(normalized)) {
54
+ return [1, 3, 5].map((start) => parseInt(normalized.slice(start, start + 2), 16)).concat(1);
55
+ }
56
+ const match = /^rgba?\(\s*(\d+(?:\.\d+)?),\s*(\d+(?:\.\d+)?),\s*(\d+(?:\.\d+)?)(?:,\s*(\d*(?:\.\d+)?))?\)$/.exec(normalized);
57
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3]), Number(match[4] ?? 1)] : null;
58
+ };
59
+ const over = (front, back) => {
60
+ const alpha = front[3] + back[3] * (1 - front[3]);
61
+ if (!alpha) return [0, 0, 0, 0];
62
+ return front.slice(0, 3).map((v, i) =>
63
+ (v * front[3] + back[i] * back[3] * (1 - front[3])) / alpha).concat(alpha);
64
+ };
65
+ const scheme = style(root).colorScheme.split(/\s+/);
66
+ const darkCanvas = scheme.includes('dark') &&
67
+ (!scheme.includes('light') || matchMedia('(prefers-color-scheme: dark)').matches);
68
+ const base = [255, 255, 255, 1];
69
+ const simplePaint = (el) => {
70
+ for (let node = el; node; node = node.parentElement) {
71
+ const s = style(node);
72
+ if (s.opacity !== '1' || s.filter !== 'none' || s.backdropFilter !== 'none' ||
73
+ s.mixBlendMode !== 'normal' || s.maskImage !== 'none') return false;
74
+ for (const pseudo of ['::before', '::after']) {
75
+ const p = getComputedStyle(node, pseudo);
76
+ if (p.content !== 'none' && p.content !== 'normal' &&
77
+ (p.backgroundImage !== 'none' || p.backgroundColor !== 'rgba(0, 0, 0, 0)' ||
78
+ p.position === 'absolute' || p.position === 'fixed')) return false;
79
+ }
80
+ }
81
+ return true;
82
+ };
83
+ const surface = (el) => {
84
+ const layers = [];
85
+ for (let node = el; node; node = node.parentElement) {
86
+ const s = style(node);
87
+ if (s.backgroundImage !== 'none' || s.backgroundClip === 'text') return null;
88
+ const paint = rgba(s.backgroundColor);
89
+ if (!paint) return null;
90
+ layers.push(paint);
91
+ if (paint[3] === 1) return layers.reverse().reduce((under, top) => over(top, under), base);
92
+ }
93
+ // Do not infer a dark canvas color from the OS/Chromium theme.
94
+ return darkCanvas ? null : layers.reverse().reduce((under, top) => over(top, under), base);
95
+ };
96
+ const luminance = (rgb) => rgb.slice(0, 3).reduce((sum, value, i) => {
97
+ const v = value / 255;
98
+ const linear = v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
99
+ return sum + linear * [0.2126, 0.7152, 0.0722][i];
100
+ }, 0);
101
+ const ratio = (fg, bg) => {
102
+ const light = luminance(over(fg, bg));
103
+ const dark = luminance(bg);
104
+ return (Math.max(light, dark) + 0.05) / (Math.min(light, dark) + 0.05);
105
+ };
106
+ const obscured = (node, box) => {
107
+ const x = (Math.max(box.left, 0) + Math.min(box.right, innerWidth)) / 2;
108
+ const y = (Math.max(box.top, 0) + Math.min(box.bottom, innerHeight)) / 2;
109
+ const hit = document.elementFromPoint(x, y);
110
+ return hit && !node.contains(hit) && !hit.contains(node);
111
+ };
112
+ const onScreen = (box) =>
113
+ box.width > 1 && box.height > 1 && box.right > 0 && box.bottom > 0 &&
114
+ box.left < innerWidth && box.top < innerHeight;
115
+ const inactive = (node) => node.closest(':disabled,[aria-disabled="true"]');
116
+ const textFailures = [];
117
+ const textUnknown = [];
118
+ let samples = 0;
119
+ let unknownCount = 0;
120
+ let minimumRatio = null;
121
+ const unknown = (node, reason) => {
122
+ unknownCount++;
123
+ if (textUnknown.length < 24) textUnknown.push({selector: locator(node), reason});
124
+ };
125
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
126
+ let visited = 0;
127
+ let textNode;
128
+ while ((textNode = walker.nextNode())) {
129
+ if (++visited > 12000 || samples + unknownCount >= limit) {
130
+ unknown(document.body, 'sample-limit');
131
+ break;
132
+ }
133
+ const node = textNode.parentElement;
134
+ if (!textNode.data.trim() || !node || node.closest('script,style,noscript,template,option,svg') ||
135
+ !visible(node) || inactive(node)) continue;
136
+ const range = document.createRange();
137
+ range.selectNodeContents(textNode);
138
+ const boxes = Array.from(range.getClientRects()).filter(onScreen);
139
+ if (!boxes.length) continue;
140
+ const s = style(node);
141
+ const fg = rgba(s.webkitTextFillColor || s.color);
142
+ const bg = simplePaint(node) && !boxes.some((box) => obscured(node, box)) ? surface(node) : null;
143
+ if (!fg || !fg[3] || !bg || s.textShadow !== 'none' || s.webkitTextStrokeWidth !== '0px') {
144
+ unknown(node, 'complex-text-paint');
145
+ continue;
146
+ }
147
+ const size = parseFloat(s.fontSize);
148
+ const bold = parseFloat(s.fontWeight) >= 700;
149
+ const threshold = size >= 24 || (size >= 56 / 3 - 0.001 && bold) ? 3 : 4.5;
150
+ const value = ratio(fg, bg);
151
+ samples++;
152
+ minimumRatio = minimumRatio === null ? value : Math.min(value, minimumRatio);
153
+ if (value < threshold) {
154
+ textFailures.push({selector: locator(node), ratio: value, threshold, fg, bg});
155
+ }
156
+ }
157
+ for (const node of document.querySelectorAll('iframe,canvas,svg text,input,textarea,select')) {
158
+ if (!onScreen(rect(node)) || !visible(node) || inactive(node)) continue;
159
+ if (node.matches('iframe,canvas,svg text') || node.value || node.placeholder ||
160
+ node.matches('input[type=submit],input[type=reset]')) {
161
+ unknown(node, 'embedded-or-native-text');
162
+ }
163
+ if (unknownCount >= limit) break;
164
+ }
165
+ const textContrast = {
166
+ status: textFailures.length ? 'FAIL' : !samples || unknownCount ? 'UNVERIFIED' : 'PASS',
167
+ samples, unknown_count: unknownCount, unknown: textUnknown, failures: textFailures,
168
+ min_ratio: minimumRatio === null ? null : round(minimumRatio),
169
+ };
170
+
171
+ const rootStyle = style(root);
172
+ const sameColor = (left, right) => {
173
+ const first = rgba(left), second = rgba(right);
174
+ return first && second && first.every((n, i) => Math.abs(n - second[i]) < 0.0001);
175
+ };
176
+ const tokenChecks = Object.entries(tokens).map(([name, expected]) => {
177
+ const actual = rootStyle.getPropertyValue(name).trim();
178
+ const matches = actual && (expected === null || actual === expected || sameColor(actual, expected));
179
+ return measured(name, matches ? 'PASS' : 'FAIL', {actual, expected});
180
+ });
181
+ const cssLength = (value, property, computed) => {
182
+ const match = /^(-?\d+(?:\.\d+)?)(px|rem|em)?$/.exec(value);
183
+ if (!match) return null;
184
+ const n = Number(match[1]);
185
+ if (match[2] === 'rem') return n * parseFloat(rootStyle.fontSize);
186
+ if (match[2] === 'em' && property !== 'font-size') return n * parseFloat(computed.fontSize);
187
+ return match[2] === 'px' || n === 0 ? n : null;
188
+ };
189
+ const compareCSS = (property, expected, actual, computed) => {
190
+ if (!expected || !CSS.supports(property, expected)) return 'UNVERIFIED';
191
+ if (actual === expected || (property.endsWith('color') && sameColor(actual, expected))) return 'PASS';
192
+ if (property === 'font-family') {
193
+ const families = (value) => value.replace(/['"]/g, '').toLowerCase().split(',').map(s => s.trim());
194
+ return String(families(actual)) === String(families(expected)) ? 'PASS' : 'FAIL';
195
+ }
196
+ if (property === 'font-weight') {
197
+ const weight = (value) => ({normal: '400', bold: '700'})[value] || value;
198
+ return weight(actual) === weight(expected) ? 'PASS' : 'FAIL';
199
+ }
200
+ const left = cssLength(actual, property, computed), right = cssLength(expected, property, computed);
201
+ if (left !== null && right !== null) return Math.abs(left - right) <= 0.02 ? 'PASS' : 'FAIL';
202
+ if (/var\(|calc\(|%|(?:^|\d)em\b|currentcolor/i.test(expected)) return 'UNVERIFIED';
203
+ return 'FAIL';
204
+ };
205
+ const componentChecks = components.map((rule) => {
206
+ const matches = Array.from(document.querySelectorAll(rule.selector)).filter(visible);
207
+ const checks = [];
208
+ for (const node of matches.slice(0, 48)) {
209
+ const s = style(node);
210
+ for (const [prop, ref] of Object.entries(rule.styles || {})) {
211
+ const expected = ref.startsWith('--') ? s.getPropertyValue(ref).trim() : ref;
212
+ const actual = s.getPropertyValue(prop).trim();
213
+ const status = compareCSS(prop, expected, actual, s);
214
+ checks.push(measured(prop, status, {selector: locator(node), actual, expected, reference: ref}));
215
+ }
216
+ }
217
+ if (rule.align) {
218
+ const axis = (box) => rule.align === 'center-x' ? box.left + box.width / 2 : box[rule.align];
219
+ const coordinates = matches.slice(0, 48).map((node) => axis(rect(node)));
220
+ const spread = coordinates.length >= 2 ? Math.max(...coordinates) - Math.min(...coordinates) : null;
221
+ const tolerance = rule.tolerance_px ?? 2;
222
+ const status = spread === null ? 'UNVERIFIED' : spread <= tolerance ? 'PASS' : 'FAIL';
223
+ checks.push(measured('alignment', status, {axis: rule.align, spread_px: spread, tolerance_px: tolerance}));
224
+ }
225
+ if (matches.length > 48) checks.push(measured('coverage', 'UNVERIFIED', {reason: 'component sample limit'}));
226
+ const status = matches.length ? outcome(checks) : 'FAIL';
227
+ return measured(rule.id, status, {selector: rule.selector, matches: matches.length, checks});
228
+ });
229
+
230
+ const active = document.activeElement;
231
+ const keyboardFocus = !!active && active !== document.body && active !== root &&
232
+ visible(active) && active.matches(':focus-visible') && onScreen(rect(active)) &&
233
+ !obscured(active, rect(active));
234
+ const nonText = contrast.map((rule) => {
235
+ const matches = Array.from(document.querySelectorAll(rule.selector)).filter(visible);
236
+ const checks = [];
237
+ for (const node of matches.slice(0, 16)) {
238
+ const selector = locator(node);
239
+ if (rule.focus) node.focus({preventScroll: true});
240
+ if (rule.focus && (document.activeElement !== node || !node.matches(':focus-visible'))) {
241
+ checks.push(measured('focus', 'UNVERIFIED', {selector, reason: 'focus state unavailable'}));
242
+ continue;
243
+ }
244
+ const s = style(node);
245
+ const kind = rule.property;
246
+ if ((kind === 'outline-color' && (!parseFloat(s.outlineWidth) || s.outlineStyle === 'none')) ||
247
+ (kind === 'border-top-color' && (!parseFloat(s.borderTopWidth) || s.borderTopStyle === 'none'))) {
248
+ checks.push(measured(kind, 'FAIL', {selector, reason: 'declared indicator absent'}));
249
+ continue;
250
+ }
251
+ const fg = kind === 'background-color' && s.backgroundImage !== 'none' ?
252
+ null : rgba(s.getPropertyValue(kind));
253
+ const bg = simplePaint(node) && surface(rule.against === 'self' ? node : node.parentElement);
254
+ const value = fg && bg ? ratio(fg, bg) : null;
255
+ checks.push(measured(kind, value === null ? 'UNVERIFIED' : value < 3 ? 'FAIL' : 'PASS',
256
+ {selector, ratio: value, threshold: 3, fg, bg}));
257
+ }
258
+ if (matches.length > 16) checks.push(measured('coverage', 'UNVERIFIED', {reason: 'indicator sample limit'}));
259
+ return measured(rule.id, outcome(checks), {selector: rule.selector, matches: matches.length, checks});
260
+ });
261
+ if (active instanceof HTMLElement && active !== document.activeElement) {
262
+ if (active === document.body) document.activeElement?.blur();
263
+ else active.focus({preventScroll: true});
264
+ }
265
+
266
+ const viewport = {
267
+ width: innerWidth, height: innerHeight, dpr: devicePixelRatio,
268
+ client_width: root.clientWidth, scroll_width: Math.max(root.scrollWidth, document.body.scrollWidth),
269
+ };
270
+ const horizontalOverflow = Math.max(0, viewport.scroll_width - viewport.client_width);
271
+ const anchors = reflow.map((rule) => {
272
+ const matches = document.querySelectorAll(rule.selector);
273
+ const node = matches.length === 1 ? matches[0] : null;
274
+ const shown = !!node && visible(node);
275
+ const box = shown ? rect(node) : null;
276
+ const outside = !!box && (box.left + scrollX < -1 || box.right + scrollX > root.clientWidth + 1);
277
+ let clipped = false;
278
+ for (let parent = node; box && parent && parent !== document.body; parent = parent.parentElement) {
279
+ const s = style(parent), bounds = rect(parent);
280
+ const clippedAxis = (overflow) => overflow === 'hidden' || overflow === 'clip';
281
+ clipped ||= clippedAxis(s.overflowX) &&
282
+ (box.left < bounds.left - 1 || box.right > bounds.right + 1 ||
283
+ (parent === node && parent.scrollWidth > parent.clientWidth + 1));
284
+ clipped ||= clippedAxis(s.overflowY) &&
285
+ (box.top < bounds.top - 1 || box.bottom > bounds.bottom + 1 ||
286
+ (parent === node && parent.scrollHeight > parent.clientHeight + 1));
287
+ }
288
+ return measured(rule.id, shown && !outside && !clipped ? 'PASS' : 'FAIL', {
289
+ selector: rule.selector, matches: matches.length, shown, outside, clipped,
290
+ rect: box ? {x: round(box.x), y: round(box.y), width: round(box.width), height: round(box.height)} : null,
291
+ });
292
+ });
293
+ return {viewport, horizontal_overflow_px: horizontalOverflow, anchors, keyboard_focus: keyboardFocus,
294
+ text_contrast: textContrast, non_text_contrast: nonText, tokens: tokenChecks, components: componentChecks};
295
+ }
296
+ """
297
+
298
+ CHECK_JOURNEY = r"""
299
+ (checks) => {
300
+ return checks.map((rule) => {
301
+ const matches = document.querySelectorAll(rule.selector);
302
+ const node = matches.length === 1 ? matches[0] : null;
303
+ const box = node?.getBoundingClientRect();
304
+ const visible = !!box && box.width > 0 && box.height > 0 &&
305
+ node.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});
306
+ const status = (rule.visible === false ? !visible && matches.length <= 1 : visible) &&
307
+ (rule.text === undefined || (node.innerText || '').includes(rule.text)) &&
308
+ (rule.disabled === undefined ||
309
+ !!node.closest(':disabled,[aria-disabled="true"]') === rule.disabled) &&
310
+ Object.entries(rule.attributes || {}).every(([name, value]) => node.getAttribute(name) === value);
311
+ return {selector: rule.selector, matches: matches.length, visible, passed: status};
312
+ });
313
+ }
314
+ """
@@ -0,0 +1,250 @@
1
+ """Plan and verify bounded CSS token repairs for the UI audit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+ import hashlib
7
+ import os
8
+ import re
9
+ import signal
10
+ import stat
11
+ from collections import Counter
12
+ from pathlib import Path
13
+ from typing import Callable
14
+
15
+ from core.probes.ui_contract import UIContract, UIContractError
16
+ from core.probes.ui_evidence import CASE_GROUPS, write_ui_evidence
17
+ from core.probes.ui_visual_diff import visual_comparable, visual_regressions
18
+ from core.secure_atomic import atomic_write_bytes, atomic_write_json, reject_symlink_components
19
+
20
+ _LITERAL = re.compile(r"(?:#[0-9a-fA-F]{3,8}|[-\w. %]+|(?:rgba?|hsla?)\([-+\d.,% /]+\))")
21
+ _DECLARATION = re.compile(r"(?m)^[ \t]*(--[a-zA-Z_][\w-]*)[ \t]*:[ \t]*([^;\r\n]+);[ \t]*\r?$")
22
+ _RANK = {"PASS": 0, "UNVERIFIED": 1, "BLOCKED": 2, "FAIL": 3}
23
+
24
+
25
+ def _fingerprint(data: bytes) -> str:
26
+ return hashlib.sha256(data).hexdigest()
27
+
28
+
29
+ def _target(root: Path, css: Path) -> Path:
30
+ path = Path(os.path.abspath(root / css))
31
+ if not path.is_relative_to(root) or path.suffix.lower() != ".css":
32
+ raise UIContractError("repair target must be a CSS file within the project")
33
+ reject_symlink_components(path)
34
+ if not path.is_file() or path.resolve(strict=True) != path:
35
+ raise UIContractError("repair target must be an existing regular file without symlink ancestors")
36
+ return path
37
+
38
+
39
+ def _proposal(before: bytes, contract: UIContract, baseline: dict) -> tuple[bytes, list[str]]:
40
+ source = before.decode("utf-8")
41
+ # Keep source offsets when masking comments, so only the value span changes.
42
+ masked = re.sub(r"/\*.*?\*/", lambda match: re.sub(r"[^\r\n]", " ", match[0]), source, flags=re.S)
43
+ block = re.fullmatch(r"\s*:root\s*\{([^{}]*)\}\s*", masked)
44
+ if not block:
45
+ raise UIContractError("repair requires a token stylesheet with a single :root block")
46
+ declarations: dict[str, list[tuple[int, int]]] = {}
47
+ for match in _DECLARATION.finditer(block[1]):
48
+ start, end = match.span(2)
49
+ declarations.setdefault(match[1], []).append((block.start(1) + start, block.start(1) + end))
50
+ replacements = []
51
+ for name, desired in (contract.tokens or {}).items():
52
+ spans = declarations.get(name, [])
53
+ if not desired or not _LITERAL.fullmatch(desired) or len(spans) != 1:
54
+ continue
55
+ start, end = spans[0]
56
+ old = source[start:end]
57
+ if not _LITERAL.fullmatch(old.strip()) or old == desired:
58
+ continue
59
+ rows = [
60
+ row for capture in baseline["captures"] for row in capture["inspection"]["tokens"]
61
+ if row["id"] == name
62
+ ]
63
+ if rows and all(row["status"] == "FAIL" and row["actual"] == old.strip() for row in rows):
64
+ replacements.append((start, start + len(old.rstrip()), desired, name))
65
+ for start, end, value, _ in sorted(replacements, reverse=True):
66
+ source = source[:start] + value + source[end:]
67
+ return source.encode(), [item[-1] for item in replacements]
68
+
69
+
70
+ def _measurements(capture: dict) -> dict[tuple, str]:
71
+ report = capture["inspection"]
72
+ rows = {(group, row["id"]): row["status"] for group in ("tokens", "anchors")
73
+ for row in report[group]}
74
+ for group in ("components", "non_text_contrast"):
75
+ for item in report[group]:
76
+ rows[(group, item["id"])] = item["status"]
77
+ for row in item["checks"]:
78
+ rows[(group, item["id"], row.get("selector"), row["id"])] = row["status"]
79
+ return rows
80
+
81
+
82
+ def _contrast_failures(check: dict) -> Counter:
83
+ return Counter((item["selector"], item["threshold"]) for item in check["failures"])
84
+
85
+
86
+ def _worsened_contrast(before: dict, after: dict) -> bool:
87
+ first, second = before["min_ratio"], after["min_ratio"]
88
+ return bool(after["failures"] and first is not None and second is not None and second < first)
89
+
90
+
91
+ def _regressions(before: dict, after: dict, names: list[str], directory: Path) -> list[str]:
92
+ previous = {row["name"]: row for row in before["captures"]}
93
+ current = {row["name"]: row for row in after["captures"]}
94
+ if set(previous) != set(current):
95
+ return ["viewport set changed"]
96
+ reasons = []
97
+ for name, old in previous.items():
98
+ new = current[name]
99
+ if new["status"] != "PASS" or new["url"] != old["url"]:
100
+ reasons.append(f"{name}: target capture unavailable or changed")
101
+ continue
102
+ old_rows, new_rows = _measurements(old), _measurements(new)
103
+ if any(new_rows.get(("tokens", token)) != "PASS" for token in names):
104
+ reasons.append(f"{name}: edited token did not match its expected rendered value")
105
+ if set(old_rows) - set(new_rows) or any(
106
+ _RANK[status] > _RANK[old_rows.get(key, "PASS")] for key, status in new_rows.items()
107
+ ):
108
+ reasons.append(f"{name}: design, layout or indicator measurement regressed")
109
+ first, second = old["inspection"], new["inspection"]
110
+ old_text, new_text = first["text_contrast"], second["text_contrast"]
111
+ if (second["horizontal_overflow_px"] > max(1, first["horizontal_overflow_px"]) or
112
+ old_text["samples"] > new_text["samples"] or
113
+ new_text["unknown_count"] > old_text["unknown_count"] or
114
+ _contrast_failures(new_text) - _contrast_failures(old_text) or
115
+ _worsened_contrast(old_text, new_text) or
116
+ (first["keyboard_focus"] and not second["keyboard_focus"]) or
117
+ any(new["evidence"][f"{key}_count"] > old["evidence"][f"{key}_count"]
118
+ for key in ("console", "page_errors", "request_failures", "http_errors"))):
119
+ reasons.append(f"{name}: overflow, focus, contrast coverage or runtime regressed")
120
+ for group in CASE_GROUPS:
121
+ old_cases = {row["name"]: row for row in before[group]}
122
+ new_cases = {row["name"]: row for row in after[group]}
123
+ if old_cases.keys() != new_cases.keys():
124
+ reasons.append(f"{group}: audited case set changed")
125
+ continue
126
+ for name, new in new_cases.items():
127
+ old = old_cases[name]
128
+ if _RANK[new["status"]] > _RANK[old["status"]]:
129
+ reasons.append(f"{name}: case result regressed")
130
+ first = old.get("inspection", {}).get("axe", {})
131
+ second = new.get("inspection", {}).get("axe", {})
132
+ if second and (_RANK[second["status"]] > _RANK[first.get("status", "UNVERIFIED")]
133
+ or _axe_findings(second) - _axe_findings(first)):
134
+ reasons.append(f"{name}: accessibility findings regressed")
135
+ old_checks = before["dynamic_evidence"]["checks"]
136
+ for key, row in after["dynamic_evidence"]["checks"].items():
137
+ if _RANK[row["status"]] > _RANK[old_checks[key]["status"]]:
138
+ reasons.append(f"{key}: aggregate result regressed")
139
+ if "visual_regression" in before:
140
+ reasons.extend(visual_regressions(before["visual_regression"], after["visual_regression"], directory))
141
+ return reasons
142
+
143
+
144
+ def _axe_findings(result: dict) -> Counter:
145
+ return Counter({(kind, row["id"]): row["node_count"]
146
+ for kind in ("violations", "incomplete") for row in result.get(kind, ())})
147
+
148
+
149
+ def repair_tokens(
150
+ root: Path, css: Path, directory: Path, contract: UIContract, baseline: dict,
151
+ *, apply: bool, verify: Callable[[Path], dict],
152
+ ) -> tuple[dict, dict | None]:
153
+ """Preview an exact token diff or write it and verify a fresh page, rolling back on regression."""
154
+ target = _target(root, css)
155
+ receipt_path = directory / "repair.json"
156
+ receipt = {"status": "BLOCKED", "target": str(target)}
157
+ if any(capture["status"] != "PASS" for capture in baseline["captures"]):
158
+ receipt["reason"] = "one or more baseline captures are unavailable"
159
+ atomic_write_json(receipt_path, receipt)
160
+ return receipt, None
161
+ if "visual_regression" in baseline and not visual_comparable(baseline["visual_regression"]):
162
+ receipt["reason"] = "visual reference coverage is incomplete"
163
+ atomic_write_json(receipt_path, receipt)
164
+ return receipt, None
165
+ with target.open("rb") as stream:
166
+ before = stream.read(256 * 1024 + 1)
167
+ if len(before) > 256 * 1024:
168
+ raise UIContractError("repair stylesheet exceeds 256 KiB")
169
+ after, names = _proposal(before, contract, baseline)
170
+ if not names:
171
+ receipt.update(status="NO_CHANGES", reason="no unambiguous declared token mismatch")
172
+ atomic_write_json(receipt_path, receipt)
173
+ return receipt, None
174
+ diff = "".join(
175
+ line if line.endswith("\n") else line + "\n\\n"
176
+ for line in difflib.unified_diff(before.decode().splitlines(keepends=True),
177
+ after.decode().splitlines(keepends=True),
178
+ fromfile=f"a/{target.relative_to(root)}",
179
+ tofile=f"b/{target.relative_to(root)}")
180
+ )
181
+ patch = directory / "repair.patch"
182
+ atomic_write_bytes(patch, diff.encode(), mode=0o600)
183
+ receipt.update(status="PREVIEW", tokens=names, patch=str(patch),
184
+ before_sha256=_fingerprint(before), proposed_sha256=_fingerprint(after))
185
+ atomic_write_json(receipt_path, receipt)
186
+ if not apply:
187
+ return receipt, None
188
+
189
+ lock = target.with_name(f".{target.name}.bugx-ui.lock")
190
+ try:
191
+ lock_fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
192
+ except FileExistsError:
193
+ receipt.update(status="BLOCKED", reason="another CSS repair owns the stylesheet lock")
194
+ atomic_write_json(receipt_path, receipt)
195
+ return receipt, None
196
+ os.close(lock_fd)
197
+ backup = directory / "repair-before.css"
198
+ written = False
199
+ verified = None
200
+ old_handler = None
201
+
202
+ def interrupt(_sig: int, _frame: object) -> None:
203
+ raise InterruptedError("repair interrupted")
204
+
205
+ try:
206
+ if _target(root, css).read_bytes() != before:
207
+ raise UIContractError("stylesheet changed after the repair preview")
208
+ mode = stat.S_IMODE(target.stat().st_mode)
209
+ atomic_write_bytes(backup, before, mode=0o600)
210
+ receipt.update(status="APPLYING", backup=str(backup))
211
+ atomic_write_json(receipt_path, receipt)
212
+ old_handler = signal.signal(signal.SIGTERM, interrupt)
213
+ written = True
214
+ atomic_write_bytes(target, after, mode=mode)
215
+ rerun = directory / "after"
216
+ rerun.mkdir(mode=0o700)
217
+ verified = verify(rerun)
218
+ write_ui_evidence(rerun, verified)
219
+ receipt["verification"] = str(rerun / "manifest.json")
220
+ reasons = _regressions(baseline, verified, names, directory)
221
+ if reasons:
222
+ raise UIContractError("; ".join(reasons))
223
+ if _target(root, css).read_bytes() != after:
224
+ raise UIContractError("stylesheet changed during verification")
225
+ receipt["status"] = "VERIFIED_APPLIED"
226
+ except BaseException as exc:
227
+ receipt["reason"] = str(exc) or type(exc).__name__
228
+ receipt["status"] = "BLOCKED"
229
+ if written:
230
+ try:
231
+ current = _target(root, css).read_bytes()
232
+ if current == after:
233
+ atomic_write_bytes(target, before, mode=mode)
234
+ elif current != before:
235
+ raise UIContractError("stylesheet contains other edits")
236
+ if _target(root, css).read_bytes() != before:
237
+ raise UIContractError("rollback byte verification failed")
238
+ receipt["status"] = "ROLLED_BACK"
239
+ except (OSError, UIContractError) as rollback:
240
+ receipt.update(status="RECOVERY_REQUIRED", rollback_error=str(rollback))
241
+ verified = None
242
+ if isinstance(exc, (KeyboardInterrupt, SystemExit)):
243
+ atomic_write_json(receipt_path, receipt)
244
+ raise
245
+ finally:
246
+ if old_handler is not None:
247
+ signal.signal(signal.SIGTERM, old_handler)
248
+ lock.unlink(missing_ok=True)
249
+ atomic_write_json(receipt_path, receipt)
250
+ return receipt, verified