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.

clew/declaration.py:633

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
lines 640–640allowed = SECTION_KEYS.get(name)lines 641–641◇ if allowed is Nonelines 642–642returnlines 643–643unknown = sorted(str(k) for k in value if k not in allowed)lines 644–644◇ if unknownlines 645–649raise 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." )

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.

clew/declaration.py:615

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
lines 617–617◇ if isinstance(value, str)lines 618–618return [value]lines 619–619◇ if not isinstance(value, list) or not all(isinstance(v, (str, int, float)) for v in value)lines 620–622raise DeclarationError( f"{path}: {name} must be a list of strings (or one string), got {type(value).__name__}" )lines 623–623return [str(v) for v in value]

Flows

_checked_requirements

dict[str, Any] clew.declaration._checked_requirements(Any value, Path path)

Check the catalog section against the gate's own schema.

clew/declaration.py:592

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
lines 594–594from .guard.config import REQUIREMENTS_SCHEMA, _validate_nodelines 596–596section = {"file": value} if isinstance(value, str) else valuelines 597–597◇ if not isinstance(section, dict)lines 598–601raise DeclarationError( f"{path}: {SECTION_REQUIREMENTS} must be one path or the catalog mapping, got " f"{type(value).__name__}" )lines 602–602errors = _validate_node(section, REQUIREMENTS_SCHEMA, SECTION_REQUIREMENTS)lines 603–603◇ if errorslines 604–604raise DeclarationError(f"{path}: {'; '.join(errors)}")lines 605–605return dict(section)

Flows

_checked_section

Any clew.declaration._checked_section(str name, Any value, Path path)

Check one section's shape.

clew/declaration.py:521

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
lines 526–526from .buildoptions import BuildOptionError, check_manifest_documentlines 528–528◇ if name in LIST_SECTIONSlines 529–529return _checked_list_section(name, value, path)lines 530–530◇ if name == SECTION_REQUIREMENTSlines 531–531return _checked_requirements(value, path)lines 532–532◇ if name == SECTION_TESTS and isinstance(value, dict)lines 533–533value = _checked_tests(value, path)lines 534–534◇ if name in PATH_SECTIONSlines 535–535◇ if not isinstance(value, str) or not value.strip()lines 536–538raise DeclarationError( f"{path}: {name} must be one repo-relative path, got {type(value).__name__}" )lines 539–539return valuelines 540–540◇ if not isinstance(value, dict)lines 541–545raise 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." )lines 546–546◇ if name in MANIFEST_SECTIONSlines 547–547trylines 548–548return check_manifest_document(name, value)lines 549–549except BuildOptionError as exclines 550–550raise DeclarationError(f"{path}: {exc}") from exclines 551–551_check_section_keys(name, value, path)lines 552–552return value

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.

clew/declaration.py:496

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
lines 505–505out = dict(data)lines 506–506◇ for name, value in data.items()lines 507–507out[name] = _checked_section(name, value, path)lines 508–508return out

Flows

_checked_tests

dict[str, Any] clew.declaration._checked_tests(dict[str, Any] value, Path path)

Check the list-shaped keys of tests: .

clew/declaration.py:561

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
lines 568–568out = dict(value)lines 569–569◇ for key in (TESTS_PATHS, TESTS_FUNCTION_PREFIXES)lines 570–570◇ if key in outlines 571–571out[key] = _checked_list_section(f"{SECTION_TESTS}.{key}", out[key], path)lines 572–572macros = out.get(TESTS_MACROS)lines 573–573◇ if macros is not Nonelines 574–574◇ if not isinstance(macros, dict) or set(macros) - TESTS_MACRO_SHAPESlines 575–578raise DeclarationError( f"{path}: tests.macros must map a shape ({', '.join(sorted(TESTS_MACRO_SHAPES))}) to a " f"list of macro names, got {macros!r}" )lines 579–582out[TESTS_MACROS] = { shape: _checked_list_section(f"tests.macros.{shape}", names, path) for shape, names in macros.items() }lines 583–583return out

Flows

_parsed_declaration

tuple[dict[str, Any], str | None] clew.declaration._parsed_declaration(Path path)

Parse a declaration file into (mapping, problem).

clew/declaration.py:683

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
lines 691–691import yamllines 693–693trylines 694–694data = yaml.safe_load(path.read_text(encoding="utf-8"))lines 695–695except (OSError, yaml.YAMLError) as exclines 696–696return {}, f"is unreadable ({exc})"lines 697–697◇ if data is Nonelines 698–698return {}, Nonelines 699–699◇ if not isinstance(data, dict)lines 700–700return {}, f"holds a {type(data).__name__}, not a mapping of sections"lines 701–701return data, None

Flows

_read_mapping

dict[str, Any] clew.declaration._read_mapping(Path path)

Parse a YAML file expected to hold a mapping.

clew/declaration.py:657

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
lines 668–668data, problem = _parsed_declaration(path)lines 669–669◇ if problem is not Nonelines 670–670logger.warning("%s %s — ignoring it, using built-in defaults", path, problem)lines 671–671◇ elif not datalines 672–674logger.info( "%s states nothing (it is empty or comments only) — built-in defaults apply", path )lines 675–675return data

Flows

declared_event_tags

dict[str, str] | None clew.declaration.declared_event_tags(dict[str, Any] declaration)

The declared event-tag vocabulary, role-validated.

clew/declaration.py:834

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
lines 856–856declared = section(declaration, SECTION_EVENT_TAGS)lines 857–857◇ if not declaredlines 858–858return Nonelines 859–859vocabulary: dict[str, str] = {}lines 860–860◇ for tag, role in declared.items()lines 861–861normalised = str(role).strip().lower()lines 862–862◇ if normalised not in (PRODUCER, CONSUMER)lines 863–866raise DeclarationError( f"{SECTION_EVENT_TAGS}: tag {str(tag)!r} declares role {role!r} " f"— allowed: {PRODUCER}, {CONSUMER}" )lines 867–867vocabulary[str(tag).strip().lower()] = normalisedlines 868–868return vocabulary

Requirements

REQ-DDB-CONFIG-001

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.

clew/declaration.py:878

Show on the map →

Called by _build_stages

Tested by

1 teststest_declared_path_section_resolves_relative_to_the_repo

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 path

1 more lines, not shown

Activity · 8 steps
lines 890–890value = declaration.get(name)lines 891–891◇ if not isinstance(value, str) or repo_root is Nonelines 892–892return Nonelines 893–893path = (Path(repo_root).expanduser() / value).resolve()lines 894–894◇ if not path.is_file()lines 895–895logger.warning("declaration: %s names %s, which does not exist — ignoring", name, path)lines 896–896return Nonelines 897–897return path

Requirements

REQ-DDB-CONFIG-001

describe_declaration

str clew.declaration.describe_declaration(Path repo_root)

One sentence on a repository's .clew.yaml and whether a build honours it.

clew/declaration.py:710

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
lines 723–723path = Path(repo_root) / DECLARATION_NAMElines 724–724◇ if not path.is_file()lines 725–725return ""lines 726–726data, problem = _parsed_declaration(path)lines 727–727◇ if problem is not Nonelines 728–728return f"Its {DECLARATION_NAME} {problem}, so it is ignored and built-in defaults apply."lines 729–729◇ if not datalines 730–733return ( 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." )lines 734–734sections = ", ".join(sorted(str(k) for k in data if k not in NON_DECLARATION_SECTIONS))lines 735–735◇ if not sectionslines 736–739return ( f"Its {DECLARATION_NAME} configures only the gate (`{SECTION_GUARD}:`), so builds " f"run on built-in defaults." )lines 740–740return f"Its {DECLARATION_NAME} declares {sections}, which every build honours."

Requirements

REQ-DDB-CONFIG-001

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.

clew/declaration.py:378

Show on the map →

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 teststest_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 moretest_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
lines 383–383return load_declaration_located(repo_root)[0]

Requirements

REQ-DDB-CONFIG-001

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.

clew/declaration.py:397

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
lines 425–425◇ if repo_root is Nonelines 426–426return {}, Nonelines 427–427root = Path(repo_root).expanduser()lines 428–428path = root / DECLARATION_NAMElines 429–429data = _read_mapping(path) if path.is_file() else {}lines 430–430◇ if datalines 431–431experimental = sorted(str(key) for key in data if str(key).startswith(EXPERIMENTAL_PREFIX))lines 432–432◇ if experimentallines 433–440logger.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, )lines 441–441moved = sorted(str(key) for key in data if key in MOVED_SECTIONS)lines 442–442◇ if movedlines 443–446raise DeclarationError( f"{path}: " + "; ".join(f"`{k}` moved in 2.0.0 to {MOVED_SECTIONS[k]}" for k in moved) )lines 447–451unknown = sorted( str(key) for key in data if key not in ACCEPTED_SECTIONS and not str(key).startswith(EXPERIMENTAL_PREFIX) )lines 452–452◇ if unknownlines 453–461raise 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." )lines 462–466data = { key: value for key, value in data.items() if key not in NON_DECLARATION_SECTIONS and not str(key).startswith(EXPERIMENTAL_PREFIX) }lines 477–477◇ if (path.parent / LEGACY_CONFIG_NAME).is_file()lines 478–483logger.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, )lines 484–484◇ if datalines 485–485data = _checked_sections(data, path)lines 486–486logger.info("declaration: %s declares %s", path, ", ".join(sorted(data)))lines 487–487return data, (path if data else None)

Requirements

REQ-DDB-CONFIG-001

Flows

section

dict[str, Any] | None clew.declaration.section(dict[str, Any] declaration, str name)

One declaration section, as a mapping.

clew/declaration.py:797

Show on the map →

Called by none

Calls none

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
lines 799–799value = declaration.get(name)lines 800–800return value if isinstance(value, dict) else None

Requirements

REQ-DDB-CONFIG-001

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.

clew/declaration.py:749

Show on the map →

Called by _apply_declared_document

Tested by

1 teststest_stated_document_meta_identifies_the_document_by_content

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
lines 775–775import hashliblines 780–780sections = SECTION_SEPARATOR.join(sorted(str(key) for key in document))lines 781–788return { "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, }

Requirements

REQ-DDB-CONFIG-001

string_list

list[str] clew.declaration.string_list(dict[str, Any] declaration, str name)

A declaration section holding a list of strings.

clew/declaration.py:809

Show on the map →

Called by _build_stages, _entry_patterns

Tested by

1 teststest_string_list_section_ignores_a_malformed_value

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)]

Activity · 7 steps
lines 819–819value = declaration.get(name)lines 820–820◇ if value is Nonelines 821–821return []lines 822–822◇ if not isinstance(value, list)lines 823–823logger.warning("declaration: %s must be a list — ignoring it", name)lines 824–824return []lines 825–825return [str(v) for v in value if str(v)]

Requirements

REQ-DDB-CONFIG-001