-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathvalidate_ui_refs.py
More file actions
2147 lines (1895 loc) · 84.1 KB
/
Copy pathvalidate_ui_refs.py
File metadata and controls
2147 lines (1895 loc) · 84.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Validate UI paths and Command Palette names in Warp Astro Starlight documentation.
Scans markdown files for references to Warp UI paths (Settings > ..., File > ..., etc.)
and Command Palette command names, then validates them against a snapshot of known-valid
paths extracted from the public warp client repo (warpdotdev/warp).
Usage:
python3 validate_ui_refs.py --all
python3 validate_ui_refs.py --check-paths
python3 validate_ui_refs.py --check-commands
python3 validate_ui_refs.py --all --fix --create-pr --slack-notify
python3 validate_ui_refs.py --refresh-valid-paths --warp /path/to/warp
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
from datetime import datetime, timezone
from difflib import SequenceMatcher
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_VALID_PATHS_FILE = SCRIPT_DIR / "valid_paths.json"
DEFAULT_DOCS_DIR = SCRIPT_DIR.parents[2] / "src" / "content" / "docs"
DEFAULT_SLACK_CHANNEL = "C09BVK0PL3Y" # #growth-docs
# Sibling directory names tried when auto-detecting the warp client checkout.
# Prefer the public warpdotdev/warp repo; `warp-internal` is a legacy fallback.
WARP_REPO_SIBLING_NAMES = ("warp", "warp-internal")
# Known Warp UI roots — paths starting with these are Warp UI paths
WARP_UI_ROOTS = {"Settings", "File", "View", "Warp", "Warp Drive", "Personal"}
# Roots that belong to external products (not Warp)
EXTERNAL_ROOTS = {
"Mac", "System", "System Preferences", "Windows", "Linux",
"Chrome", "Firefox", "Safari", "VS Code", "Visual Studio",
}
# Context keywords that indicate a non-Warp UI path even if root matches
EXTERNAL_CONTEXT_KEYWORDS = {
"github", "gitlab", "bitbucket", "organization", "org settings",
"slack", "linear", "notion", "jira", "figma",
"raycast", "vs code", "vscode", "visual studio",
}
# Known external/OS Settings paths that look like Warp paths but aren't.
# These are matched as prefixes of the normalized path.
EXTERNAL_SETTINGS_PATHS = {
"Settings > Privacy & Security",
"Settings > Secrets and variables",
"Settings > Extensions",
"Settings > Notifications",
"Settings > System",
"Settings > People",
"Settings > General",
}
# Minimum fuzzy match score to suggest an alternative
FUZZY_MATCH_THRESHOLD = 0.6
# Minimum fuzzy match score for auto-fix
AUTO_FIX_THRESHOLD = 0.9
# ---------------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------------
def load_valid_paths(path: Path) -> Dict[str, Any]:
"""Load the valid_paths.json snapshot."""
with open(path, "r") as f:
return json.load(f)
# ---------------------------------------------------------------------------
# Extraction: UI paths from docs
# ---------------------------------------------------------------------------
# Regex patterns for UI paths in various markdown formats
# Backtick: `Settings > AI > Active AI`
RE_BACKTICK_PATH = re.compile(
r"`((?:" + "|".join(re.escape(r) for r in WARP_UI_ROOTS) + r")\s*>\s*[^`]+)`"
)
# Bold: **Settings > AI > Active AI**
RE_BOLD_PATH = re.compile(
r"\*\*((?:" + "|".join(re.escape(r) for r in WARP_UI_ROOTS) + r")\s*>\s*[^*]+)\*\*"
)
# Italic: _Settings > AI > Active AI_ or *Settings > AI*
RE_ITALIC_PATH = re.compile(
r"(?:_|\*)((?:" + "|".join(re.escape(r) for r in WARP_UI_ROOTS) + r")\s*>\s*[^_*]+)(?:_|\*)"
)
# Bare (no formatting): Settings > AI > Active AI (at start of line or after common punctuation)
RE_BARE_PATH = re.compile(
r"(?:^|[(\s])((?:" + "|".join(re.escape(r) for r in WARP_UI_ROOTS) + r")\s*>\s*\S[^.)\n\[,]*)",
re.MULTILINE,
)
# Per-segment backtick: `Settings` > `AI` > `Active AI`
RE_SEG_BACKTICK_PATH = re.compile(
r"(`(?:" + "|".join(re.escape(r) for r in WARP_UI_ROOTS) + r")`\s*>\s*`[^`]+`(?:\s*>\s*`[^`]+`)*)"
)
# Canonical format: **Settings** > **AI** > **Active AI**
RE_CANONICAL_PATH = re.compile(
r"(\*\*(?:" + "|".join(re.escape(r) for r in WARP_UI_ROOTS) + r")\*\*\s*>\s*\*\*[^*]+\*\*(?:\s*>\s*\*\*[^*]+\*\*)*)"
)
def _normalize_path(raw: str) -> str:
"""Normalize whitespace around > separators and strip artifacts."""
path = " > ".join(seg.strip() for seg in raw.split(">"))
# Strip trailing punctuation that gets captured by bare-path regex
path = path.rstrip(".,;:!?")
# Strip formatting wrappers from individual segments
segments = path.split(" > ")
segments = [s.strip("`").strip("*") for s in segments]
return " > ".join(segments)
def _to_canonical_format(normalized: str) -> str:
"""Convert a normalized path to canonical bold format: **Seg** > **Seg**."""
segments = normalized.split(" > ")
return " > ".join(f"**{seg}**" for seg in segments)
# Warp Settings sections that unambiguously identify a path as Warp's UI
# (not an external product's settings), even when the surrounding line mentions
# external products like GitHub / Slack / Linear. Matched against segments[1]
# after stripping formatting.
_WARP_SETTINGS_ROOT_SECTIONS = {
"About", "Account", "Agents", "Billing and usage", "Code",
"Cloud platform", "Teams", "Appearance", "Features",
"Keyboard shortcuts", "Warpify", "Referrals", "Shared blocks",
"Warp Drive", "Privacy",
# Deprecated-but-unambiguously-Warp top-level labels the validator still
# recognizes in order to auto-migrate them:
"AI", "MCP Servers", "Environments", "Platform", "Keybindings",
}
def _is_external_path(path: str, line: str) -> bool:
"""Check if a path belongs to an external product, not Warp."""
segments = [s.strip() for s in path.split(">")]
root = segments[0]
if root in EXTERNAL_ROOTS:
return True
# Check against known external Settings paths
for ext_path in EXTERNAL_SETTINGS_PATHS:
if path.startswith(ext_path):
return True
# If the Settings path's second segment is a recognized Warp section/umbrella
# (or a known deprecated one), the external-product-mention bail-out below
# should not fire — the path is unambiguously Warp's UI. This keeps sentences
# like "Navigate to **Settings** > **MCP Servers** to get started. Some
# integrations (like Linear, GitHub, and Sentry) are available..." from being
# silently skipped.
if (
root == "Settings"
and len(segments) >= 2
and segments[1] in _WARP_SETTINGS_ROOT_SECTIONS
):
return False
# Check surrounding line for external product keywords
line_lower = line.lower()
for kw in EXTERNAL_CONTEXT_KEYWORDS:
if kw in line_lower:
return True
return False
def extract_ui_paths(file_path: Path) -> List[Dict[str, Any]]:
"""Extract all Warp UI path references from a markdown file."""
results = []
try:
text = file_path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
return results
for line_num, line in enumerate(text.splitlines(), start=1):
for pattern, fmt in [
(RE_CANONICAL_PATH, "canonical"),
(RE_SEG_BACKTICK_PATH, "seg_backtick"),
(RE_BACKTICK_PATH, "backtick"),
(RE_BOLD_PATH, "bold"),
(RE_ITALIC_PATH, "italic"),
(RE_BARE_PATH, "bare"),
]:
for match in pattern.finditer(line):
raw = match.group(1).strip()
normalized = _normalize_path(raw)
if _is_external_path(normalized, line):
continue
# Skip bare paths that look like they captured a full sentence
# (e.g. "Settings > Features so that the completions menu opens")
if fmt == "bare":
segments = normalized.split(" > ")
if len(segments) >= 2 and len(segments[1].split()) > 5:
continue
# Skip if this span was already matched by an earlier pattern
match_span = (line_num, match.start(), match.end())
if any(
r["_span"] == match_span or
(r["line"] == line_num and r["normalized"] == normalized)
for r in results
):
continue
results.append({
"file": str(file_path),
"line": line_num,
"raw": raw,
"normalized": normalized,
"format": fmt,
# For bare paths, group(0) includes the leading space/bracket
# from `(?:^|[(\s])`, which would be consumed by string
# replacement and produce `under**Settings**` instead of
# `under **Settings**`. Use the stripped group(1) (= raw)
# so replacements only cover the path text itself.
"match_text": raw if fmt == "bare" else match.group(0),
"line_text": line,
"_span": match_span,
})
return results
# ---------------------------------------------------------------------------
# Extraction: Command Palette names from docs
# ---------------------------------------------------------------------------
# Patterns for Command Palette references:
# - "Open Theme Picker" near "Command Palette"
# - Command Palette > Open Theme Picker
RE_CMD_PALETTE_QUOTED = re.compile(
r'["\u201c]([^"\u201d\n]{4,})["\u201d]'
)
RE_CMD_PALETTE_ARROW = re.compile(
r"Command Palette\s*>\s*[`\"]*([^`\"\n>]+)[`\"]*"
)
# Common words that appear quoted near Command Palette but aren't commands
_CMD_PALETTE_STOPWORDS = {
"macos", "windows", "linux", "mac", "appearance", "export", "share",
"prompt", "a11y", "settings", "preferences",
}
# UI action keywords that precede toggle/button labels, not CP commands.
# If a quoted string is preceded by one of these on the same line, skip it.
_RE_UI_LABEL_PREFIX = re.compile(
r'\b(toggle|click|clicking|enable|disable|select|check|uncheck)\b',
re.IGNORECASE,
)
def _is_plausible_command_name(name: str) -> bool:
"""Filter false positives for command palette names."""
name = name.strip()
# Too short
if len(name) < 4:
return False
# Too long — likely a sentence or alt text, not a command name
if len(name) > 80:
return False
# Pure numbers or special chars
if re.match(r"^[\d\s.,:;!?]+$", name):
return False
# Trailing colon (likely a label, not a command)
if name.endswith(":"):
return False
# Single word (unlikely to be a command name, which are usually multi-word)
if re.match(r"^[A-Za-z]+$", name) and name.lower() in _CMD_PALETTE_STOPWORDS:
return False
# Single lowercase word
if re.match(r"^[a-z]+$", name):
return False
# URLs
if name.startswith("http") or name.startswith("www."):
return False
# File paths or anchors
if "/" in name or "\\" in name or name.startswith("#"):
return False
# Kebab-case strings (URL fragments like "using-forked-conversations")
if re.match(r"^[a-z][a-z0-9-]+$", name):
return False
# HTML/markdown artifacts
if name.startswith("width=") or name.startswith("height="):
return False
if "**" in name or "__" in name:
return False
# Image alt text patterns (long descriptive phrases)
description_indicators = [
"showing", "displayed", "with the", "interface", "screenshot",
"circled", "button", "view of", "image of",
" ago", # status text like "Completed 10 minutes ago"
]
name_lower = name.lower()
if any(ind in name_lower for ind in description_indicators):
return False
# OS names that appear near Command Palette mentions
if name_lower in _CMD_PALETTE_STOPWORDS:
return False
# Settings toggle label patterns — typically lowercase descriptive phrases
# that describe a behavior rather than an action command.
# Real commands typically start with a verb: Open, Toggle, Set, Copy, etc.
_settings_toggle_phrases = {
"autocomplete quotes", "autosuggestions", "block dividers",
"compact mode", "copy on select", "cursor blink",
"error underlining for commands", "expand aliases as you type",
"help improve warp", "input hint text", "send crash reports",
"show tab indicators", "show warning before quitting",
"syntax highlighting for commands", "syntax highlighting",
"tab indicators", "show sticky command header",
"settings sync", "empty session", "secret redaction",
"sticky command header", "vim keybindings",
}
if name_lower in _settings_toggle_phrases:
return False
# Ends with common non-command suffixes
if name.endswith(".") or name.endswith("…"):
return False
return True
def extract_command_palette_refs(file_path: Path) -> List[Dict[str, Any]]:
"""Extract Command Palette command name references from a markdown file."""
results = []
try:
text = file_path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
return results
lines = text.splitlines()
for line_num, line in enumerate(lines, start=1):
# Check if "Command Palette" is mentioned nearby (within 2 lines)
context_start = max(0, line_num - 3)
context_end = min(len(lines), line_num + 1)
context = " ".join(lines[context_start:context_end])
has_palette_context = "command palette" in context.lower()
# Pattern: Command Palette > CommandName
for match in RE_CMD_PALETTE_ARROW.finditer(line):
name = match.group(1).strip()
if _is_plausible_command_name(name):
results.append({
"file": str(file_path),
"line": line_num,
"name": name,
"pattern": "arrow",
"line_text": line,
})
# Pattern: quoted strings near Command Palette mention
if has_palette_context:
for match in RE_CMD_PALETTE_QUOTED.finditer(line):
name = match.group(1).strip()
if _is_plausible_command_name(name):
# Skip if preceded by a UI action keyword (toggle, click, etc.)
# — these are toggle/button labels, not CP commands
prefix = line[:match.start()]
if _RE_UI_LABEL_PREFIX.search(prefix):
continue
# Skip if already captured by arrow pattern
if not any(
r["line"] == line_num and r["name"] == name
for r in results
):
results.append({
"file": str(file_path),
"line": line_num,
"name": name,
"pattern": "quoted",
"line_text": line,
})
return results
# ---------------------------------------------------------------------------
# Validation
# ---------------------------------------------------------------------------
def _best_fuzzy_match(needle: str, haystack: List[str]) -> Tuple[Optional[str], float]:
"""Find the best fuzzy match for needle in haystack."""
best_match = None
best_score = 0.0
needle_lower = needle.lower()
for candidate in haystack:
score = SequenceMatcher(None, needle_lower, candidate.lower()).ratio()
if score > best_score:
best_score = score
best_match = candidate
return best_match, best_score
def _suggest_migration_for_deprecated_section(
segments: List[str],
deprecated: Dict[str, Any],
umbrellas: Dict[str, Any],
) -> Optional[Dict[str, Any]]:
"""If segments[1] is a deprecated section, return an auto-fix suggestion.
Handles patterns like:
Settings > AI > Input -> Settings > Agents > Oz > Input
Settings > AI > Knowledge -> Settings > Agents > Knowledge
Settings > Platform -> Settings > Cloud platform > Oz Cloud API Keys
Settings > Environments -> Settings > Cloud platform > Environments
Settings > MCP Servers -> Settings > Agents > MCP servers
"""
if len(segments) < 2:
return None
old_section = segments[1]
info = deprecated.get(old_section)
if not info:
return None
umbrella = info["umbrella"]
default_subpage = info["default_subpage"]
subsection_map = info.get("subsection_to_subpage", {})
if len(segments) == 2:
# Settings > Platform -> Settings > Cloud platform > Oz Cloud API Keys
new_path = ["Settings", umbrella, default_subpage]
return {
"valid": False,
"issue": (
f"\"{old_section}\" has moved under the \"{umbrella}\" umbrella; "
f"use \"{default_subpage}\""
),
"suggestion": " > ".join(new_path),
"confidence": 0.95,
"fix_type": "deprecated_section",
}
# len(segments) >= 3 — check if segments[2] routes to a specific subpage
old_sub = segments[2]
remaining = segments[3:]
mapped_subpage = subsection_map.get(old_sub, default_subpage)
aliases = info.get("subsection_aliases", [])
# If old_sub is an alias for a subpage name (e.g. "AI > Knowledge" where
# "Knowledge" is now a subpage under Agents, or "AI > Agents" where "Agents"
# was the old label for the "Profiles" subpage), drop it. Otherwise treat
# old_sub as a sub-section header that should remain at its deeper level.
if old_sub in aliases or old_sub == mapped_subpage:
# Also strip any leading alias segments from `remaining` — they come from
# paths like `AI > Agents > Profiles` where both `Agents` and `Profiles`
# redundantly refer to the new `Profiles` subpage; drop them so we get
# `Agents > Profiles` instead of `Agents > Profiles > Profiles`.
while remaining and (
remaining[0] in aliases
or remaining[0] == mapped_subpage
):
remaining = remaining[1:]
new_path = ["Settings", umbrella, mapped_subpage] + remaining
else:
new_path = ["Settings", umbrella, mapped_subpage, old_sub] + remaining
return {
"valid": False,
"issue": (
f"\"Settings > {old_section}\" has moved under the \"{umbrella}\" umbrella"
),
"suggestion": " > ".join(new_path),
"confidence": 0.95,
"fix_type": "deprecated_section",
}
def validate_ui_path(path: str, valid_paths: Dict[str, Any]) -> Dict[str, Any]:
"""Validate a single UI path against valid_paths data.
Returns a dict with keys: valid, issue, suggestion, confidence, fix_type.
"""
segments = [s.strip() for s in path.split(">")]
root = segments[0]
settings = valid_paths.get("settings_sections", {})
umbrellas = valid_paths.get("umbrellas", {})
deprecated = valid_paths.get("deprecated_sections", {})
menu_bar = valid_paths.get("macos_menu_bar", {})
warp_drive = valid_paths.get("warp_drive", {})
# --- Settings paths ---
if root == "Settings" and len(segments) >= 2:
section = segments[1]
section_names = list(settings.keys())
# Flag deprecated top-level section names BEFORE fuzzy matching
# so we suggest the umbrella-based replacement.
if section in deprecated:
migration = _suggest_migration_for_deprecated_section(
segments, deprecated, umbrellas
)
if migration:
return migration
# --- Umbrella paths (Settings > Agents > Oz > Input, etc.) ---
if section in umbrellas:
umbrella_data = umbrellas[section]
subpages = umbrella_data.get("subpages", [])
if len(segments) < 3:
# Settings > Agents alone is ambiguous — flag but don't fail hard.
return {
"valid": False,
"issue": (
f"\"Settings > {section}\" is an umbrella; pick a subpage"
),
"suggestion": (
f"Valid subpages: {', '.join(subpages)}"
),
"confidence": 0.5,
"fix_type": None,
}
subpage = segments[2]
if subpage not in subpages:
ci_match = next(
(s for s in subpages if s.lower() == subpage.lower()), None
)
if ci_match:
return {
"valid": False,
"issue": (
f"Case mismatch: \"{subpage}\" should be \"{ci_match}\""
),
"suggestion": " > ".join(
["Settings", section, ci_match] + segments[3:]
),
"confidence": 0.95,
"fix_type": "case_mismatch",
}
best, score = _best_fuzzy_match(subpage, subpages)
if score >= FUZZY_MATCH_THRESHOLD:
return {
"valid": False,
"issue": (
f"\"{subpage}\" is not a known subpage of "
f"\"{section}\""
),
"suggestion": (
f"Did you mean \"{best}\"? (score: {score:.2f})"
),
"confidence": score,
"fix_type": "fuzzy" if score >= AUTO_FIX_THRESHOLD else None,
}
return {
"valid": False,
"issue": (
f"\"{subpage}\" is not a known subpage of "
f"\"{section}\""
),
"suggestion": (
f"Valid subpages: {', '.join(subpages)}"
),
"confidence": 0.0,
"fix_type": None,
}
# Valid umbrella > subpage. Now check optional sub-section (segments[3:]).
if len(segments) >= 4:
subpage_data = settings.get(subpage, {})
sub_sections = subpage_data.get("sub_sections", [])
sub = segments[3]
if sub in sub_sections:
return {
"valid": True,
"issue": None,
"suggestion": None,
"confidence": 1.0,
"fix_type": None,
}
if sub_sections:
ci_match = next(
(s for s in sub_sections if s.lower() == sub.lower()),
None,
)
if ci_match:
return {
"valid": False,
"issue": (
f"Case mismatch: \"{sub}\" should be "
f"\"{ci_match}\""
),
"suggestion": " > ".join(
["Settings", section, subpage, ci_match]
+ segments[4:]
),
"confidence": 0.95,
"fix_type": "case_mismatch",
}
# Unknown sub-section — likely a toggle/setting name; allow.
return {
"valid": True,
"issue": None,
"suggestion": None,
"confidence": 0.8,
"fix_type": None,
}
return {
"valid": True,
"issue": None,
"suggestion": None,
"confidence": 1.0,
"fix_type": None,
}
# Guard: if this section is an umbrella subpage (it has an 'umbrella' field in
# settings_sections), the caller is using the subpage as a bare top-level section
# (e.g. "Settings > Oz" instead of "Settings > Agents > Oz"). Flag and suggest
# the correct full umbrella path.
section_entry = settings.get(section, {})
if section_entry.get("umbrella"):
umbrella_name = section_entry["umbrella"]
correct_path = " > ".join(["Settings", umbrella_name, section] + segments[2:])
return {
"valid": False,
"issue": (
f"\"{section}\" is a subpage under the \"{umbrella_name}\" umbrella; "
f"use the full path"
),
"suggestion": correct_path,
"confidence": 0.95,
"fix_type": "deprecated_section",
}
# Check section (case-insensitive)
exact = section in section_names
if not exact:
ci_match = next(
(s for s in section_names if s.lower() == section.lower()), None
)
if ci_match:
return {
"valid": False,
"issue": f"Case mismatch: \"{section}\" should be \"{ci_match}\"",
"suggestion": " > ".join(["Settings", ci_match] + segments[2:]),
"confidence": 0.95,
"fix_type": "case_mismatch",
}
best, score = _best_fuzzy_match(section, section_names)
if score >= FUZZY_MATCH_THRESHOLD:
return {
"valid": False,
"issue": f"\"{section}\" is not a known Settings section",
"suggestion": f"Did you mean \"{best}\"? (score: {score:.2f})",
"confidence": score,
"fix_type": "fuzzy" if score >= AUTO_FIX_THRESHOLD else None,
}
return {
"valid": False,
"issue": f"\"{section}\" is not a known Settings section",
"suggestion": f"Valid sections: {', '.join(sorted(section_names))}",
"confidence": 0.0,
"fix_type": None,
}
# Sub-section validation: only check case mismatches for known sub-sections.
# Individual toggle/setting names beyond the section level are not captured in
# valid_paths.json, so we skip validation for unrecognized sub-sections.
if len(segments) >= 3:
section_data = settings.get(section, {})
sub_sections = section_data.get("sub_sections", [])
sub = segments[2]
# Exact match — valid
if sub in sub_sections:
return {"valid": True, "issue": None, "suggestion": None, "confidence": 1.0, "fix_type": None}
# Case mismatch against a known sub-section — still flag these
if sub_sections:
ci_match = next(
(s for s in sub_sections if s.lower() == sub.lower()), None
)
if ci_match:
return {
"valid": False,
"issue": f"Case mismatch: \"{sub}\" should be \"{ci_match}\"",
"suggestion": " > ".join(["Settings", section, ci_match] + segments[3:]),
"confidence": 0.95,
"fix_type": "case_mismatch",
}
# Unrecognized sub-section — skip (likely a toggle/setting name)
return {"valid": True, "issue": None, "suggestion": None, "confidence": 0.8, "fix_type": None}
return {"valid": True, "issue": None, "suggestion": None, "confidence": 1.0, "fix_type": None}
# --- macOS menu bar paths ---
if root in ("File", "View", "Warp") and len(segments) >= 2:
menu_items = menu_bar.get(root, [])
item = segments[1]
if item in menu_items:
return {"valid": True, "issue": None, "suggestion": None, "confidence": 1.0, "fix_type": None}
best, score = _best_fuzzy_match(item, menu_items)
if score >= FUZZY_MATCH_THRESHOLD:
return {
"valid": False,
"issue": f"\"{item}\" is not a known {root} menu item",
"suggestion": f"Did you mean \"{best}\"? (score: {score:.2f})",
"confidence": score,
"fix_type": "fuzzy" if score >= AUTO_FIX_THRESHOLD else None,
}
return {
"valid": False,
"issue": f"\"{item}\" is not a known {root} menu item",
"suggestion": f"Valid items: {', '.join(menu_items)}" if menu_items else None,
"confidence": 0.0,
"fix_type": None,
}
# --- Warp Drive paths ---
if root in ("Warp Drive", "Personal") and len(segments) >= 2:
spaces = warp_drive.get("spaces", [])
object_types = warp_drive.get("object_types", [])
all_valid = spaces + object_types
item = segments[1]
if item in all_valid:
return {"valid": True, "issue": None, "suggestion": None, "confidence": 1.0, "fix_type": None}
best, score = _best_fuzzy_match(item, all_valid)
if score >= FUZZY_MATCH_THRESHOLD:
return {
"valid": False,
"issue": f"\"{item}\" is not a known Warp Drive item",
"suggestion": f"Did you mean \"{best}\"? (score: {score:.2f})",
"confidence": score,
"fix_type": "fuzzy" if score >= AUTO_FIX_THRESHOLD else None,
}
return {
"valid": False,
"issue": f"\"{item}\" is not a known Warp Drive item",
"suggestion": f"Valid items: {', '.join(sorted(all_valid))}",
"confidence": 0.0,
"fix_type": None,
}
# Single-segment root — valid if it's a known root
if root in WARP_UI_ROOTS and len(segments) == 1:
return {"valid": True, "issue": None, "suggestion": None, "confidence": 1.0, "fix_type": None}
return {"valid": True, "issue": None, "suggestion": None, "confidence": 0.5, "fix_type": None}
def validate_command_name(name: str, valid_paths: Dict[str, Any]) -> Dict[str, Any]:
"""Validate a Command Palette name against valid_paths data."""
commands = valid_paths.get("command_palette_commands", [])
descriptions = [c["description"] for c in commands]
# Exact match
if name in descriptions:
return {"valid": True, "issue": None, "suggestion": None, "confidence": 1.0}
# Case-insensitive match
ci_match = next((d for d in descriptions if d.lower() == name.lower()), None)
if ci_match:
return {
"valid": False,
"issue": f"Case mismatch: \"{name}\" should be \"{ci_match}\"",
"suggestion": ci_match,
"confidence": 0.95,
}
# Fuzzy match
best, score = _best_fuzzy_match(name, descriptions)
if score >= FUZZY_MATCH_THRESHOLD:
return {
"valid": False,
"issue": f"\"{name}\" is not a known Command Palette command",
"suggestion": f"Did you mean \"{best}\"? (score: {score:.2f})",
"confidence": score,
}
return {
"valid": False,
"issue": f"\"{name}\" is not a known Command Palette command",
"suggestion": None,
"confidence": 0.0,
}
# ---------------------------------------------------------------------------
# Format consistency checking
# ---------------------------------------------------------------------------
# Formats that are NOT canonical
_NON_CANONICAL_FORMATS = {"backtick", "seg_backtick", "bold", "italic", "bare"}
def check_format_issues(all_refs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Check extracted UI path refs for non-canonical formatting.
Canonical format is per-segment bold: **Settings** > **AI** > **Active AI**
"""
issues = []
for ref in all_refs:
fmt = ref["format"]
if fmt not in _NON_CANONICAL_FORMATS:
continue
canonical = _to_canonical_format(ref["normalized"])
issues.append({
"file": ref["file"],
"line": ref["line"],
"raw": ref.get("match_text", ref["raw"]),
"normalized": ref["normalized"],
"format": fmt,
"canonical": canonical,
"line_text": ref["line_text"],
})
return issues
# ---------------------------------------------------------------------------
# UI element format checking
# ---------------------------------------------------------------------------
# Action keywords that imply a clickable UI element follows.
# "press" and "hit" are excluded — they typically precede keyboard keys.
_UI_ACTION_KEYWORDS = {
"click", "select", "toggle", "enable", "disable",
"choose", "check", "uncheck", "expand", "collapse",
"open", "close", "tap",
}
# Regex: action keyword followed by backtick-wrapped text.
# Allows optional prepositions/articles between keyword and backtick:
# click `Save`, click on `Save`, click the `Save` button
_RE_ACTION_BACKTICK = re.compile(
r"\b(" + "|".join(_UI_ACTION_KEYWORDS) + r")(?:\s+(?:on|the|a|an))?\s+`([^`]+)`",
re.IGNORECASE,
)
# Common keyboard key names that should stay in backticks
_KEYBOARD_KEYS = {
"enter", "return", "tab", "escape", "esc", "space", "backspace", "delete",
"up", "down", "left", "right", "home", "end", "pageup", "pagedown",
"f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
"fn",
}
def _is_code_like(text: str) -> bool:
"""Return True if backtick content looks like code rather than a UI element."""
t = text.strip()
# Single all-lowercase word (no spaces, no capitals) is almost certainly a
# code identifier or API field name (e.g. `detail`, `status`, `type`, `error`)
# rather than a UI label, which typically starts with a capital letter.
if re.match(r'^[a-z][a-z0-9]*$', t):
return True
# Known keyboard key names
if t.lower() in _KEYBOARD_KEYS:
return True
# CLI flags and options
if t.startswith("-") or t.startswith("--"):
return True
# Slash commands, file paths
if t.startswith("/") or t.startswith("."):
return True
# Environment variables
if t.startswith("$"):
return True
# Contains code-like characters: (), {}, [], =
if re.search(r"[(){}\[\]=]", t):
return True
# Contains underscores (identifiers) or dots (file extensions, methods)
if "_" in t or ("." in t and not t.endswith(".")):
return True
# Contains backtick-unfriendly patterns: looks like a command or path
if re.search(r"\S+/\S+", t): # e.g. owner/repo
return True
# All-uppercase with no spaces likely a key or env var (e.g. RIGHT-CLICK, CMD-ENTER)
if t.replace("-", "").replace("+", "").isupper() and " " not in t:
return True
# Keyboard shortcuts: modifier combos (⌘, ⌥, ⌃, Ctrl+, Cmd+, etc.)
if re.search(r"[⌘⌥⌃⇧↩↑↓←→]", t):
return True
if re.search(r"(?i)(ctrl|cmd|alt|shift|option|meta)[+\-]", t):
return True
# Single character (likely a key)
if len(t) == 1:
return True
# Looks like inline code: contains :: or -> (Rust/C++ style)
if "::" in t or "->" in t:
return True
# CamelCase without spaces (e.g. CloudEnvironment, myFunction)
if " " not in t and re.search(r"[a-z][A-Z]", t):
return True
return False
def check_ui_element_format(md_files: List[Path]) -> List[Dict[str, Any]]:
"""Find clickable UI elements in backticks that should be bold.
Detects patterns like: Click `Save` → should be Click **Save**
Excludes code-like content (CLI flags, paths, keyboard shortcuts, etc.).
"""
issues = []
for md_file in md_files:
try:
text = md_file.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
continue
in_code_block = False
for line_num, line in enumerate(text.splitlines(), start=1):
# Skip fenced code blocks
stripped = line.strip()
if stripped.startswith("```"):
in_code_block = not in_code_block
continue
if in_code_block:
continue
# Skip HTML comments and hint blocks
if stripped.startswith("<!--") or stripped.startswith("{%"):
continue
for m in _RE_ACTION_BACKTICK.finditer(line):
element_text = m.group(2).strip()
if _is_code_like(element_text):
continue
raw = f"`{m.group(2)}`"
canonical = f"**{element_text}**"
issues.append({
"file": str(md_file),
"line": line_num,
"raw": raw,
"normalized": element_text,
"format": "ui_element_backtick",
"canonical": canonical,
"line_text": line,
})
return issues
def apply_format_fixes(format_issues: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Apply auto-fixes to convert non-canonical UI path formats to canonical bold."""
fixes_by_file: Dict[str, List[Dict[str, Any]]] = {}
applied = []
for issue in format_issues:
file_path = issue["file"]
fixes_by_file.setdefault(file_path, []).append(issue)
for file_path, file_issues in fixes_by_file.items():
try:
text = Path(file_path).read_text(encoding="utf-8")
for issue in file_issues:
old = issue["raw"]
new = issue["canonical"]
if old in text:
text = text.replace(old, new, 1)
applied.append({
"file": file_path,
"line": issue["line"],
"old": old,
"new": new,
})
Path(file_path).write_text(text, encoding="utf-8")
except OSError as e:
print(f" Warning: could not fix {file_path}: {e}", file=sys.stderr)
return applied
# ---------------------------------------------------------------------------
# File scanning
# ---------------------------------------------------------------------------
SKIP_DIRS = {"_book", "node_modules", ".git", "__pycache__"}
def scan_docs(
docs_dir: Path,
include_changelog: bool = False,
) -> List[Path]:
"""Collect all .md and .mdx files under docs_dir, excluding skip dirs."""
files = []
patterns = ["*.md", "*.mdx"]
candidates = sorted(
f for p in patterns for f in docs_dir.rglob(p)
)
for md_file in candidates:
# Skip directories
parts = set(md_file.relative_to(docs_dir).parts)
if parts & SKIP_DIRS:
continue
if not include_changelog and "changelog" in parts:
continue
files.append(md_file)
return files
# ---------------------------------------------------------------------------
# Auto-fix