coverage.py

clew/guard/coverage.py

Requirement coverage analysis for clew guard.

_collect_req_ids

set[str] clew.guard.coverage._collect_req_ids(list[TaggedFunction] all_tagged)

Collect all requirement IDs referenced across tagged functions.

clew/guard/coverage.py:219

Show on the map →

Called by analyze_coverage

Tested by

2 teststest_basic, test_empty

Calls none

Source · 7 lines
def _collect_req_ids(all_tagged: list[TaggedFunction]) -> set[str]:
    result: set[str] = set()
    for tf in all_tagged:
        result.update(tf.reqs)
    return result

Activity · 4 steps
lines 220–220result: set[str] = set()lines 221–221◇ for tf in all_taggedlines 222–222result.update(tf.reqs)lines 223–223return result

Requirements

REQ-DDB-GUARD-022

Flows

_collect_unmapped_functions

set[str] clew.guard.coverage._collect_unmapped_functions(list[TaggedFunction] all_tagged)

Find documented functions with no requirement mapping, skipping exempt ones.

clew/guard/coverage.py:234

Source · 5 lines
def _collect_unmapped_functions(all_tagged: list[TaggedFunction]) -> set[str]:
    settled = {tf.qualified or tf.name for tf in all_tagged if tf.reqs or tf.is_exempt}
    return {tf.name for tf in all_tagged if (tf.qualified or tf.name) not in settled}

Activity · 2 steps
lines 235–235settled = {tf.qualified or tf.name for tf in all_tagged if tf.reqs or tf.is_exempt}lines 236–236return {tf.name for tf in all_tagged if (tf.qualified or tf.name) not in settled}

Requirements

REQ-DDB-GUARD-022

Flows

_exempt

list[dict[str, str]] clew.guard.coverage._exempt(dict[str, dict[str, str]] rows, set[str] untagged, dict[str, Any] config)

The untagged requirements whose declared status exempts them from coverage.

clew/guard/coverage.py:200

Source · 15 lines
def _exempt(
    rows: dict[str, dict[str, str]], untagged: set[str], config: dict[str, Any]
) -> list[dict[str, str]]:
    from .config import exemption

    req = get_requirements(config)
    field = req.get("status_field", "status")
    out = []
    for rid in sorted(untagged):
        reason = exemption(rows[rid], req)
        if reason is not None:
            out.append({"req_id": rid, "status": rows[rid].get(field, ""), "reason": reason})
    return out

Activity · 9 steps
lines 203–203from .config import exemptionlines 205–205req = get_requirements(config)lines 206–206field = req.get("status_field", "status")lines 207–207out = []lines 208–208◇ for rid in sorted(untagged)lines 209–209reason = exemption(rows[rid], req)lines 210–210◇ if reason is not Nonelines 211–211out.append({"req_id": rid, "status": rows[rid].get(field, ""), "reason": reason})lines 212–212return out

Requirements

REQ-DDB-GUARD-022

Flows

_realised

list[tuple[str, str]] clew.guard.coverage._realised(set[str] uncovered, str dep_id, dict[str, Any] row, dict[str, Any] source, dict[str, Any] req)

The uncovered requirements one dependency row realises, and how.

clew/guard/coverage.py:96

Source · 20 lines
def _realised(
    uncovered: set[str],
    dep_id: str,
    row: dict[str, Any],
    source: dict[str, Any],
    req: dict[str, Any],
) -> list[tuple[str, str]]:
    from ..requirements import link_ids
    from .config import exemption

    targets = [t.split(":", 1)[-1] for t in link_ids(row) if t.split(":", 1)[-1] in uncovered]
    if not targets:
        return []
    if _tagged_at_pin(source, dep_id):
        return [(t, "implemented") for t in targets]
    if exemption(row, req) is not None:
        return [(t, "exempt") for t in targets]
    return []

Activity · 10 steps
lines 103–103from ..requirements import link_idslines 104–104from .config import exemptionlines 106–106targets = [t.split(":", 1)[-1] for t in link_ids(row) if t.split(":", 1)[-1] in uncovered]lines 107–107◇ if not targetslines 108–108return []lines 109–109◇ if _tagged_at_pin(source, dep_id)lines 110–110return [(t, "implemented") for t in targets]lines 111–111◇ if exemption(row, req) is not Nonelines 112–112return [(t, "exempt") for t in targets]lines 113–113return []

Flows

_tagged_at_pin

bool clew.guard.coverage._tagged_at_pin(dict[str, Any] source, str dep_id)

Whether a dependency's code tags a requirement at its pinned revision.

clew/guard/coverage.py:120

Source · 16 lines
def _tagged_at_pin(source: dict[str, Any], dep_id: str) -> bool:
    from ..requirements import git_text

    found = git_text(
        Path.cwd() / str(source["repo"]),
        "grep",
        "-l",
        "-w",
        "-F",
        f"@req {dep_id}",
        str(source["rev"]),
        "--",
    )
    return bool(found and found.strip())

Activity · 3 steps
lines 121–121from ..requirements import git_textlines 123–132found = git_text( Path.cwd() / str(source["repo"]), "grep", "-l", "-w", "-F", f"@req {dep_id}", str(source["rev"]), "--", )lines 133–133return bool(found and found.strip())

Flows

_via

str clew.guard.coverage._via(dict[str, str] row)

One requirement covered through a dependency, as a report line.

clew/guard/coverage.py:280

Source · 4 lines
def _via(row: dict[str, str]) -> str:
    return f"{row['req_id']} via {row['via']} ({row['how']})"

Activity · 1 steps
lines 281–281return f"{row['req_id']} via {row['via']} ({row['how']})"

Flows

_why

str clew.guard.coverage._why(dict[str, Any] row)

Why one exempt requirement is exempt: its reason, else its status.

clew/guard/coverage.py:288

Source · 4 lines
def _why(row: dict[str, Any]) -> str:
    return str(row.get("reason") or row.get("status") or "")

Activity · 1 steps
lines 289–289return str(row.get("reason") or row.get("status") or "")

Flows

analyze_coverage

dict[str, Any] clew.guard.coverage.analyze_coverage(list[str] source_dirs, dict[str, Any] config)

Analyze requirement coverage across all documented functions.

clew/guard/coverage.py:33

Source · 30 lines
def analyze_coverage(
    source_dirs: list[str],
    config: dict[str, Any],
) -> dict[str, Any]:
    full_reqs = load_requirements_full(config)
    all_tagged = collect_tagged_functions(source_dirs, config)

    all_req_ids = set(full_reqs.keys())
    tagged_reqs = _collect_req_ids(all_tagged)
    unmapped = _collect_unmapped_functions(all_tagged)
    exempt = _exempt(full_reqs, all_req_ids - tagged_reqs, config)
    uncovered = all_req_ids - tagged_reqs - {e["req_id"] for e in exempt}

    report: dict[str, Any] = {
        "total_requirements": len(all_req_ids),
        "covered": sorted(tagged_reqs & all_req_ids),
        "uncovered": sorted(uncovered),
        "exempt": exempt,
        "orphan_refs": sorted(tagged_reqs - all_req_ids),
        "unmapped_functions": sorted(unmapped),
        "traceability": traceability(all_tagged, config),
    }
    ## 2.1 (#73 item 2): ABSENT unless opted in, so a report that never looked says nothing.
    if (config.get("coverage") or {}).get("through_dependencies"):
        via = covered_via(uncovered, config)
        report["covered_via"] = via
        report["uncovered"] = sorted(uncovered - {v["req_id"] for v in via})
    return report

Activity · 13 steps
lines 37–37full_reqs = load_requirements_full(config)lines 38–38all_tagged = collect_tagged_functions(source_dirs, config)lines 40–40all_req_ids = set(full_reqs.keys())lines 41–41tagged_reqs = _collect_req_ids(all_tagged)lines 42–42unmapped = _collect_unmapped_functions(all_tagged)lines 43–43exempt = _exempt(full_reqs, all_req_ids - tagged_reqs, config)lines 44–44uncovered = all_req_ids - tagged_reqs - {e["req_id"] for e in exempt}lines 46–54report: dict[str, Any] = { "total_requirements": len(all_req_ids), "covered": sorted(tagged_reqs & all_req_ids), "uncovered": sorted(uncovered), "exempt": exempt, "orphan_refs": sorted(tagged_reqs - all_req_ids), "unmapped_functions": sorted(unmapped), "traceability": traceability(all_tagged, config), }lines 56–56◇ if (config.get("coverage") or {}).get("through_dependencies")lines 57–57via = covered_via(uncovered, config)lines 58–58report["covered_via"] = vialines 59–59report["uncovered"] = sorted(uncovered - {v["req_id"] for v in via})lines 60–60return report

Requirements

REQ-DDB-GUARD-022

Flows

coverage_gaps

bool clew.guard.coverage.coverage_gaps(dict[str, Any] report)

Whether a coverage report fails the gate.

clew/guard/coverage.py:353

Source · 3 lines
def coverage_gaps(report: dict[str, Any]) -> bool:
    trace = report.get("traceability") or {}
    return bool(report["uncovered"] or report["orphan_refs"] or trace.get("below_floor"))

1 more lines, not shown

Activity · 2 steps
lines 354–354trace = report.get("traceability") or {}lines 355–355return bool(report["uncovered"] or report["orphan_refs"] or trace.get("below_floor"))

Requirements

REQ-DDB-GUARD-022

Flows

covered_via

list[dict[str, str]] clew.guard.coverage.covered_via(set[str] uncovered, dict[str, Any] config)

The uncovered requirements a pinned dependency realises: implemented or exempt at its pin.

clew/guard/coverage.py:72

Source · 20 lines
def covered_via(uncovered: set[str], config: dict[str, Any]) -> list[dict[str, str]]:
    from ..requirements import read_catalog_at

    req = get_requirements(config)
    found: dict[str, dict[str, str]] = {}
    for source in req.get("external") or []:
        if not isinstance(source, dict) or not {"repo", "rev", "path"} <= set(source):
            continue
        name = str(source.get("name") or Path(str(source["repo"])).name)
        try:
            rows = read_catalog_at(Path.cwd(), source)
        except ValueError as exc:
            logger.warning("coverage through %s skipped: %s", name, exc)
            continue
        for dep_id, row in rows.items():
            for target, how in _realised(uncovered, dep_id, row, source, req):
                found.setdefault(target, {"req_id": target, "via": f"{name}:{dep_id}", "how": how})
    return [found[r] for r in sorted(found)]

Activity · 16 steps
lines 73–73from ..requirements import read_catalog_atlines 75–75req = get_requirements(config)lines 76–76found: dict[str, dict[str, str]] = {}lines 77–77◇ for source in req.get("external") or []lines 78–78◇ if not isinstance(source, dict) or not {"repo", "rev", "path"} <= set(source)lines 79–79continuelines 80–80name = str(source.get("name") or Path(str(source["repo"])).name)lines 81–81trylines 82–82rows = read_catalog_at(Path.cwd(), source)lines 83–83except ValueError as exclines 84–84logger.warning("coverage through %s skipped: %s", name, exc)lines 85–85continuelines 86–86◇ for dep_id, row in rows.items()lines 87–87◇ for target, how in _realised(uncovered, dep_id, row, source, req)lines 88–88found.setdefault(target, {"req_id": target, "via": f"{name}:{dep_id}", "how": how})lines 89–89return [found[r] for r in sorted(found)]

Requirements

REQ-DDB-GUARD-022

Flows

format_coverage_json

str clew.guard.coverage.format_coverage_json(dict[str, Any] report)

Format coverage report as JSON.

clew/guard/coverage.py:272

Show on the map →

Called by none

Tested by

1 teststest_json_format

Calls none

Source · 4 lines
def format_coverage_json(report: dict[str, Any]) -> str:
    return json.dumps(report, indent=2)

Activity · 1 steps
lines 273–273return json.dumps(report, indent=2)

Requirements

REQ-DDB-GUARD-022

format_coverage_markdown

str clew.guard.coverage.format_coverage_markdown(dict[str, Any] report)

Format coverage report as markdown.

clew/guard/coverage.py:300

Source · 25 lines
def format_coverage_markdown(report: dict[str, Any]) -> str:
    lines = [f"# Requirements Coverage: {len(report['covered'])}/{report['total_requirements']}"]
    if report.get("traceability"):
        lines.append(f"\n{traceability_line(report['traceability'])}")
    if report["uncovered"]:
        lines.append(f"\n## Uncovered ({len(report['uncovered'])})")
        for r in report["uncovered"]:
            lines.append(f"- {r}")
    if report.get("exempt"):
        lines.append(f"\n## Exempt by status or field ({len(report['exempt'])})")
        lines += [f"- {e['req_id']} ({_why(e)})" for e in report["exempt"]]
    if report.get("covered_via"):
        lines.append(f"\n## Covered through dependencies ({len(report['covered_via'])})")
        lines += [f"- {_via(v)}" for v in report["covered_via"]]
    if report["orphan_refs"]:
        lines.append(f"\n## Orphan Refs ({len(report['orphan_refs'])})")
        for r in report["orphan_refs"]:
            lines.append(f"- `{r}`")
    if report["unmapped_functions"]:
        lines.append(f"\n## Unmapped Functions ({len(report['unmapped_functions'])})")
        for f in report["unmapped_functions"]:
            lines.append(f"- `{f}()`")
    return "\n".join(lines)

Activity · 22 steps
lines 301–301lines = [f"# Requirements Coverage: {len(report['covered'])}/{report['total_requirements']}"]lines 302–302◇ if report.get("traceability")lines 303–303lines.append(f"\n{traceability_line(report['traceability'])}")lines 304–304◇ if report["uncovered"]lines 305–305lines.append(f"\n## Uncovered ({len(report['uncovered'])})")lines 306–306◇ for r in report["uncovered"]lines 307–307lines.append(f"- {r}")lines 308–308◇ if report.get("exempt")lines 309–309lines.append(f"\n## Exempt by status or field ({len(report['exempt'])})")lines 310–310lines += [f"- {e['req_id']} ({_why(e)})" for e in report["exempt"]]lines 311–311◇ if report.get("covered_via")lines 312–312lines.append(f"\n## Covered through dependencies ({len(report['covered_via'])})")lines 313–313lines += [f"- {_via(v)}" for v in report["covered_via"]]lines 314–314◇ if report["orphan_refs"]lines 315–315lines.append(f"\n## Orphan Refs ({len(report['orphan_refs'])})")lines 316–316◇ for r in report["orphan_refs"]lines 317–317lines.append(f"- `{r}`")lines 318–318◇ if report["unmapped_functions"]lines 319–319lines.append(f"\n## Unmapped Functions ({len(report['unmapped_functions'])})")lines 320–320◇ for f in report["unmapped_functions"]lines 321–321lines.append(f"- `{f}()`")lines 322–322return "\n".join(lines)

Requirements

REQ-DDB-GUARD-022

format_coverage_text

str clew.guard.coverage.format_coverage_text(dict[str, Any] report)

Format coverage report as text.

clew/guard/coverage.py:247

Source · 21 lines
def format_coverage_text(report: dict[str, Any]) -> str:
    lines = [f"Requirements coverage: {len(report['covered'])}/{report['total_requirements']}"]
    if report.get("traceability"):
        lines.append(traceability_line(report["traceability"]))
    sections = (
        ("Uncovered", report["uncovered"]),
        (
            "Exempt by status or field",
            [f"{e['req_id']} ({_why(e)})" for e in report.get("exempt", [])],
        ),
        ("Covered through dependencies", [_via(v) for v in report.get("covered_via", [])]),
        ("Orphan @req refs", report["orphan_refs"]),
        ("Functions without @req", [f"{f}()" for f in report["unmapped_functions"]]),
    )
    for title, items in sections:
        if items:
            lines.append(f"\n{title} ({len(items)}):")
            lines += [f"  - {i}" for i in items]
    return "\n".join(lines)

Activity · 9 steps
lines 248–248lines = [f"Requirements coverage: {len(report['covered'])}/{report['total_requirements']}"]lines 249–249◇ if report.get("traceability")lines 250–250lines.append(traceability_line(report["traceability"]))lines 251–260sections = ( ("Uncovered", report["uncovered"]), ( "Exempt by status or field", [f"{e['req_id']} ({_why(e)})" for e in report.get("exempt", [])], ), ("Covered through dependencies", [_via(v) for v in report.get("covered_via", [])]), ("Orphan @req refs", report["orphan_refs"]), ("Functions without @req", [f"{f}()" for f in report["unmapped_functions"]]), )lines 261–261◇ for title, items in sectionslines 262–262◇ if itemslines 263–263lines.append(f"\n{title} ({len(items)}):")lines 264–264lines += [f" - {i}" for i in items]lines 265–265return "\n".join(lines)

Requirements

REQ-DDB-GUARD-022

Flows

run_coverage

int clew.guard.coverage.run_coverage(list[str] source_dirs, dict[str, Any] config, str output_format="text")

Run coverage analysis and return exit code.

clew/guard/coverage.py:330

Source · 17 lines
def run_coverage(
    source_dirs: list[str],
    config: dict[str, Any],
    output_format: str = "text",
) -> int:
    report = analyze_coverage(source_dirs, config)

    formatters = {
        "json": format_coverage_json,
        "markdown": format_coverage_markdown,
    }
    formatter = formatters.get(output_format, format_coverage_text)
    print(formatter(report))

    return 1 if coverage_gaps(report) else 0

Activity · 5 steps
lines 335–335report = analyze_coverage(source_dirs, config)lines 337–340formatters = { "json": format_coverage_json, "markdown": format_coverage_markdown, }lines 341–341formatter = formatters.get(output_format, format_coverage_text)lines 342–342print(formatter(report))lines 344–344return 1 if coverage_gaps(report) else 0

Requirements

REQ-DDB-GUARD-022

Flows

traceability

dict[str, Any] clew.guard.coverage.traceability(list[TaggedFunction] all_tagged, dict[str, Any] config)

The requirement ratio: functions with a req tag among those with a req tag or an exemption.

clew/guard/coverage.py:144

Source · 31 lines
def traceability(all_tagged: list[TaggedFunction], config: dict[str, Any]) -> dict[str, Any]:
    from ..testscope import TEST_PATH_FACTS, is_test_path

    patterns = tuple(config.get("test_paths") or TEST_PATH_FACTS)
    traced: set[str] = set()
    tags_of: dict[str, set[str]] = {}
    for tf in all_tagged:
        if is_test_path(str(tf.file_path).lstrip("./"), patterns):
            continue
        key = tf.qualified or tf.name
        if tf.reqs:
            traced.add(key)
        tags_of.setdefault(key, set()).update(tf.exemptions)
    exempt = {k: tags for k, tags in tags_of.items() if k not in traced and tags}
    by_tag: dict[str, int] = {}
    for tags in exempt.values():
        for tag in tags:
            by_tag[tag] = by_tag.get(tag, 0) + 1
    total = len(traced) + len(exempt)
    ratio = round(len(traced) / total, 4) if total else None
    floor = (config.get("coverage") or {}).get("min_req_ratio")
    return {
        "req": len(traced),
        "exempt": len(exempt),
        "by_tag": dict(sorted(by_tag.items())),
        "ratio": ratio,
        "floor": floor,
        "below_floor": floor is not None and ratio is not None and ratio < floor,
    }

Activity · 20 steps
lines 145–145from ..testscope import TEST_PATH_FACTS, is_test_pathlines 147–147patterns = tuple(config.get("test_paths") or TEST_PATH_FACTS)lines 148–148traced: set[str] = set()lines 149–149tags_of: dict[str, set[str]] = {}lines 150–150◇ for tf in all_taggedlines 151–151◇ if is_test_path(str(tf.file_path).lstrip("./"), patterns)lines 152–152continuelines 153–153key = tf.qualified or tf.namelines 154–154◇ if tf.reqslines 155–155traced.add(key)lines 156–156tags_of.setdefault(key, set()).update(tf.exemptions)lines 157–157exempt = {k: tags for k, tags in tags_of.items() if k not in traced and tags}lines 158–158by_tag: dict[str, int] = {}lines 159–159◇ for tags in exempt.values()lines 160–160◇ for tag in tagslines 161–161by_tag[tag] = by_tag.get(tag, 0) + 1lines 162–162total = len(traced) + len(exempt)lines 163–163ratio = round(len(traced) / total, 4) if total else Nonelines 164–164floor = (config.get("coverage") or {}).get("min_req_ratio")lines 165–172return { "req": len(traced), "exempt": len(exempt), "by_tag": dict(sorted(by_tag.items())), "ratio": ratio, "floor": floor, "below_floor": floor is not None and ratio is not None and ratio < floor, }

Requirements

REQ-DDB-GUARD-022

Flows

traceability_line

str clew.guard.coverage.traceability_line(dict[str, Any] trace)

One line stating the requirement ratio, its per-tag counts and the floor.

clew/guard/coverage.py:179

Source · 15 lines
def traceability_line(trace: dict[str, Any]) -> str:
    tags = ", ".join(f"@{t} {n}" for t, n in trace["by_tag"].items()) or "none"
    ratio = "n/a" if trace["ratio"] is None else f"{trace['ratio']:g}"
    if trace["floor"] is None:
        verdict = "no floor declared"
    elif trace["below_floor"]:
        verdict = f"below the floor {trace['floor']:g}"
    else:
        verdict = f"floor {trace['floor']:g} met"
    return (
        f"Traceability: {trace['req']} with @req, {trace['exempt']} exempt ({tags}) — "
        f"ratio {ratio} ({verdict})"
    )

Activity · 9 steps
lines 180–180tags = ", ".join(f"@{t} {n}" for t, n in trace["by_tag"].items()) or "none"lines 181–181ratio = "n/a" if trace["ratio"] is None else f"{trace['ratio']:g}"lines 182–182◇ if trace["floor"] is Nonelines 183–183verdict = "no floor declared"lines 184–184◇ elif trace["below_floor"]lines 185–185verdict = f"below the floor {trace['floor']:g}"lines 186–186elselines 187–187verdict = f"floor {trace['floor']:g} met"lines 188–191return ( f"Traceability: {trace['req']} with @req, {trace['exempt']} exempt ({tags}) — " f"ratio {ratio} ({verdict})" )

Flows