Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions .github/actions/validate/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@ runs:
using: composite
steps:

- name: Setup uv step
uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
with:
python-version: "3.13"

- name: Validate registry and spec step
shell: bash
run: |
set -Eeuo pipefail
for f in registry/*.json spec/*.json repo-config/*.json; do
jq empty "$f"
done
python3 spec/validate.py

- name: Setup uv step
uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
with:
python-version: "3.13"
uv run --no-project --script spec/validate.py

# The unittest suite under tests/ is the validator's Python leg, since the hub declares '.' in python-directories, so it runs there under coverage and uploads to Codecov like any adopter's.
# What stays here is the audit's helper suite and each self-test that is not a unittest suite.
Expand Down
4 changes: 2 additions & 2 deletions OPERATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ python3 scripts/repo_gate.py
python3 scripts/prose_lint.py . --check charset --check semicolon --check dash --check dupword --check spelling --check comment-wrap --check comment-case --check home-path --check dead-path --check issue-ref --check sentence-length
python3 scripts/prose_lint.py . --check charset-unknown --summary
for f in registry/*.json spec/*.json repo-config/*.json; do jq empty "$f"; done
python3 spec/validate.py
uv run --no-project --script spec/validate.py
python3 scripts/docker_lint.py
```

Expand Down Expand Up @@ -141,5 +141,5 @@ The `gh api --method PATCH repos/[owner/repo]/pulls/[number]` form still works a
- [catalog/](./catalog/) holds reference snippets the audit compares implementations against.
- [reports/](./reports/) holds per-repo audit output.
- [scripts/](./scripts/) holds the gates that run in CI and locally, and that every fleet repository reaches rather than carries.
- [spec/fidelity_text.py](./spec/fidelity_text.py) reads headings and code blocks with markdown-it-py for the audit's region extraction, the carry, the skill build, and the review ledger alike. Its `extract_section()` and `strip_sections()` are the audit's region reading, and its `normalize()` is the comparable form the audit and the carry share.
- [spec/fidelity_text.py](./spec/fidelity_text.py) reads headings and code blocks with markdown-it-py for the audit's region extraction, the carry, the skill build, the review ledger, and the validator. It also reads reference definitions for the audit's README link checks, and link targets for the validator's carried-link check. Its `extract_section()` and `strip_sections()` are the audit's region reading, and its `normalize()` is the comparable form the audit and the carry share.
- `read_regular_file()` and `write_regular_file()` in [host-setup/agent-safety/claude/install.py](./host-setup/agent-safety/claude/install.py) are the shared primitives for reading and replacing a file that must be regular. Each opens without blocking and judges the open descriptor, so a FIFO or a device is refused rather than hanging the call.
55 changes: 35 additions & 20 deletions spec/audit_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,18 +109,25 @@ def tagline(intro):

_MD_IMAGE_INLINE = re.compile(r"!\[[^\]]*\]\((\S+?)\)")

_LINK_DEF = re.compile(r"^\[([^\]]+)\]:\s*(\S+)", re.MULTILINE)

# A URI scheme needs more than one character so a `C:` drive letter is not read as one.
_URI_SCHEME = re.compile(r"[a-z][a-z0-9+.\-]+:", re.IGNORECASE)


def unfenced_text(text):
"""`text` normalized with every fenced code block's lines removed, since markup in a sample is shown rather than used."""
base = normalize(text)
lines = base.split("\n")
fenced = {i for b in fidelity_text.code_blocks(base) if b.fenced for i in range(b.start, b.end)}
return "\n".join(ln for i, ln in enumerate(lines) if i not in fenced)
fenced = fidelity_text.code_lines(base, fenced_only=True)
return "\n".join(ln for i, ln in enumerate(base.split("\n")) if i not in fenced)


def definitions(text):
"""The reference definitions the document renders, as written and in order, read by the parser rather than by a line scan."""
return fidelity_text.link_definitions(normalize(text))


def reference_table(text):
"""Each definition's destination keyed the way a reference finds it, so `![x][Docs]` resolves to `[docs]`."""
return {fidelity_text.reference_key(d.label): d.url for d in definitions(text)}


def readme_region(text, heading):
Expand All @@ -129,9 +136,13 @@ def readme_region(text, heading):


def shield_endpoints(region, defs):
"""The image URLs a Markdown region renders, from its `![alt][ref]` and `![alt](url)` uses."""
"""The image URLs a Markdown region renders, from its `![alt][ref]` and `![alt](url)` uses.

`defs` is the document's reference_table.
"""
region = region or ""
urls = [defs[m.group(1)] for m in _MD_IMAGE_REF.finditer(region) if m.group(1) in defs]
keys = (fidelity_text.reference_key(m.group(1)) for m in _MD_IMAGE_REF.finditer(region))
urls = [defs[k] for k in keys if k in defs]
return urls + [m.group(1) for m in _MD_IMAGE_INLINE.finditer(region)]


Expand Down Expand Up @@ -324,9 +335,13 @@ def readme_link_findings(text, model, slug):
declared = [g["name"] for g in groups]
holds = {g["name"].lower(): g["holds"] for g in groups}

unfenced = unfenced_text(text)
base = normalize(text)
fenced = fidelity_text.code_lines(base, fenced_only=True)
starts = {d.line: d for d in fidelity_text.link_definitions(base)}
seen_headers, current, in_group = [], None, {}
for ln in unfenced.split("\n"):
for i, ln in enumerate(base.split("\n")):
if i in fenced:
continue
s = ln.strip()
h = re.fullmatch(r"<!--\s*(.*?)\s*-->", s)
if h and "omit from toc" not in h.group(1):
Expand All @@ -335,16 +350,17 @@ def readme_link_findings(text, model, slug):
):
current = h.group(1)
continue
d = _LINK_DEF.match(s)
d = starts.get(i)
if d:
if current is not None and current not in in_group:
seen_headers.append(current)
in_group.setdefault(current, []).append((d.group(1), d.group(2)))
in_group.setdefault(current, []).append((d.label, d.url))

all_defs = [p for v in in_group.values() for p in v]
# A reference the document renders as an image is a shield whatever host serves it, so resolve those first.
by_ref = dict(all_defs)
rendered = {m.group(1) for m in _MD_IMAGE_REF.finditer(unfenced) if m.group(1) in by_ref}
unfenced = unfenced_text(text)
images = {fidelity_text.reference_key(m.group(1)) for m in _MD_IMAGE_REF.finditer(unfenced)}
rendered = {ref for ref, _ in all_defs if fidelity_text.reference_key(ref) in images}
described = {"shield": "a badge", "anchor": "an in-page anchor", "local": "a path in this repo"}
for ref, url in all_defs:
kind = link_kind(url, slug, ref in rendered, prefixes)
Expand Down Expand Up @@ -430,8 +446,7 @@ def third_party_tool_findings(text, catalog):
if body is None:
return [] # the absent section is already one finding from readme_section_findings
declared = {t["name"].lower(): t for t in catalog["tools"]}
# Read over the unfenced text, as readme_link_findings does: a sample footnote is not a definition.
defs = {m.group(1): m.group(2) for m in _LINK_DEF.finditer(unfenced_text(text))}
defs = reference_table(text)
findings = []
listed = []
in_head = False
Expand All @@ -454,7 +469,7 @@ def third_party_tool_findings(text, catalog):
want = declared.get(name.lower())
if want is None:
continue
url = defs.get(ref)
url = defs.get(fidelity_text.reference_key(ref))
if url is not None and url.rstrip("/") != want["link"].rstrip("/"):
findings.append(
(
Expand Down Expand Up @@ -488,16 +503,16 @@ def readme_shield_findings(text, model, entry):
"""Shield presence, by the additive classes in spec/readme-sections.json."""
findings = []
unfenced = unfenced_text(text)
defs = {m.group(1): m.group(2) for m in _LINK_DEF.finditer(unfenced)}
defs = reference_table(text)
# A retired badge service is scanned across the whole document rather than per section, since a dead badge is wrong wherever it sits.
rendered_urls = set(shield_endpoints(unfenced, defs))
used_refs = {m.group(1) for m in _MD_IMAGE_REF.finditer(unfenced)}
used_refs = {fidelity_text.reference_key(m.group(1)) for m in _MD_IMAGE_REF.finditer(unfenced)}
for dep in model.get("deprecatedShields", []):
defined_urls = set()
for ref, url in sorted(defs.items()):
for ref, url in sorted((d.label, d.url) for d in definitions(text)):
if dep["match"] in url:
defined_urls.add(url)
if ref in used_refs:
if fidelity_text.reference_key(ref) in used_refs:
verb = f"renders {dep['label']}"
elif url in rendered_urls:
verb = f"defines {dep['label']} and it is rendered elsewhere"
Expand Down
92 changes: 86 additions & 6 deletions spec/fidelity_text.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
"""The text reading the fidelity tools share, so each one splits a document at the same boundaries.

Fences and headings come from markdown-it-py. So every tool that imports this module runs under
`uv run --no-project --script`, or imports it only on the path that reads a region.
Fences, headings, and links come from markdown-it-py. So every tool that imports this module runs
under `uv run --no-project --script`, or imports it only on the path that reads a document.
"""

import functools
import re
from typing import NamedTuple

import markdown_it
from markdown_it.common.utils import normalizeReference

# A `uses: <action>@<40-hex sha>` pin plus an optional version-shaped comment, which Dependabot bumps per repo.
_ACTION_PIN = re.compile(r"(\buses:[ \t]*[^\s@]+)@[0-9a-fA-F]{40}(?:[ \t]+#[ \t]*v?[0-9][\w.\-]*)?")
Expand All @@ -23,7 +24,17 @@

# Block rules only, since a region boundary is a block fact, and skipping the inline pass keeps a parse per file cheap.
# Tables are on because GitHub renders them, and a table changes where a block ends.
_BLOCKS = markdown_it.MarkdownIt("commonmark").enable("table").disable("inline")
_BLOCKS = (
markdown_it.MarkdownIt("commonmark", {"inline_definitions": True})
.enable("table")
.disable("inline")
)

_LINKS = markdown_it.MarkdownIt("commonmark").enable("table")

_DESTINATION = re.compile(
r"\[(?:[^\[\]\\]|\\[\s\S])*\]:[ \t]*\n?[ \t>]*(?:<((?:[^<>\n\\]|\\.)*)>|(\S+))"
)


@functools.lru_cache(maxsize=16)
Expand All @@ -49,6 +60,14 @@ class CodeBlock(NamedTuple):
closed: bool


class LinkDefinition(NamedTuple):
"""A reference definition: its label and destination as written, and its zero-based line."""

label: str
url: str
line: int


def normalize(text):
"""`text` with line endings, action pins, and job `needs:` lists neutralized, the drift governed elsewhere.

Expand Down Expand Up @@ -94,9 +113,70 @@ def code_blocks(text):
return out


def code_lines(text):
"""The zero-based lines of `text` that sit inside a code block, where a marker is content."""
return frozenset(line for block in code_blocks(text) for line in range(block.start, block.end))
def code_lines(text, fenced_only=False):
"""The zero-based lines of `text` that sit inside a code block, where a marker is content.

`fenced_only` leaves an indented block's lines out, for a reader that treats only a fenced
sample as shown rather than used.
"""
return frozenset(
line
for block in code_blocks(text)
if block.fenced or not fenced_only
for line in range(block.start, block.end)
)


def reference_key(label):
"""`label` folded the way the parser matches a reference to its definition, so `[Docs]` finds `[docs]`."""
return normalizeReference(label)


def link_definitions(text):
"""The reference definitions `text` renders, in document order, one per folded label.

The parser decides which lines are definitions. So one inside a code block is content, and so is
one that would interrupt a paragraph. Of two whose labels fold together the first wins, as it
does when GitHub renders the document. The parser keeps each label as written. Its destination
is stored normalized, so that is read from the lines the parser placed the definition on.
`text` is expected with its line endings normalized, so a definition's line indexes
`text.split("\\n")`.
"""
lines = text.split("\n")
found, seen = [], set()
for t in _tokens(text):
if t.type != "definition" or t.meta["id"] in seen:
continue
seen.add(t.meta["id"])
start, end = t.map
m = _DESTINATION.search("\n".join(lines[start:end]))
url = m.group(2) if m.group(1) is None else m.group(1)
Comment thread
ptr727 marked this conversation as resolved.
Resolved
found.append(LinkDefinition(t.meta["label"], url, start))
return found


def link_targets(text):
"""Each distinct destination `text` links to.

That is every link and image the parser reads, autolinks included, in the order they appear.
After them comes every reference definition in its own order, used or not, and so does each
duplicate the parser resolves nothing to. A carried definition carries its destination either
way. Markup in a code span or a code block is content rather than a link. Every destination is
read back from the parser's form decoded, so a link and its definition compare as one target.
"""
targets = []
env = {}
stack = list(reversed(_LINKS.parse(text, env)))
while stack:
token = stack.pop()
attr = {"link_open": "href", "image": "src"}.get(token.type)
if attr:
targets.append(_LINKS.normalizeLinkText(str(token.attrs[attr])))
stack.extend(reversed(token.children or []))
refs = [*env.get("references", {}).values(), *env.get("duplicate_refs", [])]
refs.sort(key=lambda r: r["map"][0])
targets += [_LINKS.normalizeLinkText(r["href"]) for r in refs]
return list(dict.fromkeys(targets))


def sections(text):
Expand Down
52 changes: 25 additions & 27 deletions spec/validate.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
#!/usr/bin/env python3
"""Validate the registry and spec cross-references (stdlib only).
# /// script
# requires-python = ">=3.13"
# dependencies = ["markdown-it-py>=4"]
# ///
"""Validate the registry and spec cross-references.

Checks that every cataloged repo classifies against the spec: its types resolve,
its publish mechanisms are recognized, and its secrets are consistent with
spec/secrets.json. Exits non-zero on any failure. This is the classification
dry-run the CI lint job runs; it needs no third-party packages.
dry-run the hub's validate hook runs in CI, under `uv run --no-project --script`.

The Markdown checks read through spec/fidelity_text.py, which imports markdown-it-py. They import
it only on the path main() reaches, so spec/resolve_description.py still imports this module under
whatever plain python3 repo-config/configure.sh finds.
"""

import argparse
Expand Down Expand Up @@ -148,8 +156,6 @@
CHECK_ID_RE = re.compile(r"\(([a-z][a-z0-9-]*(?:\.[a-z0-9-]+)+)\)")
CHECK_SCOPES = ("repo", "baseline", "file")
CHECK_KEYS = {"id", "family", "description", "spec", "hub", "scope", "ground", "suppression"}
MARKDOWN_INLINE_LINK = re.compile(r"\]\((?P<target>[^)\s]+)")
MARKDOWN_REFERENCE_LINK = re.compile(r"^\[[^]]+\]:\s*(?P<target>\S+)", re.MULTILINE)
TEMPLATE_REPOSITORY_URL = "https://github.com/ptr727/ProjectTemplate"


Expand Down Expand Up @@ -655,29 +661,23 @@ def github_identity(url):
return f"{owner}/{repo}"


def markdown_targets(text):
"""Yield link targets outside fenced blocks."""
visible = []
in_fence = False
for line in text.splitlines():
if re.match(r"^\s*(```|~~~)", line):
in_fence = not in_fence
continue
if not in_fence:
visible.append(line)
body = re.sub(r"`+[^`]*`+", "", "\n".join(visible))
for pattern in (MARKDOWN_INLINE_LINK, MARKDOWN_REFERENCE_LINK):
yield from (match.group("target") for match in pattern.finditer(body))
def fidelity_text_module():
"""`spec/fidelity_text.py`, imported on first use rather than at module import.

Lazily, because it imports markdown-it-py and spec/resolve_description.py imports this module
under a plain `python3` for description_errors alone.
"""
import fidelity_text

return fidelity_text


def markdown_section(text, name):
"""Return one level-two Markdown section, excluding its heading."""
match = re.search(rf"^## {re.escape(name)}\s*$", text, re.MULTILINE)
if not match:
"""Return one level-two Markdown section, excluding its heading, or "" where `text` has none."""
span = fidelity_text_module().section_span(text, name)
if span is None:
return ""
following = re.search(r"^## ", text[match.end() :], re.MULTILINE)
end = len(text) if following is None else match.end() + following.start()
return text[match.end() : end]
return "\n".join(text.split("\n")[span[0] + 1 : span[1]])


def carried_link_errors(root, baseline):
Expand Down Expand Up @@ -708,7 +708,7 @@ def carried_link_errors(root, baseline):
if isinstance(name, str):
regions.append((f"section '{name}'", markdown_section(text, name)))
for region, body in regions:
for target in markdown_targets(body):
for target in fidelity_text_module().link_targets(body):
repository_target = target.split("#", 1)[0]
is_template_link = (
repository_target == TEMPLATE_REPOSITORY_URL
Expand Down Expand Up @@ -1766,9 +1766,7 @@ def check_selector(where, applies_to):
# This is Markdown only, and only where the hub ships the file.
if path.endswith(".md") and (ROOT / path).exists():
hub_text = (ROOT / path).read_text(encoding="utf-8", errors="replace")
headings = {
m.group(1).strip() for m in re.finditer(r"^## (.+?)\s*$", hub_text, re.MULTILINE)
}
headings = {h.text for h in fidelity_text_module().headings(hub_text) if h.level == 2}
for elt in sections:
name = elt.get("name") if isinstance(elt, dict) else elt
if isinstance(name, str) and name and name not in headings:
Expand Down
Loading
Loading