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
2 changes: 1 addition & 1 deletion OPERATIONS.md
Original file line number Diff line number Diff line change
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, 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.
- [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. Its `section_key()` is the one lookup key the audit, the carry, and the review ledger fold a section name to. 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.
4 changes: 2 additions & 2 deletions scripts/build_dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,12 +344,12 @@ def heading_body(lines, heading, key):
heading of its level or above, level one included. A fidelity region ends only at the next
level-two heading.
"""
want = heading.strip().lower()
reader = _fidelity_text()
want = reader.section_key(heading)
text = "\n".join(lines)
# Every level, so a level-one heading ends a body, though a key names level two down.
# That is because a level-one heading is a document's title rather than a section a skill would carry.
headings = [(h.line, h.level, h.text.lower()) for h in reader.headings(text)]
headings = [(h.line, h.level, reader.section_key(h.text)) for h in reader.headings(text)]
matches = [(index, depth) for index, depth, name in headings if name == want and depth > 1]
if not matches:
raise ValueError(f"include {key!r}: no heading {heading.strip()!r} in its source")
Expand Down
8 changes: 4 additions & 4 deletions scripts/canonical_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,14 +212,14 @@ def file_units(rel: str, text: str) -> dict[str, str]:
# Keeping the last would record a read of one of them as covering both.
# Case-folded, because the declared-name lookup folds and spec/audit.py's heading match folds.
# So a pair differing only in case is one name to every reader but this one.
earlier = seen.get(key.lower())
earlier = seen.get(fidelity_text.section_key(key))
if earlier is not None:
shown = f"'{earlier}'" if earlier == name else f"'{earlier}' and '{name}'"
raise CannotRun(
f"{rel} carries two level-two sections named {shown},"
" so a review of one cannot be told from a review of the other"
)
seen[key.lower()] = name
seen[fidelity_text.section_key(key)] = name
out[key] = region
return out

Expand Down Expand Up @@ -372,12 +372,12 @@ def build_units(
# So one re-cased declaration cannot make a section silently stop being a unit while the fidelity check still hashes it.
# The key is the document's heading rather than the manifest's spelling, so what `sweep` prints is what the file holds.
by_heading = {
key.split(SECTION_DELIM, 1)[1].strip().lower(): key
fidelity_text.section_key(key.split(SECTION_DELIM, 1)[1]): key
for key in found
if SECTION_DELIM in key
}
for name in sections:
key = by_heading.get(name.strip().lower())
key = by_heading.get(fidelity_text.section_key(name))
if key is None:
missing.append(f"{rel}{SECTION_DELIM}{name}")
else:
Expand Down
2 changes: 1 addition & 1 deletion scripts/carry.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ def section_body(lines: list[str], span: tuple[int, int]) -> str:

def fold(name: str) -> str:
"""A section name as `section_span` and `verbatim_section_names` key it."""
return name.strip().lower()
return fidelity_text_module().section_key(name)


def strip_terminator(line: str) -> str:
Expand Down
4 changes: 2 additions & 2 deletions spec/audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
title_and_intro,
undeclared_h2_headings,
)
from fidelity_text import extract_section, normalize, strip_sections
from fidelity_text import extract_section, normalize, section_key, strip_sections

ROOT = pathlib.Path(__file__).resolve().parent.parent

Expand Down Expand Up @@ -2004,7 +2004,7 @@ def check_sections_presence(run, path):
f"section: '{name}' not found as a heading in {path} on {run.ground} (renamed or missing; verify intent per AUDIT.md section 7)",
)
for name in sorted(needed)
if name.strip().lower() not in present
if section_key(name) not in present
]


Expand Down
28 changes: 14 additions & 14 deletions spec/audit_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import fidelity_text
import markdown_it
import validate
from fidelity_text import extract_section, normalize, strip_sections
from fidelity_text import extract_section, normalize, section_key, strip_sections


def docker_hub_description(slug):
Expand All @@ -31,8 +31,8 @@ def docker_hub_description(slug):

def undeclared_h2_headings(text, declared):
"""Top-level `##` headings in `text` that `declared` does not name, folded and sorted."""
h2s = {h.strip().lower() for level, h, _, _ in _atx_headings(text) if level == 2}
return sorted(h2s - {d.strip().lower() for d in declared})
h2s = {section_key(h) for level, h, _, _ in _atx_headings(text) if level == 2}
return sorted(h2s - {section_key(d) for d in declared})


# CommonMark plus tables, with escapes kept as their own tokens so a line can be rebuilt from its source.
Expand All @@ -56,7 +56,7 @@ def references(text):

def heading_texts(markdown):
"""Lowercased texts of the headings `_atx_headings` reads, for case-insensitive section-presence matching."""
return {h.strip().lower() for _, h, _, _ in _atx_headings(markdown)}
return {section_key(h) for _, h, _, _ in _atx_headings(markdown)}


_HTML_COMMENT = re.compile(r"<!--.*?-->", re.DOTALL)
Expand Down Expand Up @@ -164,7 +164,7 @@ def addressed_region(text, address):
lines = body.split("\n")
h3s = [h for h in _atx_headings(body) if h[0] == 3]
for i, (_, name, _, end) in enumerate(h3s):
if name.strip().lower() == parts[1].lower():
if section_key(name) == section_key(parts[1]):
stop = h3s[i + 1][2] if i + 1 < len(h3s) else len(lines)
return "\n".join(lines[end:stop])
return None
Expand All @@ -180,10 +180,10 @@ def ordered_headings(markdown, level):
def readme_section_findings(text, model, sel, public):
"""README section presence and order against spec/readme-sections.json."""
findings = []
by_name = {s["name"].lower(): s for s in model["sections"]}
retired = {r.lower(): s for s in model["sections"] for r in s.get("retiredNames", [])}
by_name = {section_key(s["name"]): s for s in model["sections"]}
retired = {section_key(r): s for s in model["sections"] for r in s.get("retiredNames", [])}
heads = ordered_headings(text, 2)
lower = [h.lower() for h in heads]
lower = [section_key(h) for h in heads]
present = set(lower)

for h, hl in zip(heads, lower):
Expand All @@ -201,8 +201,8 @@ def readme_section_findings(text, model, sel, public):
continue
if {t.lower() for t in s.get("notApplicableTo", [])} & {t.lower() for t in sel}:
continue
if s["name"].lower() in present or any(
r.lower() in present for r in s.get("retiredNames", [])
if section_key(s["name"]) in present or any(
section_key(r) in present for r in s.get("retiredNames", [])
):
continue
why = " (a public repo; optional while private)" if req == "public" else ""
Expand All @@ -228,7 +228,7 @@ def readme_section_findings(text, model, sel, public):
)

last = next((s for s in model["sections"] if s.get("last")), None)
if last and last["name"].lower() in present and lower[-1] != last["name"].lower():
if last and section_key(last["name"]) in present and lower[-1] != section_key(last["name"]):
findings.append(
(
"LETTER",
Expand All @@ -237,11 +237,11 @@ def readme_section_findings(text, model, sel, public):
)

for s in model["sections"]:
if s["name"].lower() not in present or not s.get("subsections"):
if section_key(s["name"]) not in present or not s.get("subsections"):
continue
have = {h.lower() for h in ordered_headings(readme_region(text, s["name"]) or "", 3)}
have = {section_key(h) for h in ordered_headings(readme_region(text, s["name"]) or "", 3)}
for sub in s["subsections"]:
if sub.lower() not in have:
if section_key(sub) not in have:
findings.append(
(
"LETTER",
Expand Down
13 changes: 9 additions & 4 deletions spec/fidelity_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,19 @@ def sections(text):
return [(h, starts[i + 1].line if i + 1 < len(starts) else None) for i, h in enumerate(starts)]


def section_key(name):
"""The lookup key for a section name: stripped, then case-folded."""
return name.strip().lower()
Comment thread
ptr727 marked this conversation as resolved.
Resolved


def section_span(text, heading):
"""The `[start, end)` lines of the first `## <heading>` region, or None when `text` has none.

`end` is None for a region that runs to the end of the document. The match is on the parsed
heading text, case-folded, so a re-cased heading is found rather than read as absent.
"""
want = heading.strip().lower()
return next(((h.line, end) for h, end in sections(text) if h.text.lower() == want), None)
want = section_key(heading)
return next(((h.line, end) for h, end in sections(text) if section_key(h.text) == want), None)


def extract_section(text, heading):
Expand All @@ -218,11 +223,11 @@ def strip_sections(text, names, keep_pins=False):

Positional, so an identical passage elsewhere in the document survives.
"""
want = {n.strip().lower() for n in names}
want = {section_key(n) for n in names}
base = text.replace("\r\n", "\n").replace("\r", "\n") if keep_pins else normalize(text)
lines = base.split("\n")
dropped = set()
for h, end in sections(base):
if h.text.lower() in want:
if section_key(h.text) in want:
dropped.update(range(h.line, len(lines) if end is None else end))
return "\n".join(ln for i, ln in enumerate(lines) if i not in dropped)
6 changes: 6 additions & 0 deletions tests/test_fidelity_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ def test_code_lines_cover_fenced_and_indented_blocks(self) -> None:


class SectionCase(unittest.TestCase):
def test_section_key_strips_then_case_folds(self) -> None:
self.assertEqual(fidelity_text.section_key(" Mixed CASE \t"), "mixed case")
self.assertEqual(
fidelity_text.section_key("Mixed case"), fidelity_text.section_key("MIXED CASE")
)

def test_the_last_region_runs_to_the_end(self) -> None:
text = "intro\n\n## Alpha\n\na\n\n## Beta\n\nb\n"
self.assertEqual(fidelity_text.section_span(text, "alpha"), (2, 6))
Expand Down
Loading