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.
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 out1 more lines, not shown
Activity · 12 steps
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).
Called by import_req_edges
Tested by 15 tests
test_a_declared_pattern_that_ends_in_punctuation_is_matched_before_stripping, test_declared_pattern_read_from_guard_config, test_extract_req_tags_from_xrefdescription_alias_form, test_extract_req_tags_id_terminated_by_markup_not_just_whitespace, test_extract_req_tags_inferred, test_extract_req_tags_keeps_inferred_when_marker_abuts_markup, test_extract_req_tags_no_tag_returns_empty, test_extract_req_tags_none_text_returns_empty, test_extract_req_tags_stated, test_extract_req_tags_survives_doxygens_own_sentence_period, test_only_ONE_trailing_character_is_retried, test_permissive_fallback_matches_req_rejects_non_req
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
Requirements
_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).
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
Requirements
_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.
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
Requirements
_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.
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
Requirements
_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.
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
Requirements
_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.
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
Requirements
_link_catch2_cases
int clew.requirements._link_catch2_cases(sqlite3.Connection conn, Path repo_root, tuple[str,...]|None test_patterns)
Link the index's Catch2 cases in test code to the requirements they name.
Called by import_req_test_edges
Calls _is_test_file, _source_lines, _table_exists, named_reqs, read_case
Source · 52 lines
def _link_catch2_cases(
conn: sqlite3.Connection, repo_root: Path, test_patterns: tuple[str, ...] | None
) -> int:
"""Doxygen records each case as a function named for its macro, at the macro's line, so the
row is there to link; the title and tags are read from that line (`catch2.read_case`). A tag
that is no catalog id is counted and logged, never linked.
@brief Link Catch2 cases.
@return Rows.
"""
from .catch2 import CASE_MACROS, named_reqs, read_case
catalog = (
{r[0] for r in conn.execute("SELECT id FROM requirements")}
if _table_exists(conn, "requirements")
else set()
)
marks = ",".join("?" * len(CASE_MACROS))
rows = conn.execute(
f"SELECT m.rowid, m.line, p.name FROM memberdef m JOIN path p ON p.rowid = m.file_id "
f"WHERE m.kind = 'function' AND m.name IN ({marks})",
CASE_MACROS,
).fetchall()
lines_of: dict[str, list[str]] = {}
inserted = unknown = 0
for rowid, line, file_path in rows:
if not _is_test_file(str(file_path), test_patterns):
continue
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))
if case is None:
continue
unknown += sum(1 for t in case.tags if t.upper().startswith("REQ") and t not in catalog)
for req_id in named_reqs(case, catalog):
inserted += conn.execute(
## An UPSERT: a comment `@req` doxygen read onto the case's row is already linked
## through `req_edges`, by the macro's name; it gains the title here.
"INSERT INTO req_test_edges (req_id, test_memberdef_rowid, test_name) "
"VALUES (?, ?, ?) ON CONFLICT(req_id, test_memberdef_rowid) "
"DO UPDATE SET test_name = excluded.test_name",
(req_id, rowid, case.title),
).rowcount
if unknown:
logger.warning(
"req_test_edges: %d Catch2 tag(s) look like requirement ids but name none in the "
"catalog; not linked",
unknown,
)
return inserted
Activity · 20 steps
Requirements
_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.
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
Requirements
_refuse_url
None clew.requirements._refuse_url(str text)
Refuse a source that is a URL.
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
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.
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
Requirements
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.
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
Requirements
git_text
str | None clew.requirements.git_text(Path cwd, *str args)
Run git in a local checkout through the hardened environment.
Called by _nested_specs, _read_source, _tagged_at_pin, pin_problems, probe_index, read_catalog_at
Calls git_argv
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
Requirements
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.
Called by _build_stages, run_real_stages
Tested by 7 tests
test_a_function_is_judged_by_its_body_s_file_not_a_declaration_s, test_import_req_edges_creates_expected_rows, test_import_req_edges_permissive_default_populates, test_import_req_test_edges_links_only_test_named_memberdefs, test_nested_domains_catalog_ingests_zero_but_tags_populate, test_with_test_patterns_only_functions_in_test_code_are_tests, test_without_patterns_the_legacy_heuristic_still_applies
Calls _create_req_edges_table, _extract_req_tags
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
Requirements
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.
Called by _build_stages, run_real_stages
Tested by
Calls _create_req_test_edges_table, _link_catch2_cases, _looks_like_test_function, _table_exists, is_test_path
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
Requirements
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 .
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
Requirements
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.
Called by _build_stages, _db, _row, run_real_stages
Tested by 8 tests
test_an_entry_with_nothing_extra_has_no_extra, test_flat_catalog_declared_columns_ingest, test_ingest_requirements_yaml_loads_rows, test_ingest_requirements_yaml_missing_file_creates_empty_table, test_ingest_requirements_yaml_none_path_creates_empty_table, test_ingest_requirements_yaml_reads_the_mapping_keyed_shape, test_ingest_requirements_yaml_still_refuses_an_unrecognized_shape, test_nested_domains_catalog_ingests_zero_but_tags_populate
Calls _create_failure_modes_table, _create_links_table, _create_requirements_table, _insert_failure_modes, _insert_req_entry, _is_flat_req_list, _keyed_req_entries, link_ids, resolve_catalog_columns
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
Requirements
link_ids
list[str] clew.requirements.link_ids(Mapping[str, Any] entry)
The ids an entry links upward to, through satisfies or serves .
Source · 16 lines
def link_ids(entry: Mapping[str, Any]) -> list[str]:
"""#72 item 13 (an adopter, 2026-11-23): sub-catalogues written `serves: [REQ-…]` would each
have needed renaming. ONE READER for the index, the wiki and the gate, as `satisfies_ids` is
one normaliser, so the three never disagree about what an entry links to.
@brief Link ids.
@return Ids.
"""
out: list[str] = []
for key in LINK_KEYS:
for target in satisfies_ids(entry.get(key)):
if target not in out:
out.append(target)
return out
Activity · 6 steps
Requirements
Flows
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 .
Called by _build_stages, declared_catalog, gather, impact_path, run_real_stages
Tested by 11 tests
test_a_guard_section_that_is_not_a_mapping_is_refused_by_the_gate, test_a_leftover_doxygen_guard_yaml_is_not_read, test_an_invalid_guard_section_is_survived, test_an_invalid_section_degrades_the_index_and_is_refused_by_the_gate, test_declared_catalog_columns_read_from_guard_config, test_declared_pattern_read_from_guard_config, test_flat_catalog_declared_columns_ingest, test_nested_domains_catalog_ingests_zero_but_tags_populate, test_no_file_and_no_section_both_mean_nothing_declared, test_the_gate_and_the_index_read_the_same_top_level_section, test_the_index_reads_the_guard_section_of_clew_yaml
Calls read_guard_config
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
Requirements
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.
Called by _read_source, catalog_requirements, covered_via, load_external_requirements
Tested by
Calls _catalog_rows, _refuse_url, git_text
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
Requirements
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.
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
Requirements
resolve_catalog_columns
tuple[str, str] clew.requirements.resolve_catalog_columns(dict|None guard_cfg)
Resolve the DECLARED requirements-catalog id/name column names.
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
Requirements
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.
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
Requirements
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).
Called by _build_stages, run_real_stages
Tested by 10 tests
test_declared_pattern_read_from_guard_config, test_extract_req_tags_id_terminated_by_markup_not_just_whitespace, test_extract_req_tags_keeps_inferred_when_marker_abuts_markup, test_extract_req_tags_survives_doxygens_own_sentence_period, test_nested_domains_catalog_ingests_zero_but_tags_populate, test_only_ONE_trailing_character_is_retried, test_permissive_fallback_matches_req_rejects_non_req, test_permissive_fallback_preserves_inferred_confidence, test_the_index_reads_the_guard_section_of_clew_yaml, test_the_xrefitem_form_stores_the_TRIMMED_id_not_the_raw_token
Calls get_validate
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
Requirements
satisfies_ids
list[str] clew.requirements.satisfies_ids(object value)
The requirement ids a satisfies value names, in every spelling a catalogue uses.
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
Requirements
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.
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,
)