Repository navigation
Expand file tree
/
Copy pathaudit.py
More file actions
executable file
·2507 lines (2169 loc) · 95.8 KB
/
Copy pathaudit.py
File metadata and controls
executable file
·2507 lines (2169 loc) · 95.8 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
# /// script
# requires-python = ">=3.13"
# dependencies = ["markdown-it-py>=4", "pyyaml>=6"]
# ///
"""Live fleet audit: the deterministic subset of AUDIT.md, run from the hub with gh and the libraries above.
Compares each cataloged registry repo against the ground truth in this repo and never modifies a target.
Findings are DEFECT, LETTER (a required file is absent, intent unverified), DRIFT (non-breaking divergence), and ERROR
(a gh call failed). It exits non-zero when any repo has a DEFECT, LETTER, or ERROR finding.
Usage: uv run --no-project --script spec/audit.py [RepoName ...] [--branch REF]
--branch overrides each repo's registry groundTruthBranch for the run.
A shallow hub clone makes a sweep report one ERROR per repo, and `--issue` exits 2 with "Run `git fetch --unshallow origin` in that checkout."
"""
import argparse
import base64
import fnmatch
import functools
import hashlib
import itertools
import json
import pathlib
import posixpath
import re
import subprocess
import sys
import urllib.parse
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Any
import validate # sibling, import-safe (its main is guarded)
import yaml
from audit_markdown import (
description_findings,
heading_texts,
readme_link_findings,
readme_section_findings,
readme_shield_findings,
strip_md_links,
tagline,
third_party_tool_findings,
title_and_intro,
undeclared_h2_headings,
)
from fidelity_text import extract_section, normalize, strip_sections
ROOT = pathlib.Path(__file__).resolve().parent.parent
SETTINGS_KEYS = [
"has_wiki",
"has_projects",
"allow_merge_commit",
"allow_squash_merge",
"allow_rebase_merge",
"allow_auto_merge",
"allow_update_branch",
"delete_branch_on_merge",
]
# The bypass_actors field is deliberately absent, since a bypass list is a per-repository decision configure.sh leaves alone.
RULESET_SUBSET = ["name", "target", "enforcement", "conditions", "rules"]
# Phrases that assert work is still outstanding, matched against a registry driftNote.
PENDING_MARKERS = ["pending", "not yet", "owed", "todo", "still", "behind", "missing", "absent"]
def load(rel):
return json.loads((ROOT / rel).read_text(encoding="utf-8"))
@functools.cache
def hub_tracked(rev=None):
"""The hub's own tracked paths at the resolved `main` commit.
A git failure raises, since an empty set would clear every hub-only finding.
"""
walk_rev = _hub_main_rev() if rev is None else rev
# No text=True: -z's pathnames are raw bytes, and locale decoding here would crash on an invalid byte before the NUL-split below ever runs.
r = subprocess.run(
["git", "ls-tree", "-r", "-z", walk_rev],
cwd=ROOT,
capture_output=True,
check=False,
)
if r.returncode != 0:
stderr = r.stderr.decode("utf-8", errors="replace").strip()
raise RuntimeError(
f"git ls-tree -r {walk_rev} failed in {ROOT}: {stderr or 'non-zero exit'}"
)
paths = set()
for record in r.stdout.split(b"\0"):
if not record:
continue
meta, _, path = record.partition(b"\t")
mode = meta.split(None, 1)[0] if meta else None
if mode in (b"100644", b"100755"):
paths.add(path.decode("utf-8", errors="surrogateescape"))
return frozenset(paths)
def hub_paths_below(source, include=("**/*",), rev=None):
"""Hub-tracked paths below a declared source directory, mapped from the path relative to it, that match its include patterns."""
root = source.rstrip("/") + "/"
return {
path.removeprefix(root): path
for path in hub_tracked(rev)
if path.startswith(root) and tree_path_included(path.removeprefix(root), include)
}
def hub_only_paths(spec, rev=None):
"""Hub-tracked paths the manifest does not declare, so a downstream copy is hub-hosted content rather than a carry.
A path below a declared repo-owned tree is left out, since a downstream file there is that repo's own.
"""
excluded = {e["path"] for e in spec["files"]["baseline"]}
for declaration in spec["files"].get("trees", []):
excluded.update(
hub_paths_below(declaration["source"], declaration["include"], rev).values()
)
for declaration in spec["files"].get("repoOwnedTrees", []):
excluded.update(hub_paths_below(declaration["source"], rev=rev).values())
return hub_tracked(rev) - excluded
def gap_dispositions(spec):
"""The curated ledger's manifest-gap dispositions, as path -> (disposition, reason)."""
out = {}
for g in spec.get("divergences", {}).get("gaps", []):
if (
isinstance(g, dict)
and isinstance(g.get("path"), str)
and isinstance(g.get("disposition"), str)
):
out[g["path"]] = (g["disposition"], g.get("reason", ""))
return out
def repo_tree_blobs(slug, ground_head):
"""Every blob path on a repo branch mapped to its object SHA and file mode, or None when it cannot be read in full."""
sha = (((ground_head or {}).get("commit") or {}).get("commit") or {}).get("tree", {}).get("sha")
if not sha:
return None
tree = gh(f"repos/{slug}/git/trees/{sha}?recursive=1", ok404=True)
if not tree or "tree" not in tree or tree.get("truncated"):
return None
return {
n["path"]: (n.get("sha"), n.get("mode")) for n in tree["tree"] if n.get("type") == "blob"
}
def blob_field(blobs, index):
"""One field of each repo_tree_blobs() entry, 0 for the SHA and 1 for the mode, or None for None."""
return None if blobs is None else {path: entry[index] for path, entry in blobs.items()}
def repo_tree_entries(slug, ground_head):
"""Every blob path and object SHA on a repo branch, or None when it cannot be read in full."""
return blob_field(repo_tree_blobs(slug, ground_head), 0)
def repo_tree(slug, ground_head):
entries = repo_tree_entries(slug, ground_head)
return None if entries is None else set(entries)
def in_test_directory(path):
"""Whether any directory segment of path names a test directory, compared case-insensitively."""
return any(segment.lower() in ("test", "tests") for segment in path.split("/")[:-1])
def is_python_test_module(path):
"""Whether path is a module pytest discovers by name, wherever in the tree it sits."""
name = path.rsplit("/", 1)[-1]
return name.endswith(".py") and (name.startswith("test_") or name.endswith("_test.py"))
def is_csharp_test_project(path):
"""Whether path is a C# project either named or located as a test project."""
if not path.endswith(".csproj"):
return False
name = path.rsplit("/", 1)[-1]
segments = name[: -len(".csproj")].lower().split(".")
return (
"Test" in name
or any(segment in ("test", "tests") for segment in segments)
or in_test_directory(path)
)
def coverage_candidate_types(types, repo_profiles):
"""The declared types whose profile leaves them owing coverage at all, before tests are looked for."""
profiles = repo_profiles if isinstance(repo_profiles, dict) else {}
return [t for t in types if t == "python" or profiles.get(t) != "lint-only"]
def coverage_claiming_types(types, type_mechanisms, tree):
"""The declared types that owe Codecov coverage, meaning the CODECOV_TOKEN secret and codecov.yml.
`tree` is the blob path set, or None when unread, and then every candidate keeps its claim.
"""
detectors = {
"csharp": lambda paths: any(is_csharp_test_project(p) for p in paths),
"python": lambda paths: any(
(p.endswith(".py") and in_test_directory(p)) or is_python_test_module(p) for p in paths
),
}
claiming = []
for name in types:
if type_mechanisms.get(name) != "codecov":
continue
detect = detectors.get(name)
if tree is None or detect is None or detect(tree):
claiming.append(name)
return claiming
def python_directories_of(entry):
"""The registry's declared `pythonDirectories` for entry, or [] where none is declared.
A malformed declaration drops rather than raises, since spec/validate.py reports it.
"""
dirs = entry.get("pythonDirectories")
return [d for d in dirs if isinstance(d, str)] if isinstance(dirs, list) else []
def python_directory_covers(directory, path):
"""Mirrors python_directories.py's covers(): '.' covers every path, any other directory its own subtree."""
return directory == "." or path.startswith(directory + "/")
def expected_python_directories(entry, tree):
"""The directories a caller's `python-directories` declaration is expected to resolve to.
`tree` is the blob path set, or None when unread.
"""
declared = python_directories_of(entry)
if declared:
return declared
if tree is not None and "pyproject.toml" in tree:
return ["."]
return []
# The catalog's hook snippets carry this helper into repos of every language, so it is fleet tooling rather than the repo's own Python.
CARRIED_PYTHON_HELPERS = {"hub_fetch_run.py", "hub-fetch-run.py"}
def declared_types(entry):
"""The string elements of the registry entry's `types` list, or an empty list where `types` is not a list."""
types = entry.get("types")
return [t for t in types if isinstance(t, str)] if isinstance(types, list) else []
def is_repo_python(path):
return path.endswith(".py") and posixpath.basename(path) not in CARRIED_PYTHON_HELPERS
def notes_naming(entry, cid):
"""The registry driftNotes naming check id `cid` in its parenthesized form."""
return [n for n in entry.get("driftNotes", []) if f"({cid})" in n]
def quote_note(note):
"""A driftNote quoted for a finding, cut at 70 characters."""
return f'"{note[:70]}{"..." if len(note) > 70 else ""}"'
def python_type_findings(entry, tree):
"""The discovery advisory for tracked `.py` files while the registry's `types` omits 'python'.
`tree` is the blob path set, or None when unread, which reports nothing.
"""
if tree is None or "python" in declared_types(entry):
return []
suppressed = bool(notes_naming(entry, "python.directories.declared"))
present = any(is_repo_python(p) for p in tree)
# The note-freshness check skips this note on a repo without the type, so its staleness is reported here, where the tree is.
if suppressed and not present:
return [
(
"DRIFT",
(
"registry: a driftNote suppresses the Python advisory (python.directories.declared), "
"but the tree carries no .py file. Delete the note."
),
)
]
if suppressed:
return []
if present:
return [
(
"DRIFT",
(
"registry: tracked .py file(s) present on the tree but types omits 'python'. "
"Declare the type, or record a driftNote naming (python.directories.declared) "
"with the reason Python is not tracked."
),
)
]
return []
def python_undeclared_root_findings(entry, tree):
"""DRIFT where a registry declaring no Python directory leaves a root suite no gate runs.
`tree` is the blob path set, or None when unread, which reports nothing.
"""
if tree is None or "python" not in declared_types(entry):
return []
if python_directories_of(entry) or "pyproject.toml" not in tree:
return []
if not any(p.startswith("tests/") and p.endswith(".py") for p in tree):
return []
if "uv.lock" in tree or any(
p.startswith("requirements") and p.endswith(".txt") and "/" not in p for p in tree
):
return []
return [
(
"DRIFT",
(
"python-directories: the root carries a tests/ suite with no uv.lock or "
"requirements*.txt, which the undeclared root default never runs. A lint-only root "
"declares '.' in the validator's python-directories input and the registry's "
"pythonDirectories, and a root whose pyproject.toml declares [project] adds a "
"uv.lock or requirements*.txt instead."
),
)
]
def python_directory_coverage_findings(entry, tree):
"""DRIFT naming tracked `.py` files outside every directory the registry's declaration expects.
`tree` is the blob path set, or None when unread, which reports nothing.
"""
if tree is None or "python" not in declared_types(entry):
return []
directories = expected_python_directories(entry, tree)
missed = sorted(
p
for p in tree
if is_repo_python(p) and not any(python_directory_covers(d, p) for d in directories)
)
if not missed:
return []
return [
(
"DRIFT",
(
f"python-directories: {len(missed)} tracked .py file(s) sit outside every expected "
f"directory ({', '.join(directories) or 'none'}): {capped_paths(missed)}"
),
)
]
PYTHON_FILE_STEM = re.compile(r"[a-z0-9_]+")
HYPHENATED_FILE_STEM = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
HYPHENATED_SCRIPT_EXTENSIONS = (".sh", ".ps1", ".cmd", ".bat")
PESTER_SUFFIX = ".Tests.ps1"
ENV_SECRET_FIELD = r"[a-z0-9]+(?:-+[a-z0-9]+)*"
ENV_SECRET_NAME = re.compile(rf"{ENV_SECRET_FIELD}(?:_{ENV_SECRET_FIELD})*(?:\.[a-z0-9]+)?")
ENV_SECRET_TEMPLATE = ".example"
SECRETS_DIRECTORY_EXEMPT = {"README.md", ".gitignore", ".gitkeep"}
PATHS_SHOWN = 5
def capped_paths(paths):
shown = ", ".join(paths[:PATHS_SHOWN])
more = f" and {len(paths) - PATHS_SHOWN} more" if len(paths) > PATHS_SHOWN else ""
return f"{shown}{more}"
FILE_NAMING_ID = "filenaming.scripts"
CODE_SPAN = re.compile(r"`([^`]+)`")
def file_naming_findings(entry, blobs, read_text):
"""DRIFT for script file names that break CODESTYLE.md "Script and Utility File Names".
`blobs` maps each blob path to its mode, or is None when unread, which reports nothing.
`read_text` returns a path's text or None, and is called only for an extensionless executable.
"""
if blobs is None:
return []
exempt_notes = notes_naming(entry, FILE_NAMING_ID)
python_stems = {}
for path in blobs:
directory, name = posixpath.split(path)
if name.endswith(".py"):
python_stems.setdefault(name[: -len(".py")], set()).add(directory)
broken = []
undecided = []
for path in sorted(blobs):
directory, name = posixpath.split(path)
stem, dot, extension = name.rpartition(".")
if not dot:
if blobs[path] != "100755":
continue
stem = name
else:
extension = f".{extension}"
lowered = extension.lower()
if lowered == ".py":
if extension != lowered or not PYTHON_FILE_STEM.fullmatch(stem):
broken.append(path)
continue
if lowered not in HYPHENATED_SCRIPT_EXTENSIONS:
continue
if extension != lowered:
broken.append(path)
continue
if name.endswith(PESTER_SUFFIX):
stem = name[: -len(PESTER_SUFFIX)]
if HYPHENATED_FILE_STEM.fullmatch(stem):
continue
wrapped = python_stems.get(stem, set()) if PYTHON_FILE_STEM.fullmatch(stem) else set()
if directory in wrapped and dot:
continue
if directory in wrapped:
undecided.append((path, "an extensionless launcher may be an installed command"))
continue
if wrapped:
undecided.append((path, f"a {stem}.py sits only in another directory"))
continue
if dot:
broken.append(path)
continue
text = read_text(path)
if text is None:
undecided.append((path, "unreadable, so its shebang is unknown"))
elif text.startswith("#!"):
broken.append(path)
else:
undecided.append((path, "an executable with no shebang"))
rule = 'CODESTYLE.md "Script and Utility File Names"'
findings = []
reported = set(broken) | {path for path, _ in undecided}
exempt = set()
for note in exempt_notes:
paths = CODE_SPAN.findall(note)
quoted = quote_note(note)
if not paths:
findings.append(
(
"DRIFT",
(
f"registry: a driftNote naming ({FILE_NAMING_ID}) names no path as a code "
f"span, so it exempts nothing. Name each exempt path, or delete the note: {quoted}"
),
)
)
stale = [p for p in paths if p not in reported]
if stale:
findings.append(
(
"DRIFT",
(
f"registry: a driftNote naming ({FILE_NAMING_ID}) exempts {len(stale)} "
"path(s) the file-naming check does not report. Drop each from the note, and "
f"the note once it exempts none: {capped_paths(stale)}"
),
)
)
exempt.update(paths)
broken = [p for p in broken if p not in exempt]
undecided = [f"{path} ({why})" for path, why in undecided if path not in exempt]
if broken:
findings.append(
(
"DRIFT",
(
f"file-naming: {len(broken)} file(s) break {rule}. Rename each, or where a "
f"tool or platform fixes the name, record a driftNote naming "
f"({FILE_NAMING_ID}) and the path as a code span: {capped_paths(broken)}"
),
)
)
if undecided:
findings.append(
(
"DRIFT",
(
f"file-naming: {len(undecided)} file(s) the per-extension patterns cannot "
f"decide, judge each by hand against {rule}: {capped_paths(undecided)}"
),
)
)
return findings
def secret_stem_findings(tree):
"""DRIFT naming each tracked env or secret file whose name breaks CODESTYLE.md's env and secret file rule.
Every file directly in a `.secrets/` directory is one, and so is a `.env` file elsewhere whose name opens on no dot.
`tree` is the blob path set, or None when unread, which reports nothing.
"""
if tree is None:
return []
broken = []
for path in sorted(tree):
segments = path.split("/")
name = segments[-1]
in_secrets = segments[-2:-1] == [".secrets"]
if in_secrets and name in SECRETS_DIRECTORY_EXEMPT:
continue
named = name.removesuffix(ENV_SECRET_TEMPLATE)
folded = name.lower().removesuffix(ENV_SECRET_TEMPLATE)
if not in_secrets and (folded.startswith(".") or not folded.endswith(".env")):
continue
if not ENV_SECRET_NAME.fullmatch(named):
broken.append(path)
if not broken:
return []
return [
(
"DRIFT",
(
f"runtime-secrets: {len(broken)} env or secret file(s) break the env and secret file "
f'rule of CODESTYLE.md "Script and Utility File Names", or are a bare .env in a '
f'.secrets directory, which GOVERNANCE.md "Repo-Scoped Secrets" rules out: '
f"{capped_paths(broken)}"
),
)
]
@functools.cache
def canonical_blob_sha(path):
"""The hub's git blob identity for path at the resolved `main` commit, not the working tree.
Raises OSError where path is absent from that commit or is not a regular file there.
"""
rev = _hub_main_rev()
# Read via git ls-tree, not git rev-parse <rev>:<path>, which resolves a directory to a tree object id just as readily as a file to a blob one, silently breaking the regular-file promise above.
result = subprocess.run(
["git", "ls-tree", rev, "--", path],
cwd=ROOT,
capture_output=True,
text=True,
encoding="utf-8",
errors="surrogateescape",
check=False,
)
if result.returncode != 0:
raise OSError(f"{path} is unreadable from the hub's main at {rev}: {result.stderr.strip()}")
entry = result.stdout.strip()
if not entry:
raise OSError(f"{path} is absent from the hub's main at {rev}")
mode, _, sha = entry.partition("\t")[0].split()
if mode not in ("100644", "100755"):
raise OSError(f"{path} is not a regular file at {rev} (mode {mode})")
return sha
def tree_path_included(path, patterns):
return any(
pattern == "**/*"
or fnmatch.fnmatchcase(path, pattern)
or pathlib.PurePosixPath(path).match(pattern)
for pattern in patterns
)
@functools.cache
def hub_name():
"""This repo's name on the remote, and whether it came from the remote."""
r = subprocess.run(
["git", "config", "--get", "remote.origin.url"],
capture_output=True,
text=True,
encoding="utf-8",
cwd=ROOT,
check=False,
)
if r.returncode == 0 and r.stdout.strip():
return r.stdout.strip().rstrip("/").removesuffix(".git").split("/")[-1], True
return ROOT.name, False
def hub_repo_name() -> str:
return hub_name()[0]
HTTP_STATUS = re.compile(r"\(HTTP (\d{3})\)")
def gh(path, ok404=False) -> Any:
"""GET a REST path via gh, returning parsed JSON, or None on a 404 (when ok404) or an empty response body."""
r = subprocess.run(
["gh", "api", path], capture_output=True, text=True, encoding="utf-8", check=False
)
if r.returncode != 0:
status = HTTP_STATUS.search(r.stderr)
if ok404 and status is not None and status.group(1) == "404":
return None
raise RuntimeError(
f"gh api {path}: {r.stderr.strip().splitlines()[-1] if r.stderr else 'failed'}"
)
return json.loads(r.stdout) if r.stdout.strip() else None
def owner_repos(owner):
"""Every non-fork repository the registry owner actually owns on GitHub, paginated by hand.
Run as the owner's own account, since a repository-scoped token returns an incomplete list with no error.
"""
me = gh("user")
login = me.get("login") if isinstance(me, dict) else None
# GitHub logins are case-insensitive.
if (login or "").lower() != owner.lower():
raise RuntimeError(
f"gh is authenticated as '{login}', not registry owner '{owner}'. "
"The membership check would query the wrong account's repos."
)
repos, page = [], 1
while True:
batch = gh(f"user/repos?affiliation=owner&per_page=100&page={page}")
# An empty response body reads as None here, per the gh() docstring above.
if batch is None:
raise RuntimeError(f"GitHub returned an empty repository-list response (page {page})")
if not isinstance(batch, list) or not all(isinstance(r, dict) for r in batch):
raise RuntimeError(f"GitHub returned an unexpected repository-list shape (page {page})")
repos.extend(r for r in batch if not r.get("fork"))
if len(batch) < 100:
return repos
page += 1
def repo_identity(url):
"""owner/repo, lowercased, parsed from a github.com URL, or None if it does not parse."""
if not isinstance(url, str):
return None
slug = validate.github_identity(url.strip())
return slug.lower() if slug is not None else None
def membership_findings(spec):
"""Fleet-wide: every non-fork repo the owner has on GitHub must have a registry entry."""
findings = []
# A bare-name match would treat a same-named repo under a different owner as this one's entry.
registry_by_identity = {}
for r in spec["registry"]["repos"]:
identity = repo_identity(r.get("url")) if isinstance(r, dict) else None
if identity is not None:
registry_by_identity[identity] = r
for gh_repo in owner_repos(spec["registry"]["owner"]):
entry = registry_by_identity.get(str(gh_repo.get("full_name", "")).strip().lower())
if entry is None:
findings.append(
(
"DEFECT",
f"{gh_repo['full_name']}: exists on GitHub with no registry/repos.json entry",
)
)
continue
gh_archived = bool(gh_repo.get("archived"))
reg_archived = entry.get("status") == "archived"
if gh_archived and not reg_archived:
msg = (
f"{entry['name']}: archived on GitHub but registry status is "
f"'{entry.get('status')}' (reconcile to 'archived')"
)
findings.append(("DRIFT", msg))
elif reg_archived and not gh_archived:
msg = (
f"{entry['name']}: registry status is 'archived' but GitHub reports it "
"unarchived (reconcile status, or verify it was not unarchived by mistake)"
)
findings.append(("DRIFT", msg))
return findings
def normalize_ruleset(payload):
sub = {k: payload.get(k) for k in RULESET_SUBSET}
if isinstance(sub.get("rules"), list):
sub["rules"] = sorted(sub["rules"], key=lambda r: json.dumps(r, sort_keys=True))
return json.dumps(sub, sort_keys=True)
def registered_check(cid):
"""The spec/checks.json entry registering `cid`, or {} where none does."""
return next((c for c in registered_checks() if c["id"] == cid), {})
def catalog_owner(spec, cid):
"""`(owning project type or None, whether spec/project-types.json defines the id)`."""
types = spec.get("types")
if not types:
raise KeyError(
"spec['types'] (spec/project-types.json) is required to resolve a driftNote check id"
)
for name, t in types.get("types", {}).items():
if any(c.get("id") == cid for c in t.get("checks", [])):
return name, True
cross = (c for dim in types.get("crossCutting", {}).values() for c in dim.get("checks", []))
return None, any(c.get("id") == cid for c in cross)
def is_suppression_id(entry, cid):
"""Whether a driftNote naming `cid` suppresses a registered check's finding on this repo, rather than naming a check to judge."""
check = registered_check(cid)
if "suppression" not in check:
return False
ending_type = check["suppression"]["endsWithType"]
return ending_type is None or ending_type not in declared_types(entry)
def driftnote_findings(entry, spec, open_count):
"""Freshness findings over one repo's registry driftNotes, given how many findings the audit already has."""
out = []
for note in entry.get("driftNotes", []):
quoted = quote_note(note)
for cid in validate.CHECK_ID_RE.findall(note):
if is_suppression_id(entry, cid):
continue
owner, in_catalog = catalog_owner(spec, cid)
if not (in_catalog or registered_check(cid)):
out.append(
(
"DRIFT",
f"registry: driftNote names check '{cid}', which neither spec/checks.json nor spec/project-types.json defines - fix the id or drop the note: {quoted}",
)
)
elif not in_catalog:
out.append(
(
"DRIFT",
f"registry: driftNote names check '{cid}', which this audit evaluates (spec/checks.json) - delete the note once that check passes: {quoted}",
)
)
elif owner and owner not in declared_types(entry):
out.append(
(
"DRIFT",
f"registry: driftNote names check '{cid}', whose type '{owner}' this repo does not declare: {quoted}",
)
)
else:
out.append(
(
"DRIFT",
f"registry: driftNote names check '{cid}', which this audit does not evaluate by id (AUDIT.md section 4) - judge it by hand and delete the note once it passes: {quoted}",
)
)
marker = next(
(w for w in PENDING_MARKERS if re.search(rf"\b{re.escape(w)}\b", note, re.IGNORECASE)),
None,
)
if marker and not open_count:
out.append(
(
"DRIFT",
f"registry: driftNote says '{marker}' but the audit is clean - verify and reconcile: {quoted}",
)
)
elif marker:
out.append(
(
"DRIFT",
f"registry: driftNote says '{marker}' while {open_count} finding(s) are open - confirm it describes one of them rather than closed work: {quoted}",
)
)
return out
# The owner half of the slug repo_slug() answers with when it cannot parse an entry's url, plus the stand-in for a name it cannot use.
UNRESOLVED_OWNER = "_unresolved"
UNNAMED_ENTRY = "_unnamed"
def repo_slug(entry):
"""The `<owner>/<repo>` every `repos/{slug}/...` read addresses.
An unparseable url never raises, it answers with UNRESOLVED_OWNER and the entry's name.
"""
slug = validate.github_identity(entry.get("url"))
if slug is not None:
return slug
name = str(entry.get("name", ""))
tail = urllib.parse.quote(name, safe="") if name.strip(".") else UNNAMED_ENTRY
return f"{UNRESOLVED_OWNER}/{tail}"
def workflow_model_of(entry, defaults):
"""The registry's workflow model for entry, falling back to the defaults and then to release."""
return entry.get("workflowModel") or defaults.get("workflowModel") or "release"
def repo_selectors(entry, defaults):
"""The scope-selector set a files.json appliesTo is matched against (see spec/scope-model.md)."""
sel = set(declared_types(entry))
sel.add(workflow_model_of(entry, defaults))
sel.add(entry.get("releaseTrigger") or defaults.get("releaseTrigger") or "two-phase")
# The consumerModel field has no defaults fallback, since the registry schema does not allow defaults.consumerModel and validate.py requires it on every cataloged repo.
cm = entry.get("consumerModel")
if cm:
sel.add(cm)
return sel
def applies(applies_to, sel):
"""True if an appliesTo selector applies to a repo's selector set."""
if applies_to == "*":
return True
tokens = applies_to if isinstance(applies_to, list) else [applies_to]
return bool(set(tokens) & sel)
def _section_spec(elt):
"""Normalize a sections[] entry to (name, appliesTo, fidelity)."""
if isinstance(elt, str):
return elt, "*", "intent"
return elt.get("name", ""), elt.get("appliesTo", "*"), elt.get("fidelity", "intent")
def required_sections(item, sel):
"""Section names to presence-check (heading grep) for this repo, the non-verbatim sections."""
out = []
for elt in item.get("sections", []):
name, sec, fid = _section_spec(elt)
if name and fid != "verbatim" and applies(sec, sel):
out.append(name)
return out
def verbatim_sections(item, sel):
"""Section names marked fidelity verbatim for this repo, checked byte-for-byte against the hub canonical."""
out = []
for elt in item.get("sections", []):
name, sec, fid = _section_spec(elt)
if name and fid == "verbatim" and applies(sec, sel):
out.append(name)
return out
# Carried files scanned for a coordination reference (GOVERNANCE.md "Documentation Style Conventions").
TEMPLATE_REF_SCANNED = ("AGENTS.md", "GOVERNANCE.md", ".github/copilot-instructions.md")
# The undeclared-H2 scan reads the same set.
UNDECLARED_HEADING_SCANNED = TEMPLATE_REF_SCANNED
VERSION_LITERAL_SCANNED = validate.VERSION_LITERAL_SCANNED
VERSION_LITERAL = validate.VERSION_LITERAL
def version_literals_outside_verbatim(text, verbatim_names):
"""Every version literal or commit SHA in `text` outside its verbatim sections, sorted and deduplicated."""
return sorted(
set(VERSION_LITERAL.findall(strip_sections(text, verbatim_names, keep_pins=True)))
)
def template_ref_outside_verbatim(text, verbatim_names, hub_name):
"""True when `hub_name` appears in `text` outside every one of its verbatim sections."""
return hub_name.lower() in strip_sections(text, verbatim_names).lower()
def workspace_cspell_words(text):
"""True if workspace/settings JSON carries its own cSpell word list."""
low = text.lower()
return any(
key in low for key in ('"cspell.words"', '"cspell.userwords"', '"cspell.ignorewords"')
)
def _yaml(text, compose=False):
"""`(document, True)`, the node tree with `compose`, or `(None, False)` where `text` does not parse."""
try:
return (
yaml.compose(text, Loader=yaml.SafeLoader) if compose else yaml.safe_load(text)
), True
except yaml.YAMLError:
return None, False
def _compose(text):
"""The YAML node tree of `text`, or None where it is empty or does not parse."""
return _yaml(text, compose=True)[0]
def _mapping(node):
"""A mapping node's children as `{key: node}`, `{}` for any other node."""
if not isinstance(node, yaml.MappingNode):
return {}
return {str(k.value): v for k, v in node.value if isinstance(k, yaml.ScalarNode)}
def _plain(node):
"""The Python value a node constructs, as the safe loader reads it."""
return yaml.SafeLoader("").construct_object(node, deep=True)
def job_nodes(text):
"""The workflow's jobs as `{key: node}`, `{}` where it has none or does not parse."""
return _mapping(_mapping(_compose(text)).get("jobs"))
def code_view(node, depth=0):
"""A node's keys and scalar values as lines indented per level, the shape a contract token is read in."""
out = []
def walk(child, key, level):
label = " " * level + ("" if key is None else f"{key}:")
if isinstance(child, yaml.MappingNode):
out.extend([label] if key else [])
for k, v in child.value:
walk(v, k.value, level + 1)
elif isinstance(child, yaml.SequenceNode):
out.extend([label] if key else [])
for v in child.value:
walk(v, None, level + 1)
elif key == "if":
out.append(f"{label} {' '.join(str(child.value).split())}")
elif child.style in ("|", ">"):
out.extend([label] if key else [])
else:
out.append(f"{label} {child.value}".rstrip())
if node is not None:
walk(node, None, depth - 1)
return "\n".join(out)
def split_jobs(text):
"""Each job's own source lines, `{key: text}`, cut at the parser's marks for the verbatim job hash."""
jobs = _mapping(_compose(text)).get("jobs")
if not isinstance(jobs, yaml.MappingNode) or jobs.flow_style or not jobs.value:
return {}
lines = text.splitlines(keepends=True)
indent = jobs.value[0][0].start_mark.column
end = jobs.end_mark.line + (1 if jobs.end_mark.column else 0)
starts = [k.start_mark.line for k, _ in jobs.value] + [end]
return {
str(k.value): "".join(
ln
for ln in lines[starts[i] : starts[i + 1]]
if not (ln.lstrip().startswith("#") and len(ln) - len(ln.lstrip()) < indent)
)
for i, (k, _) in enumerate(jobs.value)
}
def check_interface(path, contract, text):
"""DRIFT where a workflow breaks its fixed contract by name and wiring, never its body (spec/fidelity-model.md)."""
root, parsed = _yaml(text, compose=True)
if not parsed:
return [("DRIFT", f"interface: {path} does not parse as YAML, so its contract is unread")]
findings = []
jobs = _mapping(_mapping(root).get("jobs"))
for k in contract.get("requiredJobKeys", []):
if k not in jobs:
findings.append(("DRIFT", f"interface: {path} missing required job '{k}'"))
name = contract.get("requiredCheckName")
nodes = (_mapping(job).get("name") for job in jobs.values())
names = {n.value for n in nodes if isinstance(n, yaml.ScalarNode)}
if name and name not in names:
findings.append(
(
"DRIFT",
f"interface: {path} missing the ruleset-bound check name '{name}' as a job name",
)
)
tok = contract.get("artifactNameToken")
if tok and tok not in code_view(root):
findings.append(
("DRIFT", f"interface: {path} missing the '{tok}<branch>-<target>' artifact handoff")
)
# An absent job is already a requiredJobKeys finding, so its tokens are not reported again.
for job, toks in contract.get("requireTokensInJob", {}).items():
if job in jobs:
view = f" {job}:\n{code_view(jobs[job], 2)}"
for t in toks:
if t not in view:
findings.append(
("DRIFT", f"interface: {path} job '{job}' missing required '{t}'")
)
for job, toks in contract.get("forbidTokensInJob", {}).items():
if job in jobs:
view = f" {job}:\n{code_view(jobs[job], 2)}"
for t in toks:
if t in view:
findings.append(
("DRIFT", f"interface: {path} job '{job}' uses forbidden '{t}'")
)
return findings
# The callers whose validate job may declare validate-task.yml's `python-directories` input, per WORKFLOW.md.
PYTHON_DIRECTORIES_CALLERS = (
".github/workflows/test-pull-request.yml",
".github/workflows/publish-release.yml",
)
def normalize_declared_python_directory(line):