{{ message }}
Repository navigation
Expand file tree
/
Copy pathregistry-verify.py
More file actions
1714 lines (1466 loc) · 63.3 KB
/
Copy pathregistry-verify.py
File metadata and controls
1714 lines (1466 loc) · 63.3 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
"""Structural lint for the spec-0028 icon registry tree and its qrc block.
Checks the migrated icon tree (`app/rcc/icons/`) against the registry contract:
every file sits at `<category>/<tier>/<name>.svg` with a known category and a
tier in {16, 24, 32, 48}; no byte-identical duplicates exist outside the exempt
`buttons/` set (spec AC2); rcc.qrc and the disk tree agree in both directions;
and every compat alias points at an existing file. It also lints QML icon
requests: a `Cpp_Misc_IconRegistry.icon(...)` whose px would resolve to a larger
tier than the object's render size (`iconSize`/`icon.width`/`sourceSize`) loads an
oversized SVG and is flagged (spec 0028: request px must match render size). Spec
0038 adds the widget-extension gate: the bundled packages validate against
`widget-manifest.json`, the reserved builtin-id list agrees across the schema, the
C++ catalog and the widget-string mappers, the packages stay in sync with rcc.qrc,
and `WidgetExtensions::hostContextNames()` still mirrors ModuleManager. Spec 0075
adds the extension catalog v2 gate: `catalog.json` requires a per-file SHA-256
(inline or in the `sha256` sidecar table), a v1 entry is rejected by the schema, and the installer still routes every file
through the digest parser and the staged swap. The
alias report counts live
source references to each old path -- task T21 drops the alias block only when
`--require-no-alias-refs` passes. Exit code 0 = clean, 1 = violations.
Usage:
python3 scripts/registry-verify.py [--alias-report] [--require-no-alias-refs]
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import subprocess
import sys
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RCC = ROOT / "app" / "rcc"
ICONS = RCC / "icons"
QRC = RCC / "rcc.qrc"
EXEMPT_FOLDERS = {"buttons"}
CATEGORIES = {
"widgets",
"window",
"editor",
"devices",
"panes",
"console",
"database",
"code",
"licensing",
"notifications",
"commands",
"system",
}
TIERS = {"16", "24", "32", "48"}
SOURCE_ROOTS = (ROOT / "app" / "qml", ROOT / "app" / "src", ROOT / "core")
SOURCE_EXTS = {".qml", ".cpp", ".h"}
NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]*\.svg$")
def fail(errors: list[str], message: str) -> None:
errors.append(message)
def check_tree(errors: list[str]) -> None:
hashes: dict[str, list[str]] = defaultdict(list)
for path in sorted(ICONS.rglob("*")):
if path.is_dir():
continue
rel = path.relative_to(ICONS).as_posix()
top = rel.split("/", 1)[0]
if top in EXEMPT_FOLDERS or path.name == ".DS_Store":
continue
parts = rel.split("/")
if path.suffix != ".svg":
fail(errors, f"non-SVG file in icon tree: icons/{rel}")
continue
hashes[hashlib.md5(path.read_bytes()).hexdigest()].append(rel)
if len(parts) != 3:
fail(errors, f"not <category>/<tier>/<name>.svg: icons/{rel}")
continue
category, tier, name = parts
if category not in CATEGORIES:
fail(errors, f"unknown category '{category}': icons/{rel}")
if tier not in TIERS:
fail(errors, f"tier not in {sorted(TIERS)}: icons/{rel}")
if not NAME_RE.match(name):
fail(errors, f"name not kebab-case: icons/{rel}")
for digest, paths in sorted(hashes.items()):
if len(paths) > 1:
fail(errors, f"byte-identical duplicates: {', '.join(paths)}")
def qrc_entries() -> tuple[set[str], dict[str, str]]:
text = QRC.read_text(encoding="utf-8")
real = set(re.findall(r"<file>(icons/[^<]+)</file>", text))
aliases = dict(
re.findall(r'<file alias="(icons/[^"]+)">(icons/[^<]+)</file>', text)
)
return real, aliases
def check_qrc(errors: list[str]) -> dict[str, str]:
real, aliases = qrc_entries()
disk = {f"icons/{p.relative_to(ICONS).as_posix()}" for p in ICONS.rglob("*.svg")}
for entry in sorted(real - disk):
fail(errors, f"qrc entry has no file on disk: {entry}")
for entry in sorted(disk - real):
fail(errors, f"file on disk not registered in qrc: {entry}")
for alias, target in sorted(aliases.items()):
if not (RCC / target).exists():
fail(errors, f"alias points at missing file: {alias} -> {target}")
if alias in disk:
fail(errors, f"alias shadows a real file: {alias}")
return aliases
MANIFESTS = ["app.json", "dashboard.json", "projecteditor.json", "database.json"]
LAYOUTS = [
"main-toolbar.json",
"project-toolbar.json",
"start-menu.json",
"database-toolbar.json",
]
KNOWN_CONTEXTS = {"app", "dashboard", "editor"}
KNOWN_KINDS = {"action", "toggle"}
KNOWN_WINDOWS = {"main", "editor"}
KNOWN_STANDARD_KEYS = {
"Open",
"New",
"Save",
"Quit",
"Back",
"Forward",
"Close",
"Preferences",
"Undo",
"Redo",
}
COMMERCIAL_SYMBOLS = ("Cpp_Licensing_", "Cpp_Sessions_", "Cpp_MQTT_")
KNOWN_CATEGORIES = {
"file",
"mode",
"connection",
"view",
"export",
"console",
"project",
"license",
"tools",
"help",
}
def icon_ref_resolves(ref: str) -> bool:
category, _, name = ref.partition("/")
if not category or not name:
return False
return any(
(ICONS / category / str(t) / f"{name}.svg").exists() for t in (16, 24, 32, 48)
)
def check_manifests(errors: list[str]) -> set[str]:
ids: set[str] = set()
shortcuts: dict[tuple[str, str], str] = {}
for name in MANIFESTS:
path = RCC / "commands" / name
if not path.exists():
fail(errors, f"missing command manifest: {name}")
continue
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as error:
fail(errors, f"invalid JSON in {name}: {error}")
continue
for command in data.get("commands", []):
cid = command.get("id", "")
if not cid or cid in ids:
fail(errors, f"{name}: missing or duplicate id '{cid}'")
continue
ids.add(cid)
if command.get("kind", "action") not in KNOWN_KINDS:
fail(errors, f"{name}: {cid} has unknown kind")
cat = command.get("category")
if cat is not None and cat not in KNOWN_CATEGORIES:
fail(errors, f"{name}: {cid} has unknown category '{cat}'")
for ctx in command.get("contexts", []):
if ctx not in KNOWN_CONTEXTS:
fail(errors, f"{name}: {cid} has unknown context '{ctx}'")
for key in ("icon", "iconChecked"):
ref = command.get(key)
if ref and not icon_ref_resolves(ref):
fail(errors, f"{name}: {cid} {key} '{ref}' does not resolve")
shortcut = command.get("shortcut", "")
if shortcut.startswith("StandardKey."):
if shortcut.split(".", 1)[1] not in KNOWN_STANDARD_KEYS:
fail(
errors,
f"{name}: {cid} unknown {shortcut} (extend the C++ table)",
)
for window in command.get("shortcutWindows", []):
if window not in KNOWN_WINDOWS:
fail(errors, f"{name}: {cid} unknown shortcut window '{window}'")
if shortcut:
key = (window, shortcut)
if key in shortcuts:
fail(
errors,
f"duplicate shortcut {shortcut} in window {window}: "
f"{shortcuts[key]} and {cid}",
)
shortcuts[key] = cid
return ids
def check_layout_nodes(
errors: list[str], name: str, nodes: list, ids: set[str]
) -> None:
for node in nodes:
if node.get("type") == "command" and node.get("id") not in ids:
fail(
errors, f"{name}: layout references unknown command '{node.get('id')}'"
)
for ref in node.get("collapsedCommands", []):
if ref not in ids:
fail(errors, f"{name}: collapsedCommands references unknown '{ref}'")
ref = node.get("icon")
if ref and not icon_ref_resolves(ref):
fail(errors, f"{name}: layout icon '{ref}' does not resolve")
check_layout_nodes(errors, name, node.get("items", []), ids)
def check_layouts(errors: list[str], ids: set[str]) -> None:
for name in LAYOUTS:
path = RCC / "commands" / "layouts" / name
if not path.exists():
fail(errors, f"missing layout manifest: {name}")
continue
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as error:
fail(errors, f"invalid JSON in {name}: {error}")
continue
for key in ("sections", "items", "pinnedEnd"):
check_layout_nodes(errors, name, data.get(key, []), ids)
MENUS = "editor-menus.json"
MENU_BINDINGS = "ProjectEditorMenuBindings.qml"
def menu_command_ids(nodes: list, out: set[str]) -> None:
for node in nodes:
if node.get("type") == "command":
out.add(node.get("id", ""))
menu_command_ids(node.get("items", []), out)
def check_menus(errors: list[str], ids: set[str]) -> None:
path = RCC / "commands" / "layouts" / MENUS
if not path.exists():
fail(errors, f"missing menu manifest: {MENUS}")
return
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as error:
fail(errors, f"invalid JSON in {MENUS}: {error}")
return
names: set[str] = set()
for menu in data.get("menus", []):
name = menu.get("name", "")
if not name or name in names:
fail(errors, f"{MENUS}: missing or duplicate menu name '{name}'")
continue
names.add(name)
referenced: set[str] = set()
for menu in data.get("menus", []):
check_layout_nodes(errors, MENUS, menu.get("items", []), ids)
menu_command_ids(menu.get("items", []), referenced)
check_menu_includes(errors, menu.get("items", []), names)
bindings = ROOT / "app" / "qml" / "Commands" / MENU_BINDINGS
if not bindings.is_file():
fail(errors, f"missing menu bindings: {MENU_BINDINGS}")
return
text = bindings.read_text(encoding="utf-8")
bound = set(re.findall(r'"([\w.]+)":\s*root\.cmd', text))
for cid in sorted(referenced - bound):
fail(errors, f"{MENUS}: '{cid}' has no binding in {MENU_BINDINGS}")
def check_menu_includes(errors: list[str], nodes: list, names: set[str]) -> None:
for node in nodes:
target = node.get("include")
if target is not None and target not in names:
fail(errors, f"{MENUS}: include references unknown menu '{target}'")
check_menu_includes(errors, node.get("items", []), names)
def check_binding_guards(errors: list[str]) -> None:
bindings_dir = ROOT / "app" / "qml" / "Commands"
if not bindings_dir.is_dir():
return
for path in sorted(bindings_dir.glob("*.qml")):
lines = path.read_text(encoding="utf-8").splitlines()
for number, line in enumerate(lines, 1):
previous = lines[number - 2] if number >= 2 else ""
guarded = "Cpp_CommercialBuild" in line or "Cpp_CommercialBuild" in previous
for symbol in COMMERCIAL_SYMBOLS:
if symbol in line and not guarded:
fail(
errors,
f"{path.name}:{number}: {symbol} reference without a "
f"Cpp_CommercialBuild guard on the same or previous line",
)
QML_ROOT = ROOT / "app" / "qml"
RENDER_RES = (
re.compile(r"\biconSize\s*:\s*(\d+)\b"),
re.compile(r"\bicon\.width\s*:\s*(\d+)\b"),
re.compile(r"\bicon\.height\s*:\s*(\d+)\b"),
re.compile(r"\bsourceSize\.width\s*:\s*(\d+)\b"),
re.compile(r"\bsourceSize\.height\s*:\s*(\d+)\b"),
)
REQUEST_RE = re.compile(r"IconRegistry\.icon(?:ById)?\([^)]*\b(\d+)\s*\)")
ELEMENT_RE = re.compile(r"([A-Za-z_][A-Za-z0-9_.]*)\s*\{")
SORTED_TIERS = (16, 24, 32, 48)
# Components whose icon slot renders at a fixed size declared in the component file, invisible
# to the same-block scan (e.g. Widgets/Pane.qml draws `icon` at sourceSize 16).
COMPONENT_SLOT_PX = {
"Pane": 16,
}
def served_tier(px: int) -> int:
for tier in SORTED_TIERS:
if px <= tier:
return tier
return SORTED_TIERS[-1]
def strip_qml_noise(line: str, in_comment: bool) -> tuple[str, bool]:
out: list[str] = []
index = 0
length = len(line)
while index < length:
two = line[index : index + 2]
if in_comment:
if two == "*/":
in_comment = False
index += 2
continue
index += 1
continue
if two == "//":
break
if two == "/*":
in_comment = True
index += 2
continue
char = line[index]
if char in ('"', "'"):
index += 1
while index < length and line[index] != char:
index += 1
index += 1
continue
out.append(char)
index += 1
return "".join(out), in_comment
def check_icon_render_sizes(errors: list[str]) -> None:
for path in sorted(QML_ROOT.rglob("*.qml")):
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
stack: list[dict] = []
in_comment = False
rel = path.relative_to(ROOT).as_posix()
for number, line in enumerate(lines, 1):
if stack:
for regex in RENDER_RES:
match = regex.search(line)
if match and stack[-1]["render"] is None:
stack[-1]["render"] = int(match.group(1))
for match in REQUEST_RE.finditer(line):
stack[-1]["requests"].append((int(match.group(1)), number))
clean, in_comment = strip_qml_noise(line, in_comment)
names = [m.group(1).rsplit(".", 1)[-1] for m in ELEMENT_RE.finditer(clean)]
for char in clean:
if char == "{":
name = names.pop(0) if names else None
stack.append({"render": None, "requests": [], "name": name})
elif char == "}" and stack:
block = stack.pop()
render = block["render"]
if render is None:
render = COMPONENT_SLOT_PX.get(block["name"])
if render is None:
continue
for px, where in block["requests"]:
tier = served_tier(px)
if tier > served_tier(render):
fail(
errors,
f"{rel}:{where}: icon requested at {px}px loads the "
f"{tier}px tier but is rendered at {render}px (spec "
f"0028: request px must match render size)",
)
# ---------------------------------------------------------------------------------------------------
# Spec 0037: generated API surfaces
# ---------------------------------------------------------------------------------------------------
SKILLS = RCC / "ai" / "skills"
DATASET_MANIFEST = RCC / "properties" / "dataset.json"
SERIALSTUDIO_H = ROOT / "core" / "Core" / "SerialStudio.h"
REGISTRY_GENERATOR = ROOT / "scripts" / "generate-property-registry.py"
# Prose that claims the API rejects a spelling it actually accepts. The dataset manifest
# declares plotMin/widgetMin/xAxis/datasetSourceId as aliases, so a corpus sentence pairing
# one of them with a rejection phrase teaches the assistant a fact the code contradicts.
REJECTION_PHRASES = (
"accepts only",
"accepts ONLY",
"accept only",
"silently drops",
"silently drop",
"silently ignores",
"silently ignored",
"silently ignore",
"writes nothing",
"does not accept",
"are NOT the keys",
"is NOT the key",
)
# Lines whose rejection phrasing is about genuinely unknown fields, not a declared alias.
CORPUS_WHITELIST = (
# fooBar in the warnings example is a deliberately invalid field name.
"fooBar",
)
def dataset_manifest() -> dict:
return json.loads(DATASET_MANIFEST.read_text(encoding="utf-8"))
def dataset_name_space(manifest: dict) -> tuple[set[str], set[str]]:
"""Return (every accepted dataset field spelling, the declared alias spellings)."""
names: set[str] = set()
aliases: set[str] = set()
for prop in manifest["properties"]:
names.add(prop["jsonKey"])
api = prop.get("api", {})
if not api.get("expose"):
continue
names.add(api["name"])
for alias in api.get("aliases", []):
names.add(alias)
aliases.add(alias)
for sub in manifest.get("subEntities", []):
names.add(sub["apiName"])
for arg in sub.get("legacy", {}).get("args", []):
names.add(arg["name"])
for runtime in manifest.get("runtimeFields", []):
if runtime.get("jsonKey"):
names.add(runtime["jsonKey"])
return names, aliases
def dataset_option_bits() -> dict[str, int]:
"""Parse the DatasetOption bitflags out of Core/SerialStudio.h, the corpus tables' truth."""
text = SERIALSTUDIO_H.read_text(encoding="utf-8")
block = re.search(r"enum DatasetOption\s*\{(.*?)\}", text, re.DOTALL)
if not block:
return {}
bits: dict[str, int] = {}
for name, value in re.findall(r"Dataset(\w+)\s*=\s*(0b[01]+)", block.group(1)):
if name != "Generic":
bits[name.lower()] = int(value, 2)
return bits
def table_rows(text: str) -> list[tuple[list[str], list[str]]]:
"""Return every markdown table row paired with its header cells."""
rows: list[tuple[list[str], list[str]]] = []
header: list[str] = []
for line in text.splitlines():
stripped = line.strip()
if not stripped.startswith("|"):
header = []
continue
cells = [c.strip() for c in stripped.strip("|").split("|")]
if not header:
header = cells
continue
if all(set(c) <= set("-: ") for c in cells):
continue
rows.append((header, cells))
return rows
def check_option_bit_tables(errors: list[str]) -> None:
"""Every widget-option bit stated in the corpus must match the DatasetOption enum."""
bits = dataset_option_bits()
if not bits:
fail(errors, "could not parse DatasetOption from core/Core/SerialStudio.h")
return
for path in sorted(SKILLS.glob("*.md")):
text = path.read_text(encoding="utf-8")
for header, cells in table_rows(text):
index = next(
(i for i, c in enumerate(header) if "bit" in c.lower()),
None,
)
if index is None or index >= len(cells):
continue
slug = re.search(r"`\"?([a-z0-9-]+)\"?`", cells[0])
value = re.search(r"`?(\d+)`?", cells[index])
if not slug or not value or slug.group(1) not in bits:
continue
if bits[slug.group(1)] != int(value.group(1)):
fail(
errors,
f"{path.name}: option '{slug.group(1)}' is stated as bit "
f"{value.group(1)}, SerialStudio.h declares {bits[slug.group(1)]}",
)
missing = sorted(b for b in bits if f'`"{b}"`' not in text)
if len(missing) < len(bits) and missing:
fail(
errors,
f"{path.name}: widget-option table omits {', '.join(missing)}; "
"state every DatasetOption bit or cross-reference the one table that does",
)
def check_enum_domains(errors: list[str], manifest: dict) -> None:
"""An integer enum value stated in the corpus must exist in the declared domain."""
domains: dict[str, set[int]] = {}
for prop in manifest["properties"]:
api = prop.get("api", {})
source = manifest["optionSources"].get(prop.get("options", ""), {})
if not api.get("expose") or source.get("kind") != "parallelValues":
continue
domains[api["name"]] = {int(e["value"]) for e in source["entries"]}
if not domains:
return
anchor = re.compile("|".join(re.escape(n) for n in sorted(domains)))
for path in sorted(SKILLS.glob("*.md")):
text = path.read_text(encoding="utf-8")
anchors = [(m.start(), m.group(0)) for m in anchor.finditer(text)]
if not anchors:
continue
for match in re.finditer(r"\b(\d+)=", text):
prior = [a for a in anchors if a[0] < match.start()]
if not prior:
continue
start, name = prior[-1]
if match.start() - start > 400:
continue
if int(match.group(1)) not in domains[name]:
fail(
errors,
f"{path.name}: {name} value {match.group(1)} is not in the "
f"declared domain {sorted(domains[name])}",
)
def paragraphs(text: str) -> list[tuple[int, str]]:
"""Return (first line number, text) per blank-line block; each table row stands alone.
A markdown table is one visual block but many independent claims -- scanning it as a
single paragraph pairs one row's field name with another row's rejection wording.
"""
out: list[tuple[int, str]] = []
start = 1
buffer: list[str] = []
def flush() -> None:
nonlocal buffer
if buffer:
out.append((start, "\n".join(buffer)))
buffer = []
for number, line in enumerate(text.splitlines(), 1):
if line.lstrip().startswith("|"):
flush()
out.append((number, line))
continue
if line.strip():
if not buffer:
start = number
buffer.append(line)
continue
flush()
flush()
return out
def check_field_name_refs(errors: list[str], manifest: dict) -> None:
"""Field names stated in the corpus's write-form mapping tables must be declared."""
names, aliases = dataset_name_space(manifest)
for path in sorted(SKILLS.glob("*.md")):
text = path.read_text(encoding="utf-8")
for header, cells in table_rows(text):
joined = " ".join(header).lower()
if "dataset.update" not in joined and "write-form" not in joined:
continue
for cell in cells:
for token in re.findall(r"`([A-Za-z][A-Za-z0-9]*)`", cell):
if token not in names:
fail(
errors,
f"{path.name}: field '{token}' is stated in a dataset "
"write-form table but is not declared in "
"app/rcc/properties/dataset.json",
)
for number, block in paragraphs(text):
if any(token in block for token in CORPUS_WHITELIST):
continue
named = sorted(a for a in aliases if a in block)
if not named:
continue
for phrase in REJECTION_PHRASES:
if phrase in block:
fail(
errors,
f"{path.name}:{number}: says the API rejects "
f"{', '.join(named)}, but the manifest declares "
f"{'it' if len(named) == 1 else 'them'} as accepted "
f"alias(es) of project.dataset.update",
)
break
def check_corpus_field_refs(errors: list[str]) -> None:
"""Reference lint over the bundled assistant corpus; never rewrites a file."""
if not SKILLS.is_dir() or not DATASET_MANIFEST.exists():
fail(
errors, "corpus lint skipped: missing skills directory or dataset manifest"
)
return
manifest = dataset_manifest()
check_option_bit_tables(errors)
check_enum_domains(errors, manifest)
check_field_name_refs(errors, manifest)
def check_api_snapshot(errors: list[str]) -> None:
"""Fold the buildless api-schema.json projection check into this run.
The projection warns locally (only a build can refresh the snapshot) and fails in CI,
where the generator sees CI in the environment.
"""
if not REGISTRY_GENERATOR.is_file():
fail(
errors,
"api snapshot check skipped: generate-property-registry.py is missing",
)
return
result = subprocess.run(
[sys.executable, str(REGISTRY_GENERATOR), "--check-snapshot"],
capture_output=True,
text=True,
)
sys.stdout.write(result.stdout)
if result.returncode != 0:
fail(errors, "api-schema.json does not match the dataset property manifest")
# ---------------------------------------------------------------------------------------------------
# Spec 0036: dataset property manifest
# ---------------------------------------------------------------------------------------------------
PROPERTY_SCHEMA = RCC / "properties" / "schema.json"
FRAME_H = ROOT / "core" / "Core" / "DataModel" / "Frame.h"
FRAME_KEYS_H = ROOT / "core" / "Core" / "DataModel" / "FrameKeys.h"
HOOKS_H = ROOT / "core" / "Pipeline" / "DataModel" / "Project" / "PropertyHooks.h"
VALIDATORS_H = ROOT / "core" / "Core" / "DataModel" / "PropertyValidators.h"
EDITOR_H = ROOT / "core" / "Ui" / "ProjectEditor" / "ProjectEditor.h"
MODEL_H = ROOT / "core" / "Pipeline" / "DataModel" / "ProjectModel.h"
GENERATED_REGISTRY = (
ROOT / "core" / "Pipeline" / "DataModel" / "Generated" / "DatasetRegistry.h"
)
# Hooks the generated code never calls: the caller owns the dialog and the deferred form
# snap-back, so no PropertyHooks symbol backs the name.
CALLER_OWNED_HOOKS = {"onAliasRejected"}
# Manifest fields whose value names a hook, paired with the hook kind it must declare.
HOOK_REFERENCES = {
"visibleWhen": "predicate",
"enabledWhen": "predicate",
"validate": "validator",
"placeholderHook": "placeholder",
"onCommit": "commit",
}
SCHEMA_KEYWORDS = {
"$ref",
"$id",
"$schema",
"additionalProperties",
"definitions",
"description",
"enum",
"items",
"minItems",
"properties",
"required",
"title",
"type",
}
SCHEMA_TYPES = {"object": dict, "array": list, "string": str, "boolean": bool}
def type_matches(value, kind: str) -> bool:
if kind == "integer":
return isinstance(value, int) and not isinstance(value, bool)
if kind == "number":
return isinstance(value, (int, float)) and not isinstance(value, bool)
return isinstance(value, SCHEMA_TYPES[kind])
def validate_object(
value: dict, schema: dict, where: str, root: dict, errors: list[str]
):
props = schema.get("properties", {})
extra = schema.get("additionalProperties", True)
for name in schema.get("required", []):
if name not in value:
fail(errors, f"dataset.json: {where} is missing required '{name}'")
for name, entry in value.items():
if name in props:
validate_node(entry, props[name], f"{where}.{name}", root, errors)
elif extra is False:
fail(errors, f"dataset.json: {where}.{name} is not declared in schema.json")
elif isinstance(extra, dict):
validate_node(entry, extra, f"{where}.{name}", root, errors)
def validate_node(
value, schema: dict, where: str, root: dict, errors: list[str]
) -> None:
"""Validate one manifest node against the draft-07 subset schema.json actually uses.
Self-contained rather than jsonschema-backed so the gate runs identically in
sanitize-commit.py and in CI; an unrecognized keyword fails loudly instead of being
skipped, so the schema can never outgrow the validator silently.
"""
if "$ref" in schema:
target = schema["$ref"]
name = target.rsplit("/", 1)[-1]
if not target.startswith("#/definitions/") or name not in root.get(
"definitions", {}
):
fail(errors, f"schema.json: unresolved $ref '{target}'")
return
validate_node(value, root["definitions"][name], where, root, errors)
return
for keyword in schema:
if keyword not in SCHEMA_KEYWORDS:
fail(
errors,
f"schema.json: unsupported keyword '{keyword}' at {where}; teach "
"registry-verify's validator about it before using it",
)
return
kind = schema.get("type")
if kind and not type_matches(value, kind):
fail(errors, f"dataset.json: {where} must be a {kind}")
return
if "enum" in schema and value not in schema["enum"]:
fail(
errors, f"dataset.json: {where} = {value!r} is not one of {schema['enum']}"
)
if isinstance(value, dict):
validate_object(value, schema, where, root, errors)
elif isinstance(value, list):
if len(value) < schema.get("minItems", 0):
fail(errors, f"dataset.json: {where} needs {schema['minItems']} item(s)")
for index, entry in enumerate(value):
if "items" in schema:
validate_node(entry, schema["items"], f"{where}[{index}]", root, errors)
def struct_fields(text: str, name: str) -> list[str]:
"""Return the member names of a struct, in declaration order."""
block = re.search(
rf"struct (?:alignas\(\d+\) )?{name} \{{(.*?)\n\}};", text, re.DOTALL
)
if not block:
return []
fields: list[str] = []
for line in block.group(1).splitlines():
stripped = line.split("///")[0].strip()
match = re.match(r"^[A-Za-z_][\w:<>, ]*?\s+(\w+)\s*(=|;)", stripped)
if match:
fields.append(match.group(1))
return fields
def enum_values(text: str, pattern: str) -> list[str]:
block = re.search(pattern, text, re.DOTALL)
if not block:
return []
body = re.sub(r"//[^\n]*", "", block.group(1))
return [v.strip().split("=")[0].strip() for v in body.split(",") if v.strip()]
def declared_symbols(text: str) -> set[str]:
"""Return every function name declared in a header."""
return set(re.findall(r"\b(\w+)\s*\(", text))
def manifest_field_owners(manifest: dict) -> dict[str, list[str]]:
"""Map every struct field the manifest accounts for to the entries that claim it."""
owners: dict[str, list[str]] = defaultdict(list)
for prop in manifest["properties"]:
owners[prop["field"]].append(f"property {prop['id']}")
for runtime in manifest["runtimeFields"]:
owners[runtime["field"]].append("runtimeFields")
for sub in manifest["subEntities"]:
owners[sub["field"]].append("subEntities")
return owners
def check_manifest_keys(errors: list[str], manifest: dict, keys: set[str]) -> None:
"""Every jsonKey the manifest names must be a real Keys:: constant in FrameKeys.h."""
referenced: list[tuple[str, str]] = []
for prop in manifest["properties"]:
if prop.get("jsonKey"):
referenced.append((prop["id"], prop["jsonKey"]))
for legacy in prop.get("legacyKeys", []):
referenced.append((prop["id"], legacy))
for runtime in manifest["runtimeFields"]:
if runtime.get("jsonKey"):
referenced.append((runtime["field"], runtime["jsonKey"]))
for sub in manifest["subEntities"]:
if sub.get("jsonKey"):
referenced.append((sub["field"], sub["jsonKey"]))
for owner, constant in referenced:
if constant not in keys:
fail(
errors,
f"dataset.json: {owner} names jsonKey '{constant}', which is not a "
"Keys:: constant in core/Core/DataModel/FrameKeys.h",
)
def check_manifest_hooks(errors: list[str], manifest: dict) -> None:
"""Every referenced hook is declared, of the right kind, and backed by C++."""
hooks = manifest["hooks"]
hooks_text = HOOKS_H.read_text(encoding="utf-8") if HOOKS_H.exists() else ""
hooks_text += (
VALIDATORS_H.read_text(encoding="utf-8") if VALIDATORS_H.exists() else ""
)
frame_text = FRAME_H.read_text(encoding="utf-8") if FRAME_H.exists() else ""
hook_symbols = declared_symbols(hooks_text)
frame_symbols = declared_symbols(frame_text)
referenced: list[tuple[str, str, str]] = []
for prop in manifest["properties"]:
for attribute, kind in HOOK_REFERENCES.items():
if prop.get(attribute):
referenced.append((f"property {prop['id']}", prop[attribute], kind))
for sub in manifest["subEntities"]:
referenced.append((sub["field"], sub["readHook"], "subEntity"))
referenced.append((sub["field"], sub["writeHook"], "subEntity"))
for source in manifest["optionSources"].values():
if source.get("hook"):
referenced.append(("optionSources", source["hook"], "optionProvider"))
for owner, name, kind in referenced:
declared = hooks.get(name)
if declared is None:
fail(errors, f"dataset.json: {owner} references undeclared hook '{name}'")
continue
if declared["kind"] != kind:
fail(
errors,
f"dataset.json: {owner} uses hook '{name}' as a {kind}, but it is "
f"declared as a {declared['kind']}",
)
for name, declared in hooks.items():
pool = frame_symbols if declared["kind"] == "subEntity" else hook_symbols
home = (
"core/Core/DataModel/Frame.h"
if declared["kind"] == "subEntity"
else "core/Pipeline/DataModel/Project/PropertyHooks.h or "
"core/Core/DataModel/PropertyValidators.h"
)
symbol = re.search(r"(\w+)\(", declared["signature"])
if symbol and symbol.group(1) in pool:
continue
if name in pool:
continue
if name in CALLER_OWNED_HOOKS and "caller-owned" in declared["signature"]:
continue
fail(
errors,
f"dataset.json: hook '{name}' is not declared in {home} and is not marked "
"caller-owned",
)
def check_manifest_form(errors: list[str], manifest: dict) -> None:
"""Widgets, form ids, option sources and cross-references resolve."""
props = {prop["id"]: prop for prop in manifest["properties"]}
editor_text = EDITOR_H.read_text(encoding="utf-8") if EDITOR_H.exists() else ""
model_text = MODEL_H.read_text(encoding="utf-8") if MODEL_H.exists() else ""
widgets = set(enum_values(editor_text, r"enum EditorWidget \{(.*?)\};"))
accessors = declared_symbols(model_text)
for prop in manifest["properties"]:
widget = prop.get("widget")
if widget and widget not in widgets:
fail(
errors,
f"dataset.json: property {prop['id']} declares widget '{widget}', "
"which is not a ProjectEditor::EditorWidget enumerator",
)
for attribute in ("pairWith", "persistWith"):
partner = prop.get(attribute)
if partner and partner not in props:
fail(
errors,
f"dataset.json: property {prop['id']}.{attribute} names undeclared "
f"property '{partner}'",
)
source = prop.get("options")
if source and source not in manifest["optionSources"]:
fail(
errors,
f"dataset.json: property {prop['id']} names undeclared option source "
f"'{source}'",
)
for name, source in manifest["optionSources"].items():
for field in source.get("fields", []):
if field not in props:
fail(
errors,
f"dataset.json: option source {name} drives undeclared property "
f"'{field}'",
)
for attribute in ("labelProvider", "valueProvider"):
provider = source.get(attribute)
if provider and provider not in accessors:
fail(
errors,
f"dataset.json: option source {name}.{attribute} names "
f"{provider}(), which ProjectModel.h does not declare",
)
for builder in manifest["form"]["builders"]:
for row in builder["rows"]:
if row not in props:
fail(
errors,
f"dataset.json: form builder {builder['function']} emits undeclared "
f"property '{row}'",
)
You can’t perform that action at this time.
