@teevee98/synapse-hub 3.8.4 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/.agents/rules/author-integrity-guard.md +13 -10
  2. package/.agents/rules/skill-precedence.md +6 -4
  3. package/.agents/skills/agent-orchestration-multi-agent-optimize/SKILL.md +1 -1
  4. package/.agents/skills/agentless-qa-repair/SKILL.md +1 -1
  5. package/.agents/skills/auth-session-and-cookie-manager/SKILL.md +22 -2
  6. package/.agents/skills/qa-memory-os/SKILL.md +21 -4
  7. package/.agents/skills/security-dast-sentinel/SKILL.md +1 -1
  8. package/.agents/skills/token-and-context-optimizer/SKILL.md +1 -1
  9. package/.agents/skills/verification-before-completion/SKILL.md +1 -1
  10. package/AGENTS.md +3 -2
  11. package/CLAUDE.md +3 -3
  12. package/NOTICE +48 -0
  13. package/README.en.md +9 -9
  14. package/README.md +9 -9
  15. package/agentskills.json +1 -1
  16. package/bin/agent-qa.js +1 -1
  17. package/docs/ARCHITECTURE.en.md +7 -3
  18. package/docs/ARCHITECTURE.md +6 -2
  19. package/docs/CI_CD_INTEGRATION.en.md +6 -6
  20. package/docs/CI_CD_INTEGRATION.md +6 -6
  21. package/docs/CLI_REFERENCE.md +1 -1
  22. package/docs/PERFORMANCE_AUDIT_REPORT.md +1 -1
  23. package/docs/QUALITY_GATES.en.md +1 -1
  24. package/docs/QUALITY_GATES.md +1 -1
  25. package/docs/adopted-ecosystem-tools.md +37 -0
  26. package/docs/diagrams/clean_pom.svg +48 -0
  27. package/docs/diagrams/fsm_flow.svg +78 -0
  28. package/package.json +1 -1
  29. package/plugin.json +1 -1
  30. package/skills_manifest.json +103 -54
  31. package/synapse.config.json +1 -1
  32. package/templates/PROJECT_AI_GUIDE_TEMPLATE.md +3 -3
  33. package/templates/ai_bridges/CLAUDE.md +3 -3
  34. package/templates/ci/github-actions-synapse.yml +2 -2
  35. package/templates/ci/gitlab-ci-synapse.yml +1 -1
  36. package/templates/ui/index.html +2 -2
  37. package/templates/welcome.html.tmpl +26 -26
  38. package/tools/TOOLS_RUNBOOK.md +8 -8
  39. package/tools/__init__.py +1 -1
  40. package/tools/analyze_project.py +2 -2
  41. package/tools/browser_helpers.js +2 -2
  42. package/tools/build_consolidated_report.py +1640 -0
  43. package/tools/bump_version.py +5 -15
  44. package/tools/cli.py +3 -3
  45. package/tools/count_tokens.py +29 -5
  46. package/tools/dashboard_generator.py +10 -10
  47. package/tools/diagram_architect.py +220 -0
  48. package/tools/distill_log.py +33 -8
  49. package/tools/git_worktree_manager.py +185 -0
  50. package/tools/hub_publisher.py +38 -0
  51. package/tools/humanize_linter.py +4 -0
  52. package/tools/interview_story.py +25 -2
  53. package/tools/mcp_docx_server.py +1 -1
  54. package/tools/mcp_excel_server.py +1 -1
  55. package/tools/mcp_server.py +1 -1
  56. package/tools/mechanical_ui_gate.py +242 -0
  57. package/tools/pairwise_generator.py +175 -0
  58. package/tools/repo_map.py +308 -106
  59. package/tools/runaway_stopper.py +178 -0
  60. package/tools/setup_project.py +3 -3
  61. package/tools/sync_agent_rules.py +3 -3
  62. package/tools/ui_server.py +1 -1
  63. package/tools/update_sentinel.py +6 -6
  64. package/tools/verify_all.py +15 -0
  65. package/tools/welcome_page.py +2 -2
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ tools/git_worktree_manager.py — Ephemeral Git Worktree Manager for Subagents
5
+ Inspired by Jesse Vincent (obra/superpowers) and Shan Rais subagent isolation standard.
6
+ Allocates, inspects, and cleans up isolated worktrees so concurrent subagents
7
+ do not pollute or conflict with the main working directory.
8
+ 100% UTF-8 No BOM.
9
+ """
10
+
11
+ import sys
12
+ import os
13
+ import re
14
+ import subprocess
15
+ import argparse
16
+ import json
17
+ import time
18
+ from typing import Dict, List, Any, Optional
19
+
20
+ # Enforce UTF-8 stdout encoding
21
+ if hasattr(sys.stdout, "reconfigure"):
22
+ try:
23
+ sys.stdout.reconfigure(encoding="utf-8")
24
+ sys.stderr.reconfigure(encoding="utf-8")
25
+ except Exception:
26
+ pass
27
+
28
+ WORKTREES_ROOT = os.path.join(".synapse", "worktrees")
29
+
30
+ def run_git(args: List[str], cwd: Optional[str] = None) -> subprocess.CompletedProcess:
31
+ return subprocess.run(
32
+ ["git"] + args,
33
+ cwd=cwd or os.getcwd(),
34
+ capture_output=True,
35
+ text=True,
36
+ encoding="utf-8",
37
+ errors="replace"
38
+ )
39
+
40
+ class WorktreeManager:
41
+ def __init__(self, base_dir: Optional[str] = None):
42
+ self.base_dir = base_dir or os.path.join(os.getcwd(), WORKTREES_ROOT)
43
+
44
+ def list_worktrees(self) -> List[Dict[str, str]]:
45
+ res = run_git(["worktree", "list", "--porcelain"])
46
+ if res.returncode != 0:
47
+ return []
48
+
49
+ worktrees = []
50
+ current: Dict[str, str] = {}
51
+ for line in res.stdout.splitlines():
52
+ line = line.strip()
53
+ if not line:
54
+ if current:
55
+ worktrees.append(current)
56
+ current = {}
57
+ elif line.startswith("worktree "):
58
+ current["path"] = line[len("worktree "):].strip()
59
+ elif line.startswith("branch "):
60
+ current["branch"] = line[len("branch "):].strip()
61
+ elif line.startswith("HEAD "):
62
+ current["head"] = line[len("HEAD "):].strip()
63
+ if current:
64
+ worktrees.append(current)
65
+ return worktrees
66
+
67
+ def create_worktree(self, agent_id: str, branch_name: Optional[str] = None) -> Dict[str, Any]:
68
+ os.makedirs(self.base_dir, exist_ok=True)
69
+ timestamp = int(time.time())
70
+ clean_agent_id = re.sub(r'[^a-zA-Z0-9_.-]', '-', agent_id)
71
+ branch = branch_name or f"subagent/{clean_agent_id}-{timestamp}"
72
+ target_path = os.path.abspath(os.path.join(self.base_dir, f"{clean_agent_id}-{timestamp}"))
73
+
74
+ res = run_git(["worktree", "add", "-b", branch, target_path, "HEAD"])
75
+ if res.returncode != 0:
76
+ # Fallback if branch already exists
77
+ res = run_git(["worktree", "add", target_path, "HEAD"])
78
+ if res.returncode != 0:
79
+ return {
80
+ "success": False,
81
+ "error": res.stderr.strip() or "Failed to create worktree",
82
+ "path": target_path
83
+ }
84
+
85
+ return {
86
+ "success": True,
87
+ "agent_id": agent_id,
88
+ "worktree_path": target_path,
89
+ "branch": branch,
90
+ "created_at": timestamp
91
+ }
92
+
93
+ def remove_worktree(self, worktree_path: str, delete_branch: bool = True) -> Dict[str, Any]:
94
+ # Determine branch before removal
95
+ branch_to_delete = None
96
+ if delete_branch:
97
+ for wt in self.list_worktrees():
98
+ if os.path.abspath(wt.get("path", "")) == os.path.abspath(worktree_path):
99
+ branch_ref = wt.get("branch", "")
100
+ if branch_ref.startswith("refs/heads/"):
101
+ branch_to_delete = branch_ref[len("refs/heads/"):]
102
+ elif branch_ref:
103
+ branch_to_delete = branch_ref
104
+ break
105
+
106
+ res = run_git(["worktree", "remove", "--force", worktree_path])
107
+ success = res.returncode == 0
108
+
109
+ # Run git worktree prune
110
+ run_git(["worktree", "prune"])
111
+
112
+ # Clean up ephemeral subagent branch if requested
113
+ if success and delete_branch and branch_to_delete and branch_to_delete.startswith("subagent/"):
114
+ run_git(["branch", "-D", branch_to_delete])
115
+
116
+ return {
117
+ "success": success,
118
+ "path": worktree_path,
119
+ "deleted_branch": branch_to_delete if (success and delete_branch) else None,
120
+ "error": res.stderr.strip() if not success else None
121
+ }
122
+
123
+ def prune_stale(self) -> Dict[str, Any]:
124
+ res = run_git(["worktree", "prune", "-v"])
125
+ return {
126
+ "success": res.returncode == 0,
127
+ "output": res.stdout.strip()
128
+ }
129
+
130
+ def main():
131
+ parser = argparse.ArgumentParser(description="Manage ephemeral git worktrees for subagent isolation.")
132
+ parser.add_argument("action", choices=["list", "create", "remove", "prune"], help="Action to execute.")
133
+ parser.add_argument("--agent-id", help="Subagent identifier for creation.")
134
+ parser.add_argument("--path", help="Worktree path for removal.")
135
+ parser.add_argument("--json", action="store_true", help="Output JSON format.")
136
+ args = parser.parse_args()
137
+
138
+ manager = WorktreeManager()
139
+
140
+ if args.action == "list":
141
+ items = manager.list_worktrees()
142
+ if args.json:
143
+ print(json.dumps(items, indent=2))
144
+ else:
145
+ print(f"[WORKTREE MANAGER] Active Worktrees ({len(items)}):")
146
+ for it in items:
147
+ print(f" - {it.get('path')} ({it.get('branch', 'detached')})")
148
+
149
+ elif args.action == "create":
150
+ if not args.agent_id:
151
+ print("Error: --agent-id is required for create.", file=sys.stderr)
152
+ sys.exit(1)
153
+ res = manager.create_worktree(args.agent_id)
154
+ if args.json:
155
+ print(json.dumps(res, indent=2))
156
+ else:
157
+ if res["success"]:
158
+ print(f"[WORKTREE CREATED] Path: {res['worktree_path']} (Branch: {res['branch']})")
159
+ else:
160
+ print(f"[ERROR] Failed to create worktree: {res.get('error')}", file=sys.stderr)
161
+ sys.exit(1)
162
+
163
+ elif args.action == "remove":
164
+ if not args.path:
165
+ print("Error: --path is required for remove.", file=sys.stderr)
166
+ sys.exit(1)
167
+ res = manager.remove_worktree(args.path)
168
+ if args.json:
169
+ print(json.dumps(res, indent=2))
170
+ else:
171
+ if res["success"]:
172
+ print(f"[WORKTREE REMOVED] {res['path']} - Deleted branch: {res.get('deleted_branch')}")
173
+ else:
174
+ print(f"[ERROR] Failed to remove worktree: {res.get('error')}", file=sys.stderr)
175
+ sys.exit(1)
176
+
177
+ elif args.action == "prune":
178
+ res = manager.prune_stale()
179
+ if args.json:
180
+ print(json.dumps(res, indent=2))
181
+ else:
182
+ print(f"[WORKTREE PRUNED] Output: {res['output'] or 'Zero stale worktrees.'}")
183
+
184
+ if __name__ == "__main__":
185
+ main()
@@ -484,6 +484,39 @@ def step_4_and_5_monitor_packages_and_npm(owner: str, repo: str, version: str, t
484
484
  return True
485
485
 
486
486
 
487
+ def confirm_release(version: str, owner: str, repo: str, yes: bool = False, dry_run: bool = False) -> bool:
488
+ """
489
+ Prompts for user confirmation before pushing to remote, tagging, or publishing to NPM.
490
+ In interactive sessions, requires explicit 'y' or 'yes' confirmation.
491
+ In non-interactive environments, requires the --yes / --force flag.
492
+ """
493
+ if dry_run or yes:
494
+ return True
495
+
496
+ is_interactive = (
497
+ hasattr(sys.stdin, "isatty")
498
+ and sys.stdin.isatty()
499
+ and not os.environ.get("CI")
500
+ and not os.environ.get("SYNAPSE_NON_INTERACTIVE")
501
+ )
502
+
503
+ if is_interactive:
504
+ try:
505
+ prompt = f"\n⚠️ Are you sure you want to release v{version} to {owner}/{repo} and publish to NPM? [y/N]: "
506
+ choice = input(prompt).strip().lower()
507
+ if choice in ("y", "yes"):
508
+ return True
509
+ print("Release aborted by user.")
510
+ return False
511
+ except (KeyboardInterrupt, EOFError):
512
+ print("\nRelease aborted.")
513
+ return False
514
+
515
+ # In non-interactive environments, require explicit confirmation flag
516
+ log_error("Non-interactive release requires explicit approval flag: --yes (or -y / --force).")
517
+ return False
518
+
519
+
487
520
  def main() -> int:
488
521
  parser = argparse.ArgumentParser(
489
522
  description="Autonomous 1-Click Release & Publishing Pipeline for Synapse Hub"
@@ -496,6 +529,7 @@ def main() -> int:
496
529
  parser.add_argument("--auto-rollback", action="store_true", help="Automatically rollback remote tag and GitHub Release if NPM publication verification fails")
497
530
  parser.add_argument("--rollback", action="store_true", help="Immediately rollback remote tag and GitHub Release for the current version")
498
531
  parser.add_argument("--timeout", type=int, default=180, help="Maximum seconds to wait for npm publication (default 180s)")
532
+ parser.add_argument("--yes", "-y", "--force", dest="yes", action="store_true", help="Confirm release without interactive prompt (required for non-interactive execution)")
499
533
  args = parser.parse_args()
500
534
 
501
535
  print("=" * 68)
@@ -522,6 +556,10 @@ def main() -> int:
522
556
  log_error("Pre-flight verification failed. Pipeline aborted to protect release integrity.")
523
557
  return 1
524
558
 
559
+ # Confirm release before external actions (pushing, tagging, publishing)
560
+ if not confirm_release(version, owner, repo, yes=args.yes, dry_run=args.dry_run):
561
+ return 1
562
+
525
563
  # Stage & Commit
526
564
  if not stage_and_commit_changes(message=args.message, dry_run=args.dry_run):
527
565
  log_error("Failed to prepare clean Git working state.")
@@ -176,6 +176,10 @@ CLICHE_PHRASES: List[Tuple[str, str]] = [
176
176
  (r"\breflects a broader trend\b", "say 'shows a trend'"),
177
177
  (r"\bmarks a significant shift\b", "say 'marks a shift'"),
178
178
  (r"\bin today's ever-evolving landscape\b", "say 'today'"),
179
+ (r"\brest assured\b", "state verifiable evidence instead"),
180
+ (r"\bwithout further ado\b", "dive directly into technical content"),
181
+ (r"\bi hope this helps\b", "omit conversational fluff"),
182
+ (r"\bhere is the updated code\b", "deliver code directly"),
179
183
  ]
180
184
 
181
185
  # Words that are fine in isolation, but suspicious when piled up (>= 3 times)
@@ -37,10 +37,11 @@ class PocockGriller:
37
37
  def __init__(self, target_framework: str = "Playwright_TS"):
38
38
  self.target_framework = target_framework
39
39
 
40
- def generate_frontier_questions(self, story_text: str) -> List[Dict[str, Any]]:
40
+ def generate_frontier_questions(self, story_text: str, grill_me: bool = False) -> List[Dict[str, Any]]:
41
41
  """
42
42
  Analyzes requirements text and returns batched questions for ask_question.
43
43
  Only generates questions for true decision forks, never for discoverable codebase facts.
44
+ In grill_me mode (Matt Pocock pattern), aggressively probes boundary, race, and failure forks.
44
45
  """
45
46
  questions = []
46
47
 
@@ -79,19 +80,41 @@ class PocockGriller:
79
80
  ]
80
81
  })
81
82
 
83
+ # 4. Matt Pocock Grilling Mode (Aggressive Boundary & Race Probing)
84
+ if grill_me:
85
+ questions.append({
86
+ "question": "Xung đột đồng thời & Thao tác kép (Pocock Concurrency Frontier): Xử lý ra sao khi xảy ra Double-Submit hoặc 2 user cùng sửa 1 bản ghi?",
87
+ "is_multi_select": False,
88
+ "options": [
89
+ "(Recommended) Idempotency Token / Khóa nút thao tác và trả về thông báo lỗi lạc quan (Optimistic Lock 409)",
90
+ "Cho phép ghi đè tự do theo thứ tự thời gian (Last Write Wins)",
91
+ "Xếp hàng đợi tuần tự (Queue sequential execution)"
92
+ ]
93
+ })
94
+ questions.append({
95
+ "question": "Dữ liệu dị dạng & Biên tải (Pocock Fuzzing Frontier): Hành vi mong đợi khi nhận payload rỗng, quá giới hạn byte, hoặc chứa ký tự đặc biệt?",
96
+ "is_multi_select": False,
97
+ "options": [
98
+ "(Recommended) Chặn tại Client Validation kèm Schema Rejection 400 Bad Request",
99
+ "Cắt ngắn dữ liệu tự động (Silent Truncation) và lưu phần hợp lệ",
100
+ "Cho phép lưu nguyên vẹn vào DB mà không áp dụng bộ lọc ký tự"
101
+ ]
102
+ })
103
+
82
104
  return questions
83
105
 
84
106
 
85
107
  def main():
86
108
  parser = argparse.ArgumentParser(description="Pocock Grilling Primitive Engine")
87
109
  parser.add_argument("story", nargs="?", default="", help="User story or requirement text")
110
+ parser.add_argument("--grill-me", action="store_true", help="Explicit grill-me mode (Matt Pocock pattern)")
88
111
  parser.add_argument("--json", action="store_true", help="Output questions in JSON format")
89
112
  args = parser.parse_args()
90
113
 
91
114
  story_text = args.story or "User Story: As a registered user, I want to approve invoices with attached receipts."
92
115
 
93
116
  griller = PocockGriller()
94
- questions = griller.generate_frontier_questions(story_text)
117
+ questions = griller.generate_frontier_questions(story_text, grill_me=args.grill_me)
95
118
 
96
119
  if args.json:
97
120
  print(json.dumps({"story": story_text, "questions": questions}, indent=2))
@@ -60,7 +60,7 @@ if hasattr(sys.stdout, 'reconfigure'):
60
60
  except Exception:
61
61
  pass
62
62
 
63
- SERVER_VERSION = "3.8.4"
63
+ SERVER_VERSION = "3.9.0"
64
64
  MAX_DOCX_SIZE = 50 * 1024 * 1024 # 50 MB
65
65
  MAX_UNCOMPRESSED_SIZE = 200 * 1024 * 1024 # 200 MB
66
66
  MAX_RATIO = 100 # 100:1 compression ratio limit
@@ -52,7 +52,7 @@ if hasattr(sys.stdout, 'reconfigure'):
52
52
  except Exception:
53
53
  pass
54
54
 
55
- SERVER_VERSION = "3.8.4"
55
+ SERVER_VERSION = "3.9.0"
56
56
  MAX_XLSX_SIZE = 50 * 1024 * 1024 # 50 MB
57
57
  MAX_UNCOMPRESSED_SIZE = 200 * 1024 * 1024 # 200 MB
58
58
  MAX_RATIO = 100 # 100:1 compression ratio limit
@@ -46,7 +46,7 @@ import gherkin_suite
46
46
  import api_fuzzer
47
47
 
48
48
  SERVER_NAME = "enterprise-agent-qa"
49
- SERVER_VERSION = "3.8.4"
49
+ SERVER_VERSION = "3.9.0"
50
50
 
51
51
  MCP_TOOLS = [
52
52
  {
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ tools/mechanical_ui_gate.py — Headless Chrome Mechanical Layout & Contrast Gate
5
+ Inspired by Leonxlnx's taste-skill (gate.mjs & consistency.mjs).
6
+ Enforces mechanical finish criteria on rendered HTML and UI components:
7
+ zero horizontal overflow spills, WCAG AA contrast (>= 4.5:1), valid interactive
8
+ tap targets, and zero empty/unstyled placeholder divs.
9
+ 100% UTF-8 No BOM.
10
+ """
11
+
12
+ import sys
13
+ import os
14
+ import re
15
+ import json
16
+ import argparse
17
+ from typing import Dict, List, Any, Optional, Tuple
18
+
19
+ # Enforce UTF-8 stdout encoding
20
+ if hasattr(sys.stdout, "reconfigure"):
21
+ try:
22
+ sys.stdout.reconfigure(encoding="utf-8")
23
+ sys.stderr.reconfigure(encoding="utf-8")
24
+ except Exception:
25
+ pass
26
+
27
+ def parse_css_color(color_str: str) -> Optional[Tuple[int, int, int]]:
28
+ c = color_str.strip().lower()
29
+ named = {
30
+ "white": (255, 255, 255),
31
+ "black": (0, 0, 0),
32
+ "red": (255, 0, 0),
33
+ "green": (0, 128, 0),
34
+ "blue": (0, 0, 255),
35
+ "yellow": (255, 255, 0),
36
+ "cyan": (0, 255, 255),
37
+ "magenta": (255, 0, 255),
38
+ "gray": (128, 128, 128),
39
+ "grey": (128, 128, 128),
40
+ }
41
+ if c in named:
42
+ return named[c]
43
+ if c.startswith("#"):
44
+ h = c[1:]
45
+ if len(h) == 3:
46
+ return (int(h[0]*2, 16), int(h[1]*2, 16), int(h[2]*2, 16))
47
+ elif len(h) == 6:
48
+ return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
49
+ m = re.match(r'rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)', c)
50
+ if m:
51
+ return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
52
+ return None
53
+
54
+ def calc_relative_luminance(rgb: Tuple[int, int, int]) -> float:
55
+ def ch(val: int) -> float:
56
+ v = val / 255.0
57
+ return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
58
+ return 0.2126 * ch(rgb[0]) + 0.7152 * ch(rgb[1]) + 0.0722 * ch(rgb[2])
59
+
60
+ def calc_contrast_ratio(rgb1: Tuple[int, int, int], rgb2: Tuple[int, int, int]) -> float:
61
+ l1 = calc_relative_luminance(rgb1)
62
+ l2 = calc_relative_luminance(rgb2)
63
+ return (max(l1, l2) + 0.05) / (min(l1, l2) + 0.05)
64
+
65
+ class MechanicalUIGate:
66
+ def __init__(self, min_contrast: float = 4.5):
67
+ self.min_contrast = min_contrast
68
+
69
+ def audit_html_content(self, html_text: str, filename: str = "inline.html") -> Dict[str, Any]:
70
+ """Performs static DOM and structural mechanical checks on HTML content."""
71
+ findings = []
72
+
73
+ # 1. Check for empty interactive elements (buttons, links without accessible text or aria-label)
74
+ empty_button_re = re.compile(r'<button\b(?![^>]*\baria-label=)[^>]*>\s*</button>', re.IGNORECASE)
75
+ for m in empty_button_re.finditer(html_text):
76
+ findings.append({
77
+ "id": "empty-button",
78
+ "severity": "FAIL",
79
+ "message": "Found button element with zero inner text and no aria-label.",
80
+ "snippet": m.group(0)[:80]
81
+ })
82
+
83
+ empty_link_re = re.compile(r'<a\b(?![^>]*\baria-label=)[^>]*>\s*</a>', re.IGNORECASE)
84
+ for m in empty_link_re.finditer(html_text):
85
+ findings.append({
86
+ "id": "empty-anchor",
87
+ "severity": "FAIL",
88
+ "message": "Found <a> link element with zero inner text and no aria-label.",
89
+ "snippet": m.group(0)[:80]
90
+ })
91
+
92
+ # 2. Check for missing viewport meta tag (causes layout overflow on mobile)
93
+ if "<meta" in html_text.lower() and "viewport" not in html_text.lower():
94
+ findings.append({
95
+ "id": "missing-viewport",
96
+ "severity": "FAIL",
97
+ "message": "Missing <meta name='viewport'> tag, resulting in mobile rendering breakage.",
98
+ "snippet": "<meta ...>"
99
+ })
100
+
101
+ # 3. Check for inline fixed-width overflows (e.g. style='width: 1400px' or style='min-width: 1200px' without max-width)
102
+ fixed_overflow_re = re.compile(r'style=[\'"][^\'"]*?(?:min-)?width:\s*(\d{4,})px', re.IGNORECASE)
103
+ for m in fixed_overflow_re.finditer(html_text):
104
+ px_val = int(m.group(1))
105
+ if px_val > 1000 and "max-width" not in m.group(0):
106
+ findings.append({
107
+ "id": "overflow-fixed-width",
108
+ "severity": "WARN",
109
+ "message": f"Fixed width {px_val}px without max-width: 100% may cause viewport horizontal scroll.",
110
+ "snippet": m.group(0)[:80]
111
+ })
112
+
113
+ # 4. Check for unhandled AI slop tags / comments
114
+ ai_comment_re = re.compile(r'<!--\s*(?:AI-generated|TODO: add content|Placeholder|Generated by)\b[^-]*?-->', re.IGNORECASE)
115
+ for m in ai_comment_re.finditer(html_text):
116
+ findings.append({
117
+ "id": "ai-placeholder-comment",
118
+ "severity": "FAIL",
119
+ "message": "Found unresolved AI placeholder comment.",
120
+ "snippet": m.group(0)[:80]
121
+ })
122
+
123
+ # 5. Check for heading hierarchy skip (e.g. h1 directly followed by h4 without h2 or h3)
124
+ headings = re.findall(r'<h([1-6])\b', html_text, re.IGNORECASE)
125
+ levels = [int(h) for h in headings]
126
+ for i in range(len(levels) - 1):
127
+ if levels[i+1] > levels[i] + 1:
128
+ findings.append({
129
+ "id": "heading-order-skipped",
130
+ "severity": "WARN",
131
+ "message": f"Skipped heading level: h{levels[i]} followed directly by h{levels[i+1]}.",
132
+ "snippet": f"h{levels[i]} -> h{levels[i+1]}"
133
+ })
134
+
135
+ # 6. Check for low contrast inline styles (WCAG AA min_contrast, default 4.5:1)
136
+ style_matches = re.finditer(r'style=[\'"]([^\'"]+)[\'"]', html_text, re.IGNORECASE)
137
+ for sm in style_matches:
138
+ s_text = sm.group(1)
139
+ fg_m = re.search(r'(?:^|;)\s*color:\s*([^;]+)', s_text, re.IGNORECASE)
140
+ bg_m = re.search(r'(?:^|;)\s*background(?:-color)?:\s*([^;]+)', s_text, re.IGNORECASE)
141
+ if fg_m and bg_m:
142
+ fg_col = parse_css_color(fg_m.group(1))
143
+ bg_col = parse_css_color(bg_m.group(1))
144
+ if fg_col and bg_col:
145
+ ratio = calc_contrast_ratio(fg_col, bg_col)
146
+ if ratio < self.min_contrast:
147
+ findings.append({
148
+ "id": "low-contrast-text",
149
+ "severity": "FAIL",
150
+ "message": f"Color contrast ratio {ratio:.2f}:1 fails WCAG AA minimum ({self.min_contrast}:1).",
151
+ "snippet": sm.group(0)[:80]
152
+ })
153
+
154
+ fails = [f for f in findings if f["severity"] == "FAIL"]
155
+ warns = [f for f in findings if f["severity"] == "WARN"]
156
+
157
+ return {
158
+ "file": filename,
159
+ "passed": len(fails) == 0,
160
+ "fail_count": len(fails),
161
+ "warn_count": len(warns),
162
+ "findings": findings
163
+ }
164
+
165
+ def audit_file(self, file_path: str) -> Dict[str, Any]:
166
+ if not os.path.exists(file_path):
167
+ return {
168
+ "file": file_path,
169
+ "passed": False,
170
+ "error": f"File not found: {file_path}",
171
+ "findings": []
172
+ }
173
+ try:
174
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
175
+ content = f.read()
176
+ return self.audit_html_content(content, filename=file_path)
177
+ except Exception as e:
178
+ return {
179
+ "file": file_path,
180
+ "passed": False,
181
+ "error": str(e),
182
+ "findings": []
183
+ }
184
+
185
+ def main():
186
+ parser = argparse.ArgumentParser(description="Mechanical layout and UI quality gate checker.")
187
+ parser.add_argument("paths", nargs="*", help="HTML files or directories to audit.")
188
+ parser.add_argument("--json", action="store_true", help="Output JSON format.")
189
+ args = parser.parse_args()
190
+
191
+ gate = MechanicalUIGate()
192
+ target_files = []
193
+
194
+ if not args.paths:
195
+ # Default scan in reports/ or templates/
196
+ for root in ["reports", "templates"]:
197
+ if os.path.exists(root):
198
+ for dirpath, _, files in os.walk(root):
199
+ for f in files:
200
+ if f.endswith(".html"):
201
+ target_files.append(os.path.join(dirpath, f))
202
+ else:
203
+ for p in args.paths:
204
+ if os.path.isdir(p):
205
+ for dirpath, _, files in os.walk(p):
206
+ for f in files:
207
+ if f.endswith(".html"):
208
+ target_files.append(os.path.join(dirpath, f))
209
+ elif os.path.isfile(p):
210
+ target_files.append(p)
211
+
212
+ if not target_files:
213
+ print("[MECHANICAL UI GATE] No HTML files provided or found. Exiting clean.", file=sys.stderr)
214
+ sys.exit(0)
215
+
216
+ results = [gate.audit_file(f) for f in target_files]
217
+ total_fails = sum(r.get("fail_count", 0) for r in results)
218
+ total_warns = sum(r.get("warn_count", 0) for r in results)
219
+ all_passed = total_fails == 0
220
+
221
+ if args.json:
222
+ print(json.dumps({
223
+ "overall_passed": all_passed,
224
+ "total_files": len(results),
225
+ "total_fails": total_fails,
226
+ "total_warns": total_warns,
227
+ "results": results
228
+ }, indent=2))
229
+ else:
230
+ status_sym = "✅ PASS" if all_passed else "❌ FAIL"
231
+ print(f"[MECHANICAL UI GATE] {status_sym} — Checked {len(results)} files | Fails: {total_fails} | Warnings: {total_warns}")
232
+ for r in results:
233
+ if not r["passed"] or r.get("warn_count", 0) > 0:
234
+ print(f" File: {r['file']}")
235
+ for f in r.get("findings", []):
236
+ print(f" - [{f['severity']}] {f['id']}: {f['message']}")
237
+
238
+ if not all_passed:
239
+ sys.exit(1)
240
+
241
+ if __name__ == "__main__":
242
+ main()