declaration.py¶
clew/declaration.py
A target repo's own `.clew.yaml` — its declared indexing conventions.
_check_section_keys
None clew.declaration._check_section_keys(str name, dict[str, Any] value, Path path)
Refuse a key a section-document section's reader never reads.
Source · 19 lines
def _check_section_keys(name: str, value: dict[str, Any], path: Path) -> None:
"""R5-CFG F4: `preprocessor: {predefine: [FOO]}` recorded a DECLARED configuration with no
macros, and `kconfig: {path: ...}` (once the documented spelling) was ignored in favour of the
root Kconfig by convention.
@brief Allow-list a section document's keys.
"""
allowed = SECTION_KEYS.get(name)
if allowed is None:
return
unknown = sorted(str(k) for k in value if k not in allowed)
if unknown:
raise DeclarationError(
f"{path}: {name} names unknown key(s) {', '.join(repr(k) for k in unknown)} — "
f"allowed: {', '.join(sorted(allowed))}. A misspelled key reads as an absent one, so "
f"it would silently take its default."
)
Activity · 6 steps
Flows
_checked_list_section
list[str] clew.declaration._checked_list_section(str name, Any value, Path path)
Read a list section, accepting one bare string as a one-item list.
Source · 11 lines
def _checked_list_section(name: str, value: Any, path: Path) -> list[str]:
"""@brief Normalise a list section. @return Strings."""
if isinstance(value, str):
return [value]
if not isinstance(value, list) or not all(isinstance(v, (str, int, float)) for v in value):
raise DeclarationError(
f"{path}: {name} must be a list of strings (or one string), got {type(value).__name__}"
)
return [str(v) for v in value]
Activity · 5 steps
Flows
_checked_requirements
dict[str, Any] clew.declaration._checked_requirements(Any value, Path path)
Check the catalog section against the gate's own schema.
Source · 16 lines
def _checked_requirements(value: Any, path: Path) -> dict[str, Any]:
"""@brief Validate `requirements:` with REQUIREMENTS_SCHEMA. @return Mapping."""
from .guard.config import REQUIREMENTS_SCHEMA, _validate_node
section = {"file": value} if isinstance(value, str) else value
if not isinstance(section, dict):
raise DeclarationError(
f"{path}: {SECTION_REQUIREMENTS} must be one path or the catalog mapping, got "
f"{type(value).__name__}"
)
errors = _validate_node(section, REQUIREMENTS_SCHEMA, SECTION_REQUIREMENTS)
if errors:
raise DeclarationError(f"{path}: {'; '.join(errors)}")
return dict(section)
Activity · 8 steps
Flows
_checked_section
Any clew.declaration._checked_section(str name, Any value, Path path)
Check one section's shape.
Called by _checked_sections
Calls _check_section_keys, _checked_list_section, _checked_requirements, _checked_tests, check_manifest_document
Source · 34 lines
def _checked_section(name: str, value: Any, path: Path) -> Any:
"""@brief Refuse a wrong-shaped section, naming it and the expected shape.
@return The checked value.
@version 1
"""
from .buildoptions import BuildOptionError, check_manifest_document
if name in LIST_SECTIONS:
return _checked_list_section(name, value, path)
if name == SECTION_REQUIREMENTS:
return _checked_requirements(value, path)
if name == SECTION_TESTS and isinstance(value, dict):
value = _checked_tests(value, path)
if name in PATH_SECTIONS:
if not isinstance(value, str) or not value.strip():
raise DeclarationError(
f"{path}: {name} must be one repo-relative path, got {type(value).__name__}"
)
return value
if not isinstance(value, dict):
raise DeclarationError(
f"{path}: {name} must be a mapping (the document inline), got "
f"{type(value).__name__}. Nothing reads a {type(value).__name__} here, so the build "
f"would have used built-in defaults while reporting the section declared."
)
if name in MANIFEST_SECTIONS:
try:
return check_manifest_document(name, value)
except BuildOptionError as exc:
raise DeclarationError(f"{path}: {exc}") from exc
_check_section_keys(name, value, path)
return value
Activity · 20 steps
Flows
_checked_sections
dict[str, Any] clew.declaration._checked_sections(dict[str, Any] data, Path path)
Check every declared section's shape, normalising a one-string list section.
Source · 15 lines
def _checked_sections(data: dict[str, Any], path: Path) -> dict[str, Any]:
"""ONE VALIDATOR FOR BOTH ROUTES (R5-CFG F1): manifest sections go through
`buildoptions.check_manifest_document`, the check tier 1 already had, so a key refused from
`--declare` is refused from the checked-in file too.
@brief Validate section shapes.
@return Normalised declaration.
@version 1
"""
out = dict(data)
for name, value in data.items():
out[name] = _checked_section(name, value, path)
return out
Activity · 4 steps
Flows
_checked_tests
dict[str, Any] clew.declaration._checked_tests(dict[str, Any] value, Path path)
Check the list-shaped keys of tests: .
Source · 25 lines
def _checked_tests(value: dict[str, Any], path: Path) -> dict[str, Any]:
"""`paths` and `function_prefixes` are lists; `macros` maps a SHAPE (`named` / `suite` /
`bare`) to a list. An unknown shape is refused by name: it would read as no macros at all.
@brief Check tests: lists and shapes.
@return The section.
"""
out = dict(value)
for key in (TESTS_PATHS, TESTS_FUNCTION_PREFIXES):
if key in out:
out[key] = _checked_list_section(f"{SECTION_TESTS}.{key}", out[key], path)
macros = out.get(TESTS_MACROS)
if macros is not None:
if not isinstance(macros, dict) or set(macros) - TESTS_MACRO_SHAPES:
raise DeclarationError(
f"{path}: tests.macros must map a shape ({', '.join(sorted(TESTS_MACRO_SHAPES))}) to a "
f"list of macro names, got {macros!r}"
)
out[TESTS_MACROS] = {
shape: _checked_list_section(f"tests.macros.{shape}", names, path)
for shape, names in macros.items()
}
return out
Activity · 10 steps
Flows
_parsed_declaration
tuple[dict[str, Any], str | None] clew.declaration._parsed_declaration(Path path)
Parse a declaration file into (mapping, problem).
Source · 21 lines
def _parsed_declaration(path: Path) -> tuple[dict[str, Any], str | None]:
"""ONE PARSE FOR THE BUILD AND FOR THE MESSAGES that describe it, so a refusal saying
"comments only" and a build honouring nothing cannot disagree about the same file.
@brief Parse a declaration file, classifying why it holds nothing.
@return (mapping, problem phrase or None).
@version 1
"""
import yaml
try:
data = yaml.safe_load(path.read_text(encoding="utf-8"))
except (OSError, yaml.YAMLError) as exc:
return {}, f"is unreadable ({exc})"
if data is None:
return {}, None
if not isinstance(data, dict):
return {}, f"holds a {type(data).__name__}, not a mapping of sections"
return data, None
Activity · 10 steps
Flows
_read_mapping
dict[str, Any] clew.declaration._read_mapping(Path path)
Parse a YAML file expected to hold a mapping.
Source · 21 lines
def _read_mapping(path: Path) -> dict[str, Any]:
"""AN EMPTY OR COMMENT-ONLY FILE IS NOT MALFORMED (gh#48). It is exactly what
`propose_declaration` hands an owner — a draft written entirely as comments so that committing
it changes nothing — and it used to log "does not contain a mapping — ignoring it", a WARNING
that reads as a broken file and sent a reporter looking for damage that was not there. It
states nothing, so the defaults apply, and that is said at INFO in those words.
@brief Read a YAML mapping, degrading to {} with a message that names the actual state.
@return The mapping, or {}.
@version 2
"""
data, problem = _parsed_declaration(path)
if problem is not None:
logger.warning("%s %s — ignoring it, using built-in defaults", path, problem)
elif not data:
logger.info(
"%s states nothing (it is empty or comments only) — built-in defaults apply", path
)
return data
Activity · 6 steps
Flows
declared_event_tags
dict[str, str] | None clew.declaration.declared_event_tags(dict[str, Any] declaration)
The declared event-tag vocabulary, role-validated.
Called by _build_stages
Tested by
Calls none
Source · 37 lines
def declared_event_tags(declaration: dict[str, Any]) -> dict[str, str] | None:
"""REPLACE, never merge — see SECTION_EVENT_TAGS on the `raises` collision that
makes replacing the only available fix. None (not `{}`) is what "undeclared"
returns, because the importer's parameter distinguishes the two and `None` is
its "use the defaults" value; an empty or non-mapping section is undeclared.
AN UNRECOGNISED ROLE IS REFUSED, matching `dispatch.py::_reject_unknown` and the
unknown-section refusal above. Degrading a misspelled `producers:` to a default
would silently file an emitter as a handler, and a reversed edge is worse than a
missing one: `chain_trace` would report causality flowing the wrong way with the
`declared=1`, `confidence='high'` grading these edges carry precisely because an
author asserted them.
The two roles are validated against `event_edges`' own constants rather than a
`vocabulary.py` entry: they never reach the database as a value — the role
chooses which COLUMN a rowid lands in (`writer_rowid` vs `reader_rowid`) — so
there is no DDL CHECK for `vocabulary.py` to be the source of.
@brief Read and validate the repo's declared event-tag vocabulary.
@return Tag → role mapping, or None when nothing usable is declared.
@version 1
"""
declared = section(declaration, SECTION_EVENT_TAGS)
if not declared:
return None
vocabulary: dict[str, str] = {}
for tag, role in declared.items():
normalised = str(role).strip().lower()
if normalised not in (PRODUCER, CONSUMER):
raise DeclarationError(
f"{SECTION_EVENT_TAGS}: tag {str(tag)!r} declares role {role!r} "
f"— allowed: {PRODUCER}, {CONSUMER}"
)
vocabulary[str(tag).strip().lower()] = normalised
return vocabulary
Activity · 10 steps
Requirements
declared_path
Path | None clew.declaration.declared_path(dict[str, Any] declaration, str name, Path|str|None repo_root)
Resolve a repo-relative path declared in a section.
Called by _build_stages
Tested by
Calls none
Source · 20 lines
def declared_path(
declaration: dict[str, Any], name: str, repo_root: Path | str | None
) -> Path | None:
"""For manifests that are not YAML (the ingot data-model TOML), the section
names a file instead of inlining it. Resolved relative to the repo so the
declaration stays portable, and a declared-but-missing file warns rather
than failing the build.
@brief Resolve a declared repo-relative manifest path.
@return Absolute path, or None.
@version 2
"""
value = declaration.get(name)
if not isinstance(value, str) or repo_root is None:
return None
path = (Path(repo_root).expanduser() / value).resolve()
if not path.is_file():
logger.warning("declaration: %s names %s, which does not exist — ignoring", name, path)
return None
return path1 more lines, not shown
Activity · 8 steps
Requirements
describe_declaration
str clew.declaration.describe_declaration(Path repo_root)
One sentence on a repository's .clew.yaml and whether a build honours it.
Source · 33 lines
def describe_declaration(repo_root: Path) -> str:
"""gh#48 ASK 4. A reporter's split repository carried a `.clew.yaml` that was comments only, so
its guidance reached neither clew nor the agent — and nothing on the tool surface said so. A
refusal about that repository now names the file and whether it was honoured, which is where an
owner would go to change the behaviour being refused.
SILENT WHEN THE FILE IS ABSENT, which is the common case and not news: most repositories declare
nothing, and a sentence saying so on every refusal is a sentence nobody reads.
@brief Describe a repository's declaration file for a message.
@return The sentence, or "".
@version 2
"""
path = Path(repo_root) / DECLARATION_NAME
if not path.is_file():
return ""
data, problem = _parsed_declaration(path)
if problem is not None:
return f"Its {DECLARATION_NAME} {problem}, so it is ignored and built-in defaults apply."
if not data:
return (
f"Its {DECLARATION_NAME} holds only comments, so it states nothing and built-in "
f"defaults apply — uncomment a section to have builds honour it."
)
sections = ", ".join(sorted(str(k) for k in data if k not in NON_DECLARATION_SECTIONS))
if not sections:
return (
f"Its {DECLARATION_NAME} configures only the gate (`{SECTION_GUARD}:`), so builds "
f"run on built-in defaults."
)
return f"Its {DECLARATION_NAME} declares {sections}, which every build honours."
Activity · 12 steps
Requirements
Flows
load_declaration
dict[str, Any] clew.declaration.load_declaration(Path|str|None repo_root)
Load a repo's .clew.yaml , or an empty mapping when it has none.
Called by _build_stages, _declared_doxyfile, _declared_entry_patterns, _test_shapes, _vendored_scope, build_context, config_inputs, declared_blocking_harvester, declared_sub_index_excludes
Tested by 30 tests
test_a_comment_only_declaration_is_not_reported_as_malformed, test_a_leftover_doxygen_guard_yaml_is_not_read, test_a_list_section_written_as_one_string_is_one_entry, test_a_mapping_section_written_as_a_scalar_is_refused, test_a_misspelled_section_is_refused, test_a_path_section_must_be_a_string, test_a_section_document_key_nothing_reads_is_refused, test_absent_declaration_is_not_an_error, test_an_experimental_section_is_tolerated_and_ignored, test_an_unknown_manifest_entry_key_is_refused_in_tree, test_an_unknown_section_beside_the_guard_section_is_still_refused, test_an_unknown_section_is_refused 18 more
test_an_unknown_tests_key_is_refused, test_an_x_prefix_does_not_excuse_a_misspelling, test_draft_becomes_a_statable_option_without_a_file, test_every_known_section_is_accepted, test_existing_declaration_is_not_overwritten_without_force, test_malformed_declaration_degrades_to_defaults, test_overviews_declaration_example_loads_and_means_what_it_says, test_rendered_draft_round_trips_through_load_declaration, test_sections_mirror_the_standalone_manifest_formats, test_test_paths_is_refused_with_a_pointer, test_the_declaration_and_the_gate_config_share_one_file, test_the_declaration_route_reaches_the_stage_and_the_flag_wins, test_the_fixture_config_loads_under_the_current_schema, test_the_guard_section_is_known_but_is_not_an_index_declaration, test_the_index_reads_tests_paths, test_the_index_warns_too, test_the_old_guard_config_passthrough_is_not_read, test_the_refusal_names_the_probable_cause
Calls load_declaration_located
Source · 8 lines
def load_declaration(repo_root: Path | str | None) -> dict[str, Any]:
"""@brief Read the target's declared conventions, discarding their provenance.
@return Parsed mapping, or {} when there is nothing usable.
@version 7
"""
return load_declaration_located(repo_root)[0]
Activity · 1 steps
Requirements
Flows
load_declaration_located
tuple[dict[str, Any], Path | None] clew.declaration.load_declaration_located(Path|str|None repo_root)
A repo's declaration AND the file it was read from.
Called by _declared_index_scope, load_declaration
Calls _checked_sections, _read_mapping
Source · 93 lines
def load_declaration_located(
repo_root: Path | str | None,
) -> tuple[dict[str, Any], Path | None]:
"""THE PATH TRAVELS WITH THE DATA (gh#20): `scope.py` reports WHERE it read the
index scope from, and None when nothing was declared, rather than naming a file
that need not exist.
The `guard:` section is the gate's and is dropped from the result, so a file that
configures only the gate declares nothing to the index.
Absent is the norm, not an error: most repos declare nothing and run
entirely on built-in defaults. An unreadable or malformed file is reported
at WARNING and treated as absent, so a broken file degrades to defaults rather
than failing a build that would otherwise succeed.
An UNKNOWN SECTION NAME is treated differently, and the distinction is
deliberate. Unparseable YAML is an accident with nothing recoverable in it. A
misspelled section is a document that parses, where the author plainly
intended something — and degrading there means running on built-in defaults
while reporting that the declaration was read. So this REFUSES, matching
`dispatch.py::_reject_unknown`, which closed exactly this failure mode one
level down and whose lesson was that entry-level slips are worse than
document-level ones because they are quieter.
@brief Read the target's declared conventions and their source file.
@return (parsed mapping, source path) — ({}, None) when there is nothing usable.
@version 3
"""
if repo_root is None:
return {}, None
root = Path(repo_root).expanduser()
path = root / DECLARATION_NAME
data = _read_mapping(path) if path.is_file() else {}
if data:
experimental = sorted(str(key) for key in data if str(key).startswith(EXPERIMENTAL_PREFIX))
if experimental:
logger.warning(
"declaration: %s carries experimental section(s) %s — tolerated and IGNORED, "
"so nothing in them reaches this build. A misspelled section that happens to "
"carry the `%s` prefix looks exactly like this.",
path,
", ".join(experimental),
EXPERIMENTAL_PREFIX,
)
moved = sorted(str(key) for key in data if key in MOVED_SECTIONS)
if moved:
raise DeclarationError(
f"{path}: "
+ "; ".join(f"`{k}` moved in 2.0.0 to {MOVED_SECTIONS[k]}" for k in moved)
)
unknown = sorted(
str(key)
for key in data
if key not in ACCEPTED_SECTIONS and not str(key).startswith(EXPERIMENTAL_PREFIX)
)
if unknown:
raise DeclarationError(
f"{path}: unknown section(s) {', '.join(repr(k) for k in unknown)} "
f"— allowed: {', '.join(sorted(ACCEPTED_SECTIONS))}. Nothing reads an "
f"unknown section, so the build would have used built-in defaults "
f"while reporting that your declaration was honoured. If this file was "
f"written for a newer clew than the one reading it — `guard:` is new in "
f"1.1.0 — upgrade with `pip install -U clew-trace` and bump the `rev:` in "
f"`.pre-commit-config.yaml` to match."
)
data = {
key: value
for key, value in data.items()
if key not in NON_DECLARATION_SECTIONS and not str(key).startswith(EXPERIMENTAL_PREFIX)
}
## BOTH SIDES OF THE DROPPED TOOL (group B, 1.1.0 merge review). The INDEX reads the
## gate's section too — the `@req` id pattern and the requirements catalog come from
## `guard:` — so a repository still carrying an inert `.doxygen-guard.yaml` has its
## requirement links defaulted in the graph for the same reason its gate stopped
## enforcing them. An owner who only runs `clew index` would otherwise never be told.
##
## The GATE'S OWN helper, not a copy: this module already imports the gate's config for
## the section name, and two descriptions of one migration is how they drift.
## 2.0.0 (PG4): the GATE refuses to run while a doxygen-guard leftover exists; the INDEX only
## says so, because clew indexes repositories it must not change (third-party trees included).
if (path.parent / LEGACY_CONFIG_NAME).is_file():
logger.warning(
"%s is a doxygen-guard config: clew does not read it, and `clew guard` refuses to run "
"while it exists. Move its contents under `guard:` in %s and delete it.",
path.parent / LEGACY_CONFIG_NAME,
path.name,
)
if data:
data = _checked_sections(data, path)
logger.info("declaration: %s declares %s", path, ", ".join(sorted(data)))
return data, (path if data else None)
Activity · 22 steps
Requirements
Flows
section
dict[str, Any] | None clew.declaration.section(dict[str, Any] declaration, str name)
One declaration section, as a mapping.
Source · 6 lines
def section(declaration: dict[str, Any], name: str) -> dict[str, Any] | None:
"""@brief Return a mapping-valued section, or None."""
value = declaration.get(name)
return value if isinstance(value, dict) else None
Activity · 2 steps
Requirements
stated_document_meta
dict[str, str] clew.declaration.stated_document_meta(bytes raw, dict[str, Any] document)
Identify a STATED declaration document for the build record.
Called by _apply_declared_document
Tested by
Calls none
Source · 42 lines
def stated_document_meta(raw: bytes, document: dict[str, Any]) -> dict[str, str]:
"""WHAT WAS STATED, recorded so a later reader can check it was applied.
`options.*` records which TIER won for each option and cannot answer this question.
Only a tier-1 statement replays onto a later build, so a section added to a stated
document AFTER the build that last stated it never lands — while the sections that
did still report `explicit`. Measured on the mbedtls acceptance target: one document
declaring `locks`, `vendored` and `preprocessor` produced an index with
`options.locks.tier=explicit`, `options.predefined.tier=heuristic` and no vendored
row at all, and every reader reported health. It invalidated a graded run.
CONTENT-ADDRESSED, WITH NO SECTION-TO-EVIDENCE MAP. The sha identifies the document
and the section list names its top-level keys, so a checker compares the file it holds
against the build without knowing that `preprocessor:` lands as `options.predefined.*`
or that `vendored:` leaves no `options.*` row. Such a map would be a second vocabulary
free to drift as sections are added, and the section it forgot would be the silent one.
NO PATH IS RECORDED. A stated document lives in the CONSUMER'S tree, not the target's,
so storing its path would publish the builder's machine layout through every MCP reply —
the disclosure that forced the build-version-9 bump. A sha plus a section list
identifies the document exactly and says nothing about where it sat.
@brief build_meta identification of a stated declaration document.
@return {stated_sha256, stated_sections} — sections empty-string-free.
@version 1
"""
import hashlib
## SORTED, so two spellings of one document produce one row. `build_meta` is compared
## verbatim by the determinism test, and a YAML parser's key order is whatever the file
## happened to use — the same reason `tiers.DOCUMENT_SEPARATORS` canonicalises.
sections = SECTION_SEPARATOR.join(sorted(str(key) for key in document))
return {
"stated_sha256": hashlib.sha256(raw).hexdigest(),
## An EMPTY document states nothing, and the falsy-drop rule in `write_build_signature`
## then writes no section row — which is correct rather than lossy: `--declare` on an
## empty file is the withdrawal spelling, so "nothing was stated" and "no document was
## given" genuinely are the same build. The sha still records that a file was read.
"stated_sections": sections,
}
Activity · 3 steps
Requirements
string_list
list[str] clew.declaration.string_list(dict[str, Any] declaration, str name)
A declaration section holding a list of strings.
Called by _build_stages, _entry_patterns
Tested by
Calls none
Source · 19 lines
def string_list(declaration: dict[str, Any], name: str) -> list[str]:
"""Some sections are a flat list rather than a mapping — reachability entry
patterns, for instance. A non-list value is ignored with a warning rather
than coerced, so a malformed section degrades to "declared nothing" instead
of silently seeding something unintended.
@brief Read a list-valued declaration section.
@return List of declared strings.
@version 1
"""
value = declaration.get(name)
if value is None:
return []
if not isinstance(value, list):
logger.warning("declaration: %s must be a list — ignoring it", name)
return []
return [str(v) for v in value if str(v)]