requirements.py

clew/requirements.py

Requirements traceability: requirements.yaml ingestion + `@req` edges.

_catalog_rows

dict[str, dict[str, str]] clew.requirements._catalog_rows(object data)

The rows of a parsed catalogue, in either shape.

clew/requirements.py:1379

Source · 14 lines
def _catalog_rows(data: object) -> dict[str, dict[str, str]]:
    """@brief Rows. @return Mapping."""
    if isinstance(data, dict) and isinstance(data.get("requirements"), dict):
        data = data["requirements"]
    out: dict[str, dict[str, str]] = {}
    if isinstance(data, list):
        for row in data:
            if isinstance(row, dict) and (row.get("id") or row.get("ID")):
                out[str(row.get("id") or row.get("ID"))] = {k: str(v) for k, v in row.items()}
    elif isinstance(data, dict):
        for key, row in data.items():
            if isinstance(row, dict) or row is None:
                out[str(key)] = {k: str(v) for k, v in (row or {}).items()}
    return out

1 more lines, not shown

Activity · 12 steps
lines 1381–1381◇ if isinstance(data, dict) and isinstance(data.get("requirements"), dict)lines 1382–1382data = data["requirements"]lines 1383–1383out: dict[str, dict[str, str]] = {}lines 1384–1384◇ if isinstance(data, list)lines 1385–1385◇ for row in datalines 1386–1386◇ if isinstance(row, dict) and (row.get("id") or row.get("ID"))lines 1387–1387out[str(row.get("id") or row.get("ID"))] = {k: str(v) for k, v in row.items()}lines 1388–1388◇ elif isinstance(data, dict)lines 1389–1389◇ for key, row in data.items()lines 1390–1390◇ if isinstance(row, dict) or row is Nonelines 1391–1391out[str(key)] = {k: str(v) for k, v in (row or {}).items()}lines 1392–1392return out

Flows

_extract_req_tags

list[tuple[str, str]] clew.requirements._extract_req_tags(str|None text, re.Pattern[str] req_id_pattern=_PERMISSIVE_REQ_ID_RE)

Classify each @req tag occurrence into (req_id, confidence).

clew/requirements.py:603

Source · 28 lines
def _extract_req_tags(
    text: str | None,
    req_id_pattern: re.Pattern[str] = _PERMISSIVE_REQ_ID_RE,
) -> list[tuple[str, str]]:
    """Return every `@req <id>` occurrence in `text` whose `<id>`
    token FULLY matches `req_id_pattern` (the target repo's declared pattern,
    or the permissive default).

    The `@req` keyword is matched case-insensitively; the id token is kept
    verbatim so it round-trips against a case-sensitive declared pattern. An id
    is terminated by whitespace, by `<` (a doxygen markup boundary) or by
    end-of-text — see the `_REQ_TAG_TOKEN_RE` comment for the two silent
    failures the `<` terminator fixes.

    @brief Extract declared-pattern @req tags (literal + xrefitem-alias forms).
    @version 7
    """
    if not text:
        return []
    found: list[str] = []
    for match in _REQ_TAG_TOKEN_RE.finditer(text):
        req_id = _matched_req_id(match.group(1), req_id_pattern)
        if req_id:
            found.append(req_id)
    found.extend(_extract_xref_req_tags(text, req_id_pattern))
    return found

Activity · 9 steps
lines 620–620◇ if not textlines 621–621return []lines 622–622found: list[str] = []lines 623–623◇ for match in _REQ_TAG_TOKEN_RE.finditer(text)lines 624–624req_id = _matched_req_id(match.group(1), req_id_pattern)lines 625–625◇ if req_idlines 626–626found.append(req_id)lines 627–627found.extend(_extract_xref_req_tags(text, req_id_pattern))lines 628–628return found

Requirements

REQ-DDB-SCHEMA-006

_extract_xref_req_tags

list[tuple[str, str]] clew.requirements._extract_xref_req_tags(str text, re.Pattern[str] req_id_pattern)

Extract req ids from doxygen blocks (aliased @req).

clew/requirements.py:637

Source · 27 lines
def _extract_xref_req_tags(
    text: str,
    req_id_pattern: re.Pattern[str],
) -> list[tuple[str, str]]:
    """Scan `<xrefdescription>` blocks for tokens matching the declared req id
    pattern — the form doxygen emits when `@req` is an xrefitem alias.

    Confined to xrefdescription content so prose mentions of an id elsewhere
    can't create phantom edges. An `[inferred]` marker inside the block maps
    to confidence 'inferred', else 'stated'.

    @brief Extract @req ids from doxygen xrefdescription blocks.
    @version 4
    """
    found: list[str] = []
    for block in _XREF_DESC_RE.findall(text):
        for token in _ID_TOKEN_RE.findall(block):
            ## Same tolerance as the literal form: an aliased tag rendered into an
            ## xrefdescription ends a sentence just as often as an unaliased one. The
            ## MATCHED id is appended, not the raw token — appending the token would store
            ## `REQ-X.` as the id and break the join to the catalog.
            req_id = _matched_req_id(token, req_id_pattern)
            if req_id:
                found.append(req_id)
    return found

Activity · 7 steps
lines 651–651found: list[str] = []lines 652–652◇ for block in _XREF_DESC_RE.findall(text)lines 653–653◇ for token in _ID_TOKEN_RE.findall(block)lines 658–658req_id = _matched_req_id(token, req_id_pattern)lines 659–659◇ if req_idlines 660–660found.append(req_id)lines 661–661return found

Requirements

REQ-DDB-SCHEMA-006

_insert_failure_modes

None clew.requirements._insert_failure_modes(sqlite3.Connection conn, str req_id, dict entry)

Insert the failure modes one catalog entry declares.

clew/requirements.py:877

Source · 27 lines
def _insert_failure_modes(conn: sqlite3.Connection, req_id: str, entry: dict) -> None:
    """A MALFORMED `failure_modes` IS LOGGED AND SKIPPED here; the gate refuses it (`clew guard`
    reads it through the same `failuremodes.modes_of`). A mode id declared twice keeps the first
    requirement, and the second is named.

    @brief Insert declared modes.
    @return None.
    """
    from .failuremodes import modes_of

    try:
        modes = modes_of(req_id, entry)
    except ValueError as exc:
        logger.warning("requirements: %s — its failure modes are not indexed", exc)
        return
    for mode in modes:
        if not conn.execute(
            "INSERT OR IGNORE INTO failure_modes VALUES (?, ?, ?)",
            (mode.req_id, mode.mode_id, mode.meaning),
        ).rowcount:
            logger.warning(
                "requirements: failure mode %s is declared again by %s; the first is kept",
                mode.mode_id,
                req_id,
            )

Activity · 9 steps
lines 885–885from .failuremodes import modes_oflines 887–887trylines 888–888modes = modes_of(req_id, entry)lines 889–889except ValueError as exclines 890–890logger.warning("requirements: %s — its failure modes are not indexed", exc)lines 891–891returnlines 892–892◇ for mode in modeslines 893–896◇ if not conn.execute(lines 897–901logger.warning( "requirements: failure mode %s is declared again by %s; the first is kept", mode.mode_id, req_id, )

Requirements

REQ-DDB-SCHEMA-006

_insert_req_entry

int clew.requirements._insert_req_entry(sqlite3.Connection conn, dict entry, str id_col, str name_col)

Ingest one requirements entry into the requirements table.

clew/requirements.py:333

Show on the map →

Called by ingest_requirements_yaml

Calls _first, _scalar

Source · 47 lines
def _insert_req_entry(
    conn: sqlite3.Connection,
    entry: dict,
    id_col: str,
    name_col: str,
) -> int:
    """Insert a single flat catalog row, tolerating either the declared or
    the convention id/name keys.

    A KEY NO COLUMN READS IS KEPT, NOT DROPPED (2.0.0, S4): it lands verbatim in `extra` and the
    build log names it, so a catalog field the index does not model is visible rather than
    indistinguishable from one the catalog never had.

    @brief Insert one flat requirements-catalog row.
    @version 3
    """
    rid = entry.get(id_col) or entry.get("id")
    if not rid:
        return 0
    columns = {col: _first(entry, *keys) for col, keys in _COLUMN_KEYS.items()}
    columns["title"] = _first(entry, name_col, *_COLUMN_KEYS["title"])
    read = {
        id_col,
        "id",
        name_col,
        *_READ_ELSEWHERE,
        *(k for keys in _COLUMN_KEYS.values() for k in keys),
    }
    extra = {k: entry[k] for k in sorted(entry) if k not in read}
    if extra:
        logger.info(
            "requirements: %s carries keys no column reads, kept in `extra`: %s",
            rid,
            ", ".join(extra),
        )
    conn.execute(
        f"INSERT OR REPLACE INTO requirements (id, {', '.join(columns)}, extra) "
        f"VALUES (?, {', '.join('?' * len(columns))}, ?)",
        (
            rid,
            *(_scalar(v) for v in columns.values()),
            json.dumps(extra, default=str) if extra else None,
        ),
    )
    return 1

Activity · 11 steps
lines 349–349rid = entry.get(id_col) or entry.get("id")lines 350–350◇ if not ridlines 351–351return 0lines 352–352columns = {col: _first(entry, *keys) for col, keys in _COLUMN_KEYS.items()}lines 353–353columns["title"] = _first(entry, name_col, *_COLUMN_KEYS["title"])lines 354–360read = { id_col, "id", name_col, *_READ_ELSEWHERE, *(k for keys in _COLUMN_KEYS.values() for k in keys), }lines 361–361extra = {k: entry[k] for k in sorted(entry) if k not in read}lines 362–362◇ if extralines 363–367logger.info( "requirements: %s carries keys no column reads, kept in `extra`: %s", rid, ", ".join(extra), )lines 368–376conn.execute( f"INSERT OR REPLACE INTO requirements (id, {', '.join(columns)}, extra) " f"VALUES (?, {', '.join('?' * len(columns))}, ?)", ( rid, *(_scalar(v) for v in columns.values()), json.dumps(extra, default=str) if extra else None, ), )lines 377–377return 1

Requirements

REQ-DDB-CONFIG-003

_is_flat_req_list

bool clew.requirements._is_flat_req_list(object data, str id_col)

Decide whether YAML data is a flat list of id-bearing req mappings.

clew/requirements.py:176

Source · 17 lines
def _is_flat_req_list(data: object, id_col: str) -> bool:
    """Detect the flat `[{id, ...}, ...]` catalog shape.

    Anything else — a nested `{domains: ...}` catalog, a scalar, an
    empty document — is NOT assumed to be ingestible; the caller ingests 0
    catalog rows rather than guessing at the structure.

    @brief Recognise the flat id-bearing requirements-list shape.
    @version 4
    """
    if not isinstance(data, list) or not data:
        return False
    if not all(isinstance(entry, dict) for entry in data):
        return False
    return any((id_col in entry) or ("id" in entry) for entry in data)

Activity · 5 steps
lines 186–186◇ if not isinstance(data, list) or not datalines 187–187return Falselines 188–188◇ if not all(isinstance(entry, dict) for entry in data)lines 189–189return Falselines 190–190return any((id_col in entry) or ("id" in entry) for entry in data)

Requirements

REQ-DDB-CONFIG-003

_keyed_req_entries

list[dict] clew.requirements._keyed_req_entries(object data)

Requirement entries out of a mapping-keyed catalog, ID taken from the key.

clew/requirements.py:441

Source · 30 lines
def _keyed_req_entries(data: object) -> list[dict]:
    """Recognise the MAPPING-KEYED catalog: `{requirements: {REQ-X: {name: ...}}}`.

    doxygen-guard 1.3.1 adopted exactly this shape for its own catalog, and its schema
    says why — `formats_using_id_column` lists only `csv` and `json`, so a YAML catalog
    is keyed by ID and "the structure is self-describing", no `id_column` involved.

    THIS WAS MEASURED BEFORE IT WAS WRITTEN. Against the pinned public integration
    target, a 9,534-byte catalog of 22 requirements ingested ZERO rows, because
    `_is_flat_req_list` recognises only the flat `[{id, ...}, ...]` list. Nothing
    errored; the table was simply empty, which reads identically to a repo that has no
    catalog. That is the third time in this project that "no rows" was a claim about the
    DETECTOR rather than the data — the same shape as the macro-defined accessors and
    the causal layer once recorded as a correct negative.

    The ID comes from the key, so an entry that ALSO carries an id field is not merged:
    the key wins, because it is the thing the format is keyed on.

    @brief Flatten a mapping-keyed requirements catalog into entry dicts.
    @return Entries carrying 'id', or [] when the document is not this shape.
    @version 2
    """
    if not isinstance(data, dict):
        return []
    root = data.get(CATALOG_ROOT_KEY)
    if not isinstance(root, dict) or not root:
        return []
    return [{**value, "id": rid} for rid, value in root.items() if isinstance(value, dict) and rid]

Activity · 6 steps
lines 463–463◇ if not isinstance(data, dict)lines 464–464return []lines 465–465root = data.get(CATALOG_ROOT_KEY)lines 466–466◇ if not isinstance(root, dict) or not rootlines 467–467return []lines 468–468return [{**value, "id": rid} for rid, value in root.items() if isinstance(value, dict) and rid]

Requirements

REQ-DDB-CONFIG-003

_matched_req_id

str clew.requirements._matched_req_id(str token, re.Pattern[str] req_id_pattern)

The req id a captured token denotes, allowing for doxygen's own trailing punctuation.

clew/requirements.py:568

Source · 29 lines
def _matched_req_id(token: str, req_id_pattern: re.Pattern[str]) -> str:
    """GREEDY FIRST, AND THAT ORDER IS THE WHOLE SAFETY ARGUMENT (gh#20). A `@req` that
    follows `@brief` with no blank line continues the brief paragraph, and doxygen appends
    its own period when it closes that paragraph — so the captured token is
    `REQ-PROBE-001.` for a tag the author wrote cleanly, the full match fails, and the edge
    is dropped with no warning anywhere.

    Stripping punctuation unconditionally would be the wrong fix: a target's DECLARED
    pattern may legitimately contain dots (`REQ-1.2.3`), and this extractor's one hard
    guarantee is that every id matching today still matches. Trying the token as captured
    first means a dotted id matches on the first attempt and is never touched.

    ONE CHARACTER, ONCE. `REQ-X...` is prose this should decline, not a tag with three
    periods to peel — peeling until something matches is how a scanner starts inventing
    ids out of surrounding text.

    @brief Match a captured id token, tolerating one trailing sentence character.
    @return The id, or ''.
    @version 1
    """
    if req_id_pattern.match(token):
        return token
    if token[-1:] in _SENTENCE_TAIL:
        trimmed = token[:-1]
        if trimmed and req_id_pattern.match(trimmed):
            return trimmed
    return ""

Activity · 7 steps
lines 588–588◇ if req_id_pattern.match(token)lines 589–589return tokenlines 590–590◇ if token[-1:] in _SENTENCE_TAILlines 591–591trimmed = token[:-1]lines 592–592◇ if trimmed and req_id_pattern.match(trimmed)lines 593–593return trimmedlines 594–594return ""

Requirements

REQ-DDB-SCHEMA-006

_refuse_url

None clew.requirements._refuse_url(str text)

Refuse a source that is a URL.

clew/requirements.py:1365

Source · 9 lines
def _refuse_url(text: str) -> None:
    """@brief URL check. @return None."""
    if _URLISH.match(text.strip()):
        raise ValueError(
            f"{text!r} is a URL: a catalogue is read from a local path or a local clone pinned "
            "by revision, never fetched"
        )

Activity · 2 steps
lines 1367–1367◇ if _URLISH.match(text.strip())lines 1368–1371raise ValueError( f"{text!r} is a URL: a catalogue is read from a local path or a local clone pinned " "by revision, never fetched" )

Flows

catalog_value

object clew.requirements.catalog_value(dict entry, str column)

A catalogue entry's value for one column, through that column's aliases.

clew/requirements.py:400

Show on the map →

Called by _ears_line, _shows

Calls none

Source · 10 lines
def catalog_value(entry: dict, column: str) -> object:
    """ONE READING of a catalogue field, so the wiki's S4 checklist and the index's
    `requirements` table cannot disagree about whether an entry carries one.

    @brief Aliased catalogue lookup.
    @return Value or "".
    """
    return next((entry[k] for k in _COLUMN_KEYS[column] if entry.get(k)), "")

Activity · 1 steps
lines 407–407return next((entry[k] for k in _COLUMN_KEYS[column] if entry.get(k)), "")

Requirements

REQ-DDB-WIKI-022

Flows

declared_catalog_path

Path | None clew.requirements.declared_catalog_path(dict|None guard_cfg, Path repo_root)

The catalog path a repo DECLARES, when it declares one.

clew/requirements.py:1154

Source · 38 lines
def declared_catalog_path(guard_cfg: dict | None, repo_root: Path) -> Path | None:
    """Honour `impact.requirements.file`, which the GATE already reads.

    doxygen-guard issue #7: "clew ignores `impact.requirements.file` and `.format`
    entirely, so a repo that declares where its catalog lives has that declaration honoured
    by the gate and ignored by the index." Measured true — the CLI took `--requirements` or
    nothing, so a repo that had said exactly where its catalog is still had to say it AGAIN
    on the command line, and through the MCP server (which passes no such flag) the
    declaration could never be honoured at all. That is the same argv-only hole
    `.clew.yaml` was created to close, left open on this one field.

    An explicit `--requirements` still WINS. The precedence is the repo's universal rule:
    CLI flag > declaration > nothing.

    Returns None rather than raising when the declared file is missing. A catalog is
    OPTIONAL metadata — `req_edges` populate from tags regardless — so a stale path should
    degrade to "no catalog" with a warning, not fail a build that has already run doxygen.

    @brief Resolve the declared requirements-catalog path, if any.
    @return Path when declared and present, else None.
    @version 2
    """
    declared = _declared_catalog_field(guard_cfg)
    if not declared:
        return None
    path = (repo_root / str(declared)).resolve()
    if not path.exists():
        logger.warning(
            "requirements: .clew.yaml declares requirements.file=%s but %s "
            "does not exist — ingesting no catalog; @req edges still populate from tags",
            declared,
            path,
        )
        return None
    logger.info("requirements: using DECLARED catalog requirements.file=%s", declared)
    return path

Activity · 9 steps
lines 1176–1176declared = _declared_catalog_field(guard_cfg)lines 1177–1177◇ if not declaredlines 1178–1178return Nonelines 1179–1179path = (repo_root / str(declared)).resolve()lines 1180–1180◇ if not path.exists()lines 1181–1186logger.warning( "requirements: .clew.yaml declares requirements.file=%s but %s " "does not exist — ingesting no catalog; @req edges still populate from tags", declared, path, )lines 1187–1187return Nonelines 1188–1188logger.info("requirements: using DECLARED catalog requirements.file=%s", declared)lines 1189–1189return path

Requirements

REQ-DDB-SCHEMA-006

git_text

str | None clew.requirements.git_text(Path cwd, *str args)

Run git in a local checkout through the hardened environment.

clew/requirements.py:1295

Source · 19 lines
def git_text(cwd: Path, *args: str) -> str | None:
    """THE HARDENED ENVIRONMENT (`gitenv.git_argv`): a checkout's own config is data, never code.

    @brief Run git.
    @return Output or None.
    """
    import subprocess

    from .gitenv import git_argv

    try:
        out = subprocess.run(
            git_argv(*args), cwd=cwd, capture_output=True, text=True, check=False, timeout=30
        )
    except (OSError, subprocess.TimeoutExpired):
        return None
    return out.stdout if out.returncode == 0 else None

Activity · 7 steps
lines 1301–1301import subprocesslines 1303–1303from .gitenv import git_argvlines 1305–1305trylines 1306–1308out = subprocess.run( git_argv(*args), cwd=cwd, capture_output=True, text=True, check=False, timeout=30 )lines 1309–1309except (OSError, subprocess.TimeoutExpired)lines 1310–1310return Nonelines 1311–1311return out.stdout if out.returncode == 0 else None

Requirements

REQ-DDB-GUARD-027

Flows

import_req_edges

None clew.requirements.import_req_edges(Path db_path, re.Pattern[str]|None req_id_pattern=None)

Parse requirement-reference doxygen tags out of function descriptions.

clew/requirements.py:756

Source · 47 lines
def import_req_edges(
    db_path: Path,
    req_id_pattern: re.Pattern[str] | None = None,
) -> None:
    """Scan every function memberdef's brief/detailed description for `@req`
    tags whose id matches the target repo's DECLARED pattern (or the
    permissive fallback) and populate req_edges.

    A tag is simply an id — there is no confidence grading. That distinction was
    retired 2026-07-30: a requirement either has an implementer or it does not, and
    grading an author's confidence in their own tag added a second axis nobody read.
    Whether a requirement HAS an implementer is UNCHECKED — the pre-commit coverage
    audit that checked it is DELETED. This runs REGARDLESS of whether the
    requirements catalog parsed — tag edges are the authoritative traceability.

    @brief Import declared-pattern @req doxygen-tag edges into req_edges.
    @version 5
    """
    pattern = req_id_pattern or _PERMISSIVE_REQ_ID_RE
    conn = sqlite3.connect(str(db_path))
    conn.row_factory = sqlite3.Row
    _create_req_edges_table(conn)

    rows = conn.execute(
        """
        SELECT rowid, briefdescription, detaileddescription
        FROM memberdef
        WHERE kind = 'function'
        """,
    ).fetchall()

    imported = 0
    for row in rows:
        tags = _extract_req_tags(row["briefdescription"], pattern) + _extract_req_tags(
            row["detaileddescription"],
            pattern,
        )
        for req_id in tags:
            imported += conn.execute(
                "INSERT OR IGNORE INTO req_edges (req_id, memberdef_rowid) VALUES (?, ?)",
                (req_id, row["rowid"]),
            ).rowcount
    conn.commit()
    conn.close()
    logger.info("req_edges: imported %d @req tag edges", imported)

Activity · 13 steps
lines 774–774pattern = req_id_pattern or _PERMISSIVE_REQ_ID_RElines 775–775conn = sqlite3.connect(str(db_path))lines 776–776conn.row_factory = sqlite3.Rowlines 777–777_create_req_edges_table(conn)lines 779–785rows = conn.execute( """ SELECT rowid, briefdescription, detaileddescription FROM memberdef WHERE kind = 'function' """, ).fetchall()lines 787–787imported = 0lines 788–788◇ for row in rowslines 789–792tags = _extract_req_tags(row["briefdescription"], pattern) + _extract_req_tags( row["detaileddescription"], pattern, )lines 793–793◇ for req_id in tagslines 794–797imported += conn.execute( "INSERT OR IGNORE INTO req_edges (req_id, memberdef_rowid) VALUES (?, ?)", (req_id, row["rowid"]), ).rowcountlines 798–798conn.commit()lines 799–799conn.close()lines 800–800logger.info("req_edges: imported %d @req tag edges", imported)

Requirements

REQ-DDB-SCHEMA-006

import_req_test_edges

None clew.requirements.import_req_test_edges(Path db_path, tuple[str,...]|None test_patterns=None, Path|None repo_root=None)

Materialize the test-function subset of req_edges into req_test_edges.

clew/requirements.py:978

Source · 64 lines
def import_req_test_edges(
    db_path: Path, test_patterns: tuple[str, ...] | None = None, repo_root: Path | None = None
) -> None:
    """Link test functions to requirements via req_edges → req_test_edges.

    For every req_edges row whose memberdef matches `_looks_like_test_function`,
    insert a (req_id, test_memberdef_rowid) row. This lets lookup_requirement
    cheaply distinguish "implementing functions" from "covering tests"
    without re-deriving the test-name heuristic at query time.

    @brief Materialize test-covering req_edges rows into req_test_edges.
    @version 2
    """
    conn = sqlite3.connect(str(db_path))
    conn.row_factory = sqlite3.Row
    _create_req_test_edges_table(conn)

    if not _table_exists(conn, "req_edges"):
        conn.close()
        logger.info("req_test_edges: req_edges table absent — skipping")
        return

    ## THE BODY'S FILE DECIDES (2.1, found on entropic measuring clew#74): `file_id` is where a
    ## function is DECLARED, so a production function re-declared in a test file read as a test
    ## — 34 of 39 rows there — and dropped out of its requirement's implementers.
    columns = {r[1] for r in conn.execute("PRAGMA table_info(memberdef)")}
    where = (
        "COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id)" if "bodyfile_id" in columns else "m.file_id"
    )
    rows = conn.execute(
        f"""
        SELECT re.req_id, re.memberdef_rowid, m.name, p.name AS file_path
        FROM req_edges re
        JOIN memberdef m ON m.rowid = re.memberdef_rowid
        LEFT JOIN path p ON p.rowid = {where}
        """,
    ).fetchall()

    imported = 0
    for row in rows:
        if test_patterns is not None:
            from .testscope import is_test_path

            if not is_test_path(str(row["file_path"] or ""), test_patterns):
                continue
        elif not _looks_like_test_function(row["name"], row["file_path"]):
            continue
        imported += conn.execute(
            """
            INSERT OR IGNORE INTO req_test_edges (req_id, test_memberdef_rowid)
            VALUES (?, ?)
            """,
            (row["req_id"], row["memberdef_rowid"]),
        ).rowcount
    cases = _link_catch2_cases(conn, repo_root, test_patterns) if repo_root is not None else 0
    conn.commit()
    conn.close()
    logger.info(
        "req_test_edges: imported %d test-coverage edges (%d from Catch2 cases)",
        imported + cases,
        cases,
    )

Activity · 23 steps
lines 991–991conn = sqlite3.connect(str(db_path))lines 992–992conn.row_factory = sqlite3.Rowlines 993–993_create_req_test_edges_table(conn)lines 995–995◇ if not _table_exists(conn, "req_edges")lines 996–996conn.close()lines 997–997logger.info("req_test_edges: req_edges table absent — skipping")lines 998–998returnlines 1003–1003columns = {r[1] for r in conn.execute("PRAGMA table_info(memberdef)")}lines 1004–1006where = ( "COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id)" if "bodyfile_id" in columns else "m.file_id" )lines 1007–1014rows = conn.execute( f""" SELECT re.req_id, re.memberdef_rowid, m.name, p.name AS file_path FROM req_edges re JOIN memberdef m ON m.rowid = re.memberdef_rowid LEFT JOIN path p ON p.rowid = {where} """, ).fetchall()lines 1016–1016imported = 0lines 1017–1017◇ for row in rowslines 1018–1018◇ if test_patterns is not Nonelines 1019–1019from .testscope import is_test_pathlines 1021–1021◇ if not is_test_path(str(row["file_path"] or ""), test_patterns)lines 1022–1022continuelines 1023–1023◇ elif not _looks_like_test_function(row["name"], row["file_path"])lines 1024–1024continuelines 1025–1031imported += conn.execute( """ INSERT OR IGNORE INTO req_test_edges (req_id, test_memberdef_rowid) VALUES (?, ?) """, (row["req_id"], row["memberdef_rowid"]), ).rowcountlines 1032–1032cases = _link_catch2_cases(conn, repo_root, test_patterns) if repo_root is not None else 0lines 1033–1033conn.commit()lines 1034–1034conn.close()lines 1035–1039logger.info( "req_test_edges: imported %d test-coverage edges (%d from Catch2 cases)", imported + cases, cases, )

Requirements

REQ-DDB-SCHEMA-006

import_test_failure_modes

None clew.requirements.import_test_failure_modes(Path db_path, tuple[str,...]|None test_patterns=None, Path|None repo_root=None)

Link tests in test code to the declared failure modes they name with @fails_when .

clew/requirements.py:911

Show on the map →

Called by _build_stages, run_real_stages

Calls _is_test_file, _source_lines, _table_exists, fails_when_ids, list, read_case

Source · 57 lines
def import_test_failure_modes(
    db_path: Path, test_patterns: tuple[str, ...] | None = None, repo_root: Path | None = None
) -> None:
    """2.2 (the test flowchart's fail branches). A test function names a mode in its doc text; a
    Catch2 case, which has no doc text of its own, in the comment block directly above it. Only an
    id the catalog declares links; any other is counted and logged, never linked. Created on every
    build, so an absent table means an index from before the layer.

    @brief Import test → failure-mode links.
    @return None.
    """
    from .catch2 import CASE_MACROS, read_case
    from .failuremodes import fails_when_ids

    conn = sqlite3.connect(str(db_path))
    conn.execute("DROP TABLE IF EXISTS test_failure_modes")
    conn.execute(
        "CREATE TABLE test_failure_modes (mode_id TEXT NOT NULL, "
        "test_memberdef_rowid INTEGER NOT NULL REFERENCES memberdef(rowid), test_name TEXT NOT NULL, "
        "UNIQUE(mode_id, test_memberdef_rowid))"
    )
    declared = (
        {r[0] for r in conn.execute("SELECT mode_id FROM failure_modes")}
        if _table_exists(conn, "failure_modes")
        else set()
    )
    rows = conn.execute(
        "SELECT m.rowid, m.name, m.line, COALESCE(m.briefdescription, ''), "
        "COALESCE(m.detaileddescription, ''), p.name FROM memberdef m "
        "JOIN path p ON p.rowid = COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) "
        "WHERE m.kind = 'function'"
    ).fetchall()
    lines_of: dict[str, list[str]] = {}
    links: list[tuple[str, int, str]] = []
    for rowid, name, line, brief, detail, file_path in rows:
        if not _is_test_file(str(file_path), test_patterns):
            continue
        ids, label = fails_when_ids(f"{brief} {detail}"), str(name)
        if name in CASE_MACROS and repo_root is not None:
            if file_path not in lines_of:
                lines_of[file_path] = _source_lines(repo_root / str(file_path))
            case = read_case(lines_of[file_path], int(line or 0))
            ids, label = (list(case.fails_when), case.title) if case else (ids, label)
        links += [(mode, int(rowid), label) for mode in dict.fromkeys(ids)]
    known = [link for link in links if link[0] in declared]
    conn.executemany("INSERT OR IGNORE INTO test_failure_modes VALUES (?, ?, ?)", known)
    conn.commit()
    conn.close()
    if len(known) < len(links):
        logger.warning(
            "test_failure_modes: %d @fails_when reference(s) name no declared failure mode; "
            "not linked",
            len(links) - len(known),
        )
    logger.info("test_failure_modes: %d test → failure-mode link(s)", len(known))

Activity · 26 steps
lines 922–922from .catch2 import CASE_MACROS, read_caselines 923–923from .failuremodes import fails_when_idslines 925–925conn = sqlite3.connect(str(db_path))lines 926–926conn.execute("DROP TABLE IF EXISTS test_failure_modes")lines 927–931conn.execute( "CREATE TABLE test_failure_modes (mode_id TEXT NOT NULL, " "test_memberdef_rowid INTEGER NOT NULL REFERENCES memberdef(rowid), test_name TEXT NOT NULL, " "UNIQUE(mode_id, test_memberdef_rowid))" )lines 932–936declared = ( {r[0] for r in conn.execute("SELECT mode_id FROM failure_modes")} if _table_exists(conn, "failure_modes") else set() )lines 937–942rows = conn.execute( "SELECT m.rowid, m.name, m.line, COALESCE(m.briefdescription, ''), " "COALESCE(m.detaileddescription, ''), p.name FROM memberdef m " "JOIN path p ON p.rowid = COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) " "WHERE m.kind = 'function'" ).fetchall()lines 943–943lines_of: dict[str, list[str]] = {}lines 944–944links: list[tuple[str, int, str]] = []lines 945–945◇ for rowid, name, line, brief, detail, file_path in rowslines 946–946◇ if not _is_test_file(str(file_path), test_patterns)lines 947–947continuelines 948–948ids, label = fails_when_ids(f"{brief} {detail}"), str(name)lines 949–949◇ if name in CASE_MACROS and repo_root is not Nonelines 950–950◇ if file_path not in lines_oflines 951–951lines_of[file_path] = _source_lines(repo_root / str(file_path))lines 952–952case = read_case(lines_of[file_path], int(line or 0))lines 953–953ids, label = (list(case.fails_when), case.title) if case else (ids, label)lines 954–954links += [(mode, int(rowid), label) for mode in dict.fromkeys(ids)]lines 955–955known = [link for link in links if link[0] in declared]lines 956–956conn.executemany("INSERT OR IGNORE INTO test_failure_modes VALUES (?, ?, ?)", known)lines 957–957conn.commit()lines 958–958conn.close()lines 959–959◇ if len(known) < len(links)lines 960–964logger.warning( "test_failure_modes: %d @fails_when reference(s) name no declared failure mode; " "not linked", len(links) - len(known), )lines 965–965logger.info("test_failure_modes: %d test → failure-mode link(s)", len(known))

Requirements

REQ-DDB-SCHEMA-006

ingest_requirements_yaml

None clew.requirements.ingest_requirements_yaml(Path db_path, Path|None requirements_yaml, dict|None guard_cfg=None)

Load a target repo's requirements.yaml into the requirements table.

clew/requirements.py:481

Source · 75 lines
def ingest_requirements_yaml(
    db_path: Path,
    requirements_yaml: Path | None,
    guard_cfg: dict | None = None,
) -> None:
    """Populate the `requirements` table from an OPTIONAL, format-tolerant
    requirements catalog.

    There is NO universal requirements.yaml format, so TWO declared shapes are read and
    nothing else is guessed:

      * the flat `[{id, ...}, ...]` list — CSV semantics in YAML syntax, keyed by the
        declared `impact.requirements.{id_column,name_column}` mapping when the guard
        config provides one, else the `{id, title, block, acceptance, priority}`
        convention;
      * the MAPPING-KEYED `{requirements: {REQ-X: {name: ...}}}` catalog, which is what
        doxygen-guard 1.3.1 itself now ships and what its schema implies by listing only
        csv/json under `formats_using_id_column`.

    Any other shape (e.g. a nested `domains:` catalog parsed only by that repo's own
    scripts) is logged and yields 0 catalog rows.

    The table is always created (possibly empty) so downstream `_has_table`-
    gated queries rely on a stable schema. An empty catalog is legitimate:
    `req_edges` (from `@req` tags) are the authoritative traceability, and
    LEFT JOINs to `requirements` already tolerate missing rows.

    @brief Ingest a flat or mapping-keyed requirements catalog; tolerate unknown shapes.
    @version 5
    """
    conn = sqlite3.connect(str(db_path))
    _create_requirements_table(conn)
    _create_links_table(conn)
    _create_failure_modes_table(conn)
    if requirements_yaml is None or not requirements_yaml.exists():
        conn.close()
        logger.info("requirements: no requirements.yaml found — table empty")
        return

    import yaml

    data = yaml.safe_load(requirements_yaml.read_text(encoding="utf-8"))
    id_col, name_col = resolve_catalog_columns(guard_cfg)

    entries = data if _is_flat_req_list(data, id_col) else _keyed_req_entries(data)
    if not entries:
        conn.close()
        logger.info(
            "requirements: %s is neither a flat id-bearing list nor a `%s:` mapping "
            "keyed by requirement id (nested or unrecognized catalog shape) — ingesting "
            "0 catalog rows; @req req_edges remain the authoritative traceability",
            requirements_yaml,
            CATALOG_ROOT_KEY,
        )
        return

    imported = 0
    for entry in entries:
        imported += _insert_req_entry(conn, entry, id_col, name_col)
        rid = entry.get(id_col) or entry.get("id")
        if rid:
            conn.executemany(
                "INSERT OR IGNORE INTO requirement_links (req_id, satisfies) VALUES (?, ?)",
                [(str(rid), target) for target in link_ids(entry)],
            )
            _insert_failure_modes(conn, str(rid), entry)
    conn.commit()
    conn.close()
    logger.info(
        "requirements: ingested %d requirements from %s",
        imported,
        requirements_yaml,
    )

Activity · 26 steps
lines 511–511conn = sqlite3.connect(str(db_path))lines 512–512_create_requirements_table(conn)lines 513–513_create_links_table(conn)lines 514–514_create_failure_modes_table(conn)lines 515–515◇ if requirements_yaml is None or not requirements_yaml.exists()lines 516–516conn.close()lines 517–517logger.info("requirements: no requirements.yaml found — table empty")lines 518–518returnlines 520–520import yamllines 522–522data = yaml.safe_load(requirements_yaml.read_text(encoding="utf-8"))lines 523–523id_col, name_col = resolve_catalog_columns(guard_cfg)lines 525–525entries = data if _is_flat_req_list(data, id_col) else _keyed_req_entries(data)lines 526–526◇ if not entrieslines 527–527conn.close()lines 528–534logger.info( "requirements: %s is neither a flat id-bearing list nor a `%s:` mapping " "keyed by requirement id (nested or unrecognized catalog shape) — ingesting " "0 catalog rows; @req req_edges remain the authoritative traceability", requirements_yaml, CATALOG_ROOT_KEY, )lines 535–535returnlines 537–537imported = 0lines 538–538◇ for entry in entrieslines 539–539imported += _insert_req_entry(conn, entry, id_col, name_col)lines 540–540rid = entry.get(id_col) or entry.get("id")lines 541–541◇ if ridlines 542–545conn.executemany( "INSERT OR IGNORE INTO requirement_links (req_id, satisfies) VALUES (?, ?)", [(str(rid), target) for target in link_ids(entry)], )lines 546–546_insert_failure_modes(conn, str(rid), entry)lines 547–547conn.commit()lines 548–548conn.close()lines 549–553logger.info( "requirements: ingested %d requirements from %s", imported, requirements_yaml, )

Requirements

REQ-DDB-SCHEMA-006 REQ-DDB-SCHEMA-015

load_guard_config

dict | None clew.requirements.load_guard_config(Path|str repo_root)

Load a target repo's gate config: the guard: section of its .clew.yaml .

clew/requirements.py:102

Source · 15 lines
def load_guard_config(repo_root: Path | str) -> dict | None:
    """Single source of the config load so both the `@req` pattern resolution
    and the catalog column mapping read from ONE parsed dict. Returns None
    (not an error) when there is nothing declared — every declaration-driven
    lookup then falls back to its permissive built-in default. An invalid section
    is reported by `guardconfig.read_guard_config` and also returns None.

    @brief Load the target repo's declared gate config.
    """
    from .guardconfig import read_guard_config

    read = read_guard_config(repo_root)
    return read.config if read.usable() else None

Activity · 3 steps
lines 111–111from .guardconfig import read_guard_configlines 113–113read = read_guard_config(repo_root)lines 114–114return read.config if read.usable() else None

Requirements

REQ-DDB-CONFIG-001

read_catalog_at

dict[str, dict[str, str]] clew.requirements.read_catalog_at(Path|str repo_root, str|dict source)

Read a requirements catalogue from a local path or a pinned revision of a local checkout.

clew/requirements.py:1320

Source · 40 lines
def read_catalog_at(repo_root: Path | str, source: str | dict) -> dict[str, dict[str, str]]:
    """ONE READER for the gate's external catalogues and the wiki's pinned sub-catalogues (GH #68).

    A URL is REFUSED BY NAME (owner 2026-11-16): reading one would make a pre-commit gate depend
    on the network. A pinned source is read with `git show <rev>:<path>` from a LOCAL clone or
    submodule, so it is the catalogue as it was at that revision, not as the working tree has it.
    Both shapes are read — the `requirements:`-keyed mapping and the flat list of rows — and
    anything else raises rather than yielding an empty catalogue that would pass every tag.

    @brief Read a catalogue.
    @return Rows by id.
    """
    import yaml

    root = Path(repo_root)
    if isinstance(source, dict):
        missing = [k for k in ("repo", "rev", "path") if not source.get(k)]
        if missing:
            raise ValueError(f"a pinned catalogue needs repo, rev and path (missing: {missing})")
        _refuse_url(str(source["repo"]))
        text = git_text(root / str(source["repo"]), "show", f"{source['rev']}:{source['path']}")
        where = f"{source['repo']}@{source['rev']}:{source['path']}"
        if text is None:
            raise ValueError(f"catalogue {where} is not readable at that revision")
    else:
        _refuse_url(str(source))
        where = str(source)
        try:
            text = (root / where).read_text(encoding="utf-8")
        except OSError as exc:
            raise ValueError(f"catalogue {where} is not readable: {exc.strerror}") from exc
    try:
        rows = _catalog_rows(yaml.safe_load(text))
    except yaml.YAMLError as exc:
        raise ValueError(f"catalogue {where} is not YAML") from exc
    if not rows:
        raise ValueError(f"catalogue {where} holds no requirement rows")
    return rows

Activity · 25 steps
lines 1332–1332import yamllines 1334–1334root = Path(repo_root)lines 1335–1335◇ if isinstance(source, dict)lines 1336–1336missing = [k for k in ("repo", "rev", "path") if not source.get(k)]lines 1337–1337◇ if missinglines 1338–1338raise ValueError(f"a pinned catalogue needs repo, rev and path (missing: {missing})")lines 1339–1339_refuse_url(str(source["repo"]))lines 1340–1340text = git_text(root / str(source["repo"]), "show", f"{source['rev']}:{source['path']}")lines 1341–1341where = f"{source['repo']}@{source['rev']}:{source['path']}"lines 1342–1342◇ if text is Nonelines 1343–1343raise ValueError(f"catalogue {where} is not readable at that revision")lines 1344–1344elselines 1345–1345_refuse_url(str(source))lines 1346–1346where = str(source)lines 1347–1347trylines 1348–1348text = (root / where).read_text(encoding="utf-8")lines 1349–1349except OSError as exclines 1350–1350raise ValueError(f"catalogue {where} is not readable: {exc.strerror}") from exclines 1351–1351trylines 1352–1352rows = _catalog_rows(yaml.safe_load(text))lines 1353–1353except yaml.YAMLError as exclines 1354–1354raise ValueError(f"catalogue {where} is not YAML") from exclines 1355–1355◇ if not rowslines 1356–1356raise ValueError(f"catalogue {where} holds no requirement rows")lines 1357–1357return rows

Requirements

REQ-DDB-GUARD-027

Flows

redefined_clew_tags

dict[str, str] clew.requirements.redefined_clew_tags(Path doxyfile)

The Doxyfile aliases that redefine one of clew's own tags.

clew/requirements.py:705

Source · 20 lines
def redefined_clew_tags(doxyfile: Path) -> dict[str, str]:
    """#72 bug 2 (an adopter, 2026-11-23). An unreadable or synthesised Doxyfile is a correct
    negative, as in `event_edges.classify_aliases`.

    @brief Redefined clew tags.
    @return Map.
    """
    try:
        text = Path(doxyfile).read_text(encoding="utf-8", errors="replace")
    except OSError:
        return {}
    found: dict[str, str] = {}
    for assignment in _ALIASES_LINE.findall(text):
        for quoted, bare in _ALIAS_ENTRY.findall(assignment.replace("\\\n", " ")):
            name, _eq, definition = (quoted or bare).partition("=")
            if _eq and name.strip() in CLEW_TAGS:
                found[name.strip()] = definition.replace('\\"', '"')
    return found

Activity · 11 steps
lines 712–712trylines 713–713text = Path(doxyfile).read_text(encoding="utf-8", errors="replace")lines 714–714except OSErrorlines 715–715return {}lines 716–716found: dict[str, str] = {}lines 717–717◇ for assignment in _ALIASES_LINE.findall(text)lines 718–718◇ for quoted, bare in _ALIAS_ENTRY.findall(assignment.replace("\\\n", " "))lines 719–719name, _eq, definition = (quoted or bare).partition("=")lines 720–720◇ if _eq and name.strip() in CLEW_TAGSlines 721–721found[name.strip()] = definition.replace('\\"', '"')lines 722–722return found

Requirements

REQ-DDB-SCHEMA-006

resolve_catalog_columns

tuple[str, str] clew.requirements.resolve_catalog_columns(dict|None guard_cfg)

Resolve the DECLARED requirements-catalog id/name column names.

clew/requirements.py:148

Source · 22 lines
def resolve_catalog_columns(guard_cfg: dict | None) -> tuple[str, str]:
    """Return the id/name column keys for a flat requirements catalog.

    Reads `requirements.{id_column,name_column}` (the top-level section, which the gate reads
    too); otherwise the ONE default pair both readers share (R5-CFG F8).

    @brief Resolve declared catalog id/name columns (id/name default).
    @version 5
    """
    from .guard import config as dg_config

    id_col, name_col = (
        dg_config.REQUIREMENTS_ID_COLUMN_DEFAULT,
        dg_config.REQUIREMENTS_NAME_COLUMN_DEFAULT,
    )
    if guard_cfg:
        req = dg_config.get_requirements(guard_cfg)
        id_col = req.get("id_column", id_col)
        name_col = req.get("name_column", name_col)
    return id_col, name_col

Activity · 7 steps
lines 157–157from .guard import config as dg_configlines 159–162id_col, name_col = ( dg_config.REQUIREMENTS_ID_COLUMN_DEFAULT, dg_config.REQUIREMENTS_NAME_COLUMN_DEFAULT, )lines 163–163◇ if guard_cfglines 164–164req = dg_config.get_requirements(guard_cfg)lines 165–165id_col = req.get("id_column", id_col)lines 166–166name_col = req.get("name_column", name_col)lines 167–167return id_col, name_col

Requirements

REQ-DDB-CONFIG-001

resolve_catalog_path

Path | None clew.requirements.resolve_catalog_path(dict|None guard_cfg, Path repo_root)

The catalog path to ingest: declared first, then the conventional filename.

clew/requirements.py:1214

Source · 48 lines
def resolve_catalog_path(guard_cfg: dict | None, repo_root: Path) -> Path | None:
    """ONE RESOLVER, BECAUSE THERE WERE TWO AND THEY DISAGREED. `cli` resolved
    `--requirements or declared_catalog_path(...)` and never looked for the conventional
    file; the MCP server COMPOSED `repo/"requirements.yaml"` and passed it AS the flag — so
    through MCP the convention outranked the declaration, and through the CLI it did not
    exist at all. A repo with a root `requirements.yaml` AND a declared catalog elsewhere got
    a different catalog depending on which door the build came through, with no warning and
    two plausible-looking indexes.

    PRECEDENCE IS THE REPO'S UNIVERSAL RULE, extended by one step: explicit flag >
    declaration > convention > nothing. The flag stays above the declaration because someone
    typing a path means it; the convention goes BELOW because a file that merely happens to
    sit at the root is the weakest possible statement of intent — and `declared > whole repo`
    is the same precedence gh#333 settled for scope.

    The convention is kept rather than dropped: this repository, and most that adopt
    requirements traceability, put the catalog at the root and declare nothing. Deleting the
    composition without moving the discovery here would have silently stopped ingesting
    those catalogs — the `@req` edges would still populate from tags, so nothing would fail;
    the metadata would just quietly go missing.

    @brief Resolve the catalog path by declaration, then by convention.
    @return Catalog path, or None.
    @version 2
    """
    declared = declared_catalog_path(guard_cfg, repo_root)
    if declared is not None:
        return declared
    found = [rel for rel in _CONVENTIONAL_CATALOGS if (repo_root / rel).is_file()]
    if not found:
        return None
    ## NAMES THE LOSERS WHEN THERE ARE ANY. A silent pick is only safe when the caller can tell
    ## a pick was made, which is the rule `lookup_class` follows for compounds and `dossier` for
    ## overloads. Two conventional catalogs is a repository saying two different things, and the
    ## remedy — declare `impact.requirements.file` — is the one that makes the answer stable.
    if len(found) > 1:
        logger.warning(
            "requirements: %d conventional catalogs exist (%s) — using %s. Declare "
            "requirements.file to choose deliberately.",
            len(found),
            ", ".join(found),
            found[0],
        )
    else:
        logger.info("requirements: using CONVENTIONAL catalog %s", found[0])
    return repo_root / found[0]

Activity · 11 steps
lines 1239–1239declared = declared_catalog_path(guard_cfg, repo_root)lines 1240–1240◇ if declared is not Nonelines 1241–1241return declaredlines 1242–1242found = [rel for rel in _CONVENTIONAL_CATALOGS if (repo_root / rel).is_file()]lines 1243–1243◇ if not foundlines 1244–1244return Nonelines 1249–1249◇ if len(found) > 1lines 1250–1256logger.warning( "requirements: %d conventional catalogs exist (%s) — using %s. Declare " "requirements.file to choose deliberately.", len(found), ", ".join(found), found[0], )lines 1257–1257elselines 1258–1258logger.info("requirements: using CONVENTIONAL catalog %s", found[0])lines 1259–1259return repo_root / found[0]

Requirements

REQ-DDB-SCHEMA-006

resolve_req_id_pattern

re.Pattern[str] clew.requirements.resolve_req_id_pattern(dict|None guard_cfg)

Resolve the target repo's DECLARED @req id pattern (or fallback).

clew/requirements.py:122

Source · 20 lines
def resolve_req_id_pattern(guard_cfg: dict | None) -> re.Pattern[str]:
    """Return the compiled `validate.tags.req.pattern` from the guard config.

    When no config or no declared pattern is present, fall back to the
    PERMISSIVE default — never to a hardcoded per-repo format.

    @brief Resolve the declared @req id pattern (permissive fallback).
    @version 3
    """
    if guard_cfg:
        from .guard import config as dg_config

        validate = dg_config.get_validate(guard_cfg)
        declared = (validate.get("tags", {}).get("req", {}) or {}).get("pattern")
        if declared:
            logger.info("requirements: using declared @req id pattern %r", declared)
            return re.compile(declared)
    return _PERMISSIVE_REQ_ID_RE

Activity · 8 steps
lines 131–131◇ if guard_cfglines 132–132from .guard import config as dg_configlines 134–134validate = dg_config.get_validate(guard_cfg)lines 135–135declared = (validate.get("tags", {}).get("req", {}) or {}).get("pattern")lines 136–136◇ if declaredlines 137–137logger.info("requirements: using declared @req id pattern %r", declared)lines 138–138return re.compile(declared)lines 139–139return _PERMISSIVE_REQ_ID_RE

Requirements

REQ-DDB-CONFIG-001

satisfies_ids

list[str] clew.requirements.satisfies_ids(object value)

The requirement ids a satisfies value names, in every spelling a catalogue uses.

clew/requirements.py:253

Source · 16 lines
def satisfies_ids(value: object) -> list[str]:
    """ONE NORMALISER for the index and the gate, so they never disagree about what an entry
    links to.

    @brief Normalise satisfies.
    @return Ids.
    """
    items = value if isinstance(value, list) else [value] if value else []
    out: list[str] = []
    for item in items:
        for tok in _LINK_TOKEN.findall(str(item)):
            if tok not in out:
                out.append(tok)
    return out

Activity · 7 steps
lines 260–260items = value if isinstance(value, list) else [value] if value else []lines 261–261out: list[str] = []lines 262–262◇ for item in itemslines 263–263◇ for tok in _LINK_TOKEN.findall(str(item))lines 264–264◇ if tok not in outlines 265–265out.append(tok)lines 266–266return out

Requirements

REQ-DDB-SCHEMA-015

Flows

warn_redefined_tags

None clew.requirements.warn_redefined_tags(Path doxyfile)

Warn, naming the alias, when the Doxyfile redefines one of clew's tags.

clew/requirements.py:730

Source · 20 lines
def warn_redefined_tags(doxyfile: Path) -> None:
    """SAID, NEVER SILENT: the adopter's index reported `req_edges: 0` with 196 ids tagged, and every
    requirement read MISSING with no reason given.

    @brief Warn on redefined tags.
    @return None.
    """
    for tag, definition in redefined_clew_tags(doxyfile).items():
        logger.warning(
            "%s defines ALIASES `%s=%s`: doxygen rewrites every @%s before clew reads it, so no "
            "%s is taken from those tags. Remove that alias; clew reads @%s itself.",
            doxyfile,
            tag,
            definition,
            tag,
            "requirement edge" if tag == "req" else "exemption",
            tag,
        )

Activity · 2 steps
lines 737–737◇ for tag, definition in redefined_clew_tags(doxyfile).items()lines 738–747logger.warning( "%s defines ALIASES `%s=%s`: doxygen rewrites every @%s before clew reads it, so no " "%s is taken from those tags. Remove that alias; clew reads @%s itself.", doxyfile, tag, definition, tag, "requirement edge" if tag == "req" else "exemption", tag, )

Requirements

REQ-DDB-SCHEMA-006