kconfig.py

clew/kconfig.py

The CONFIGURATION SPACE a repo declares in Kconfig — structure and help text.

_served_parse_error

str clew.kconfig._served_parse_error(Exception exc)

The parse error as it may be SERVED: its type and location, never a quoted line.

clew/kconfig.py:456

Source · 24 lines
def _served_parse_error(exc: Exception) -> str:
    """`kconfig.error` IS A SERVED `build_meta` VALUE, and kconfiglib's messages QUOTE THE
    OFFENDING LINE. A repository whose `source` reaches a file it should not read therefore got
    that file's content back out through the failure text even when the parse failed and every
    row was discarded (1.1.0 audit, M2).

    The type and the `file:line:` prefix are kept because they are what makes the value
    diagnostic — an owner can open that line. The remainder is dropped from the SERVED value
    only: `load_kconfig` has already logged the full message at WARNING, which is the
    operator's to read and is not published over MCP. This is the same split
    `_warn_unwalkable` makes in `scope.py` — the gap is reported, the content is not.

    @brief Reduce a parse error to type and location.
    @return "<Type>: <file>:<line>" where a location is present, else "<Type>".
    @version 1
    """
    located = re.match(r"([^\s:]+:\d+)", str(exc))
    where = f": {located.group(1)}" if located else ""
    return (
        f"{type(exc).__name__}{where} — the full message is in the build log, and is not "
        f"published here because it quotes the line it failed on"
    )

Activity · 3 steps
lines 472–472located = re.match(r"([^\s:]+:\d+)", str(exc))lines 473–473where = f": {located.group(1)}" if located else ""lines 474–477return ( f"{type(exc).__name__}{where} — the full message is in the build log, and is not " f"published here because it quotes the line it failed on" )

Requirements

REQ-DDB-PIPE-014

_sourced_outside

list[str] clew.kconfig._sourced_outside(Any kconf, Path root)

Files this parse read that lie outside the repository.

clew/kconfig.py:486

Source · 22 lines
def _sourced_outside(kconf: Any, root: Path) -> list[str]:
    """kconfiglib resolves `source` against `$srctree` and offers NO HOOK on that resolution,
    so `source "/abs/path"` parsed a file anywhere on the machine and served its symbols,
    prompts and help text as this repository's configuration space (1.1.0 audit, M2).

    CHECKED AFTER THE PARSE, from `kconf.kconfig_filenames` — kconfiglib's own record of every
    file it read. The read has happened by the time this runs; what the check prevents is
    DISCLOSURE, which is the harm. A pre-parse scan of the text was the alternative and it is
    the fragile one: `source` takes globs and preprocessor-expanded variables, so a scanner
    would have to re-implement the parser to be right.

    @brief Report sourced files that escape the repository.
    @return The escaping paths.
    @version 1
    """
    escaped = set()
    for name in getattr(kconf, "kconfig_filenames", ()) or ():
        if within_repo(root / str(name), root, setting=f"kconfig source {name}") is None:
            escaped.add(str(name))
    return sorted(escaped)

Activity · 5 steps
lines 501–501escaped = set()lines 502–502◇ for name in getattr(kconf, "kconfig_filenames", ()) or ()lines 503–503◇ if within_repo(root / str(name), root, setting=f"kconfig source {name}") is Nonelines 504–504escaped.add(str(name))lines 505–505return sorted(escaped)

Requirements

REQ-DDB-PIPE-014

as_meta

dict[str, str] clew.kconfig.KconfigModel.as_meta(self)

Flatten to string values for build_meta persistence.

clew/kconfig.py:258

Show on the map →

Called by none

Calls found

Source · 30 lines
    def as_meta(self) -> dict[str, str]:
        """Counts are STRINGS because `write_build_signature` drops falsy values, and a
        measured zero must survive: `"0"` is truthy where `0` is not. That is the same
        rule `coverage.as_meta` and `preprocessor.as_meta` document, and here it is
        what makes "found a Kconfig, parsed it, it declares nothing" distinguishable
        from "no Kconfig".

        Returns {} — no `kconfig.*` rows at all — only when NOTHING was found, so an
        absent key honestly reads as "not recorded" and every existing target's
        `build_meta` is unchanged.

        @brief Kconfig provenance and counts as build_meta values.
        @return Unprefixed key -> string value.
        @version 1
        """
        if not self.found:
            return {}
        return {
            "source": self.location.source,
            "root": str(self.location.path),
            "symbol_count": str(len(self.symbols)),
            "choice_count": str(len(self.choices)),
            "documented_count": str(self.documented),
            "error": self.error,
            ## A STRING COUNT for the reason every count here is one: `write_build_signature`
            ## drops falsy values, so a measured zero has to survive as "0".
            "shell_refused": str(len(self.shell_refused)),
        }

Activity · 3 steps
lines 273–273◇ if not self.foundlines 274–274return {}lines 275–285return { "source": self.location.source, "root": str(self.location.path), "symbol_count": str(len(self.symbols)), "choice_count": str(len(self.choices)), "documented_count": str(self.documented), "error": self.error, ## A STRING COUNT for the reason every count here is one: `write_build_signature` ## drops falsy values, so a measured zero has to survive as "0". "shell_refused": str(len(self.shell_refused)), }

Requirements

REQ-DDB-CONFIG-005

discover_kconfig

KconfigLocation clew.kconfig.discover_kconfig(Path|str|None repo_root, dict[str, Any]|None declaration=None)

Locate a repo's top-level Kconfig: declared, root, then convention.

clew/kconfig.py:294

Source · 28 lines
def discover_kconfig(
    repo_root: Path | str | None, declaration: dict[str, Any] | None = None
) -> KconfigLocation:
    """Explicit, then convention, then a REFUSAL when convention is ambiguous —
    the rule `preprocessor` follows too — because a wrong answer here looks like a
    right one: a Kconfig belonging to
    a vendored subsystem describes a configuration space the repo does not ship,
    and every count taken from it looks legitimate.

    `path` on the returned location is REPO-RELATIVE, and that is not only a
    disclosure rule. kconfiglib resolves `source` paths against `$srctree`, so the
    parse is driven from a relative path anyway and every filename it reports comes
    back relative — one convention end to end rather than two that must be
    reconciled per row.

    @brief Discover the repo's top-level Kconfig with its provenance.
    @return The located Kconfig and how it was found.
    @version 2
    """
    if repo_root is None:
        return KconfigLocation(path=None)
    root = Path(repo_root).expanduser().resolve()
    declared = (declaration or {}).get(SECTION_KCONFIG)
    if isinstance(declared, dict) and declared.get(KEY_ROOT):
        return _declared_kconfig(root, str(declared[KEY_ROOT]))
    return _conventional_kconfig(root)

Activity · 7 steps
lines 313–313◇ if repo_root is Nonelines 314–314return KconfigLocation(path=None)lines 315–315root = Path(repo_root).expanduser().resolve()lines 316–316declared = (declaration or {}).get(SECTION_KCONFIG)lines 317–317◇ if isinstance(declared, dict) and declared.get(KEY_ROOT)lines 318–318return _declared_kconfig(root, str(declared[KEY_ROOT]))lines 319–319return _conventional_kconfig(root)

Requirements

REQ-DDB-CONFIG-005

documented

int clew.kconfig.KconfigModel.documented(self)

How many symbols carry help text — the surface gh#18 exists for.

clew/kconfig.py:246

Show on the map →

Called by none

Calls none

Source · 8 lines
    def documented(self) -> int:
        """@brief Count symbols carrying a help block.

        @return Number of symbols with help text.
        @version 1
        """
        return sum(1 for sym in self.symbols if sym.help)
Activity · 1 steps
lines 252–252return sum(1 for sym in self.symbols if sym.help)

Requirements

REQ-DDB-CONFIG-005

ensure_kconfig_tables

None clew.kconfig.ensure_kconfig_tables(sqlite3.Connection conn)

Idempotent creation of the kconfig_choices and kconfig_symbols tables.

clew/kconfig.py:688

Show on the map →

Called by schema_db, store_kconfig

Calls none

Source · 48 lines
def ensure_kconfig_tables(conn: sqlite3.Connection) -> None:
    """`kconfig_gates` is created by `kconfig_gates.py`, next to the harvest that
    fills it, for the same reason `lock_acquisitions` lives with the lock scan: the
    two layers fail independently — a repo can have a parseable Kconfig and no C
    sources, or gated C and an unparseable Kconfig — and a shared creator would make
    one layer's absence look like the other's.

    `choice_key` is a plain INTEGER rather than a foreign key into `kconfig_choices`,
    because it is a SYNTHETIC per-build ordinal, not a durable identity. Declaring a
    REFERENCES on it would suggest a stability across builds that the enumeration
    order does not promise for a tree whose files changed.

    @brief Create the Kconfig structure tables.
    @version 1
    """
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS kconfig_choices (
            key       INTEGER PRIMARY KEY,
            name      TEXT NOT NULL,
            prompt    TEXT NOT NULL,
            default_expr TEXT NOT NULL,
            file_path TEXT NOT NULL,
            line      INTEGER NOT NULL
        )
        """
    )
    conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS kconfig_symbols (
            name         TEXT NOT NULL,
            type         TEXT NOT NULL {check("kconfig_symbols", "type")},
            prompt       TEXT NOT NULL,
            help         TEXT NOT NULL,
            default_expr TEXT NOT NULL,
            choice_key   INTEGER,
            file_path    TEXT NOT NULL,
            line         INTEGER NOT NULL,
            UNIQUE(name)
        )
        """
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_kconfig_symbols_choice ON kconfig_symbols(choice_key)"
    )
    conn.commit()

Activity · 4 steps
lines 703–714conn.execute( """ CREATE TABLE IF NOT EXISTS kconfig_choices ( key INTEGER PRIMARY KEY, name TEXT NOT NULL, prompt TEXT NOT NULL, default_expr TEXT NOT NULL, file_path TEXT NOT NULL, line INTEGER NOT NULL ) """ )lines 715–729conn.execute( f""" CREATE TABLE IF NOT EXISTS kconfig_symbols ( name TEXT NOT NULL, type TEXT NOT NULL {check("kconfig_symbols", "type")}, prompt TEXT NOT NULL, help TEXT NOT NULL, default_expr TEXT NOT NULL, choice_key INTEGER, file_path TEXT NOT NULL, line INTEGER NOT NULL, UNIQUE(name) ) """ )lines 730–732conn.execute( "CREATE INDEX IF NOT EXISTS idx_kconfig_symbols_choice ON kconfig_symbols(choice_key)" )lines 733–733conn.commit()

Requirements

REQ-DDB-SCHEMA-013

found

bool clew.kconfig.KconfigModel.found(self)

Whether the repo has a top-level Kconfig at all.

clew/kconfig.py:230

Show on the map →

Called by as_meta

Calls none

Source · 11 lines
    def found(self) -> bool:
        """NOT `bool(self.symbols)`. A Kconfig that was found and failed to parse is
        a FINDING, and it is the finding a Zephyr app indexed outside its workspace
        produces.

        @brief Did discovery find a Kconfig?
        @return True when a path was located.
        @version 1
        """
        return self.location.path is not None
Activity · 1 steps
lines 239–239return self.location.path is not None

Requirements

REQ-DDB-CONFIG-005

import_kconfig

KconfigModel clew.kconfig.import_kconfig(Path db_path, Path|str|None repo_root, dict[str, Any]|None declaration=None)

Discover, parse, store and index a repo's configuration space.

clew/kconfig.py:843

Source · 25 lines
def import_kconfig(
    db_path: Path, repo_root: Path | str | None, declaration: dict[str, Any] | None = None
) -> KconfigModel:
    """The one entry point `cli._build_stages` calls. Returns the model rather than
    only counts, because the caller's `write_build_signature` needs the provenance —
    and because a stage that reports a number and discards the reason why it is that
    number is the defect persisting the scope decision fixed.

    Reachable with nothing but `repo_root` and the declaration, so the MCP server
    gets it with no per-section plumbing: CLAUDE.md's rule is that a declaration
    reachable only from an argument is not a declaration, and the MCP build passes
    no override arguments.

    @brief Run the whole Kconfig ingestion stage.
    @return The parsed configuration space.
    @version 2
    """
    location = discover_kconfig(repo_root, declaration)
    if location.path is None:
        logger.info("kconfig: none found — searched %s", location.describe_search())
        return KconfigModel(location=location)
    model = load_kconfig(location, repo_root or ".")
    store_kconfig(db_path, model)
    ingest_kconfig_prose(db_path, model)
    return model

1 more lines, not shown

Activity · 8 steps
lines 860–860location = discover_kconfig(repo_root, declaration)lines 861–861◇ if location.path is Nonelines 862–862logger.info("kconfig: none found — searched %s", location.describe_search())lines 863–863return KconfigModel(location=location)lines 864–864model = load_kconfig(location, repo_root or ".")lines 865–865store_kconfig(db_path, model)lines 866–866ingest_kconfig_prose(db_path, model)lines 867–867return model

Requirements

REQ-DDB-CONFIG-005

ingest_kconfig_prose

int clew.kconfig.ingest_kconfig_prose(Path db_path, KconfigModel model)

Feed every symbol's prompt and help text into the FTS5 prose corpus.

clew/kconfig.py:787

Source · 49 lines
def ingest_kconfig_prose(db_path: Path, model: KconfigModel) -> int:
    """THE HIGHEST-VALUE PART OF gh#18 PER LINE, and it needs no new table. A `help`
    block routinely carries the only statement of a known limitation in a whole
    repository — a variant whose current limits are placeholders reused from a
    sibling pending real measurements — and until this ran, `search_prose` could not
    reach a word of it.

    MUST RUN AFTER `prose.ingest_supplementary_docs`, which DROPs and recreates
    `supplementary_docs` on every build. Running before it would insert these rows
    and then delete them, and the observable result would be an empty search with no
    error anywhere — the quietest possible failure.

    The symbol NAME goes in the heading and is repeated in the content, because FTS5
    ranks over the columns it is given and an engineer searching for a limitation
    types words from the help text, while one auditing a symbol types its name. Both
    have to hit.

    @brief Insert Kconfig prompts and help blocks into the prose corpus.
    @return Chunk count.
    @version 1
    """
    rows = [
        (
            sym.file_path or str(model.location.path),
            f"CONFIG_{sym.name}" + (f" — {sym.prompt}" if sym.prompt else ""),
            "\n".join(part for part in (f"CONFIG_{sym.name}", sym.prompt, sym.help) if part),
        )
        for sym in model.symbols
        if sym.prompt or sym.help
    ]
    if not rows:
        return 0
    conn = sqlite3.connect(str(db_path))
    try:
        conn.execute(
            "CREATE VIRTUAL TABLE IF NOT EXISTS supplementary_docs "
            "USING fts5(file_path, heading, content)"
        )
        conn.executemany(
            "INSERT INTO supplementary_docs (file_path, heading, content) VALUES (?, ?, ?)",
            rows,
        )
        conn.commit()
    finally:
        conn.close()
    logger.info("kconfig: %d prompt/help chunk(s) ingested into the prose corpus", len(rows))
    return len(rows)

Activity · 10 steps
lines 808–816rows = [ ( sym.file_path or str(model.location.path), f"CONFIG_{sym.name}" + (f" — {sym.prompt}" if sym.prompt else ""), "\n".join(part for part in (f"CONFIG_{sym.name}", sym.prompt, sym.help) if part), ) for sym in model.symbols if sym.prompt or sym.help ]lines 817–817◇ if not rowslines 818–818return 0lines 819–819conn = sqlite3.connect(str(db_path))lines 820–820trylines 821–824conn.execute( "CREATE VIRTUAL TABLE IF NOT EXISTS supplementary_docs " "USING fts5(file_path, heading, content)" )lines 825–828conn.executemany( "INSERT INTO supplementary_docs (file_path, heading, content) VALUES (?, ?, ?)", rows, )lines 829–829conn.commit()lines 832–832logger.info("kconfig: %d prompt/help chunk(s) ingested into the prose corpus", len(rows))lines 833–833return len(rows)

Requirements

REQ-DDB-CONFIG-005

load_kconfig

KconfigModel clew.kconfig.load_kconfig(KconfigLocation location, Path|str repo_root)

Parse a located Kconfig into the configuration space it declares.

clew/kconfig.py:396

Source · 55 lines
def load_kconfig(location: KconfigLocation, repo_root: Path | str) -> KconfigModel:
    """DEGRADES TO A RECORDED ERROR, never to an exception. A configuration space is
    metadata about a repository; failing an index build over it would take a whole
    doxygen run with it, and the parse can fail for a completely ordinary reason —
    a Zephyr application's Kconfig `source`s the Zephyr tree's own, so it is
    unparseable outside a west workspace.

    kconfiglib's warnings are CAPTURED rather than printed (`warn_to_stderr=False`)
    and reported at INFO with a count. They are genuinely informative — an undefined
    symbol in a `select` is a real defect in the target — but they are the target's
    business and not a reason to make our build look broken.

    @brief Parse a repo's Kconfig, recording any failure instead of raising.
    @return The parsed configuration space.
    @version 2
    """
    if location.path is None:
        return KconfigModel(location=location)
    root = Path(repo_root).expanduser().resolve()
    refused: list[str] = []
    try:
        ## `parse_environment` REPLACES the process environment for the parse rather than
        ## only setting `srctree` (1.1.0 audit, H3): a Kconfig expands `$(VAR)` from the
        ## environment into text this build then serves, runs `$(shell,…)` as a command, and
        ## imports whatever `KCONFIG_FUNCTIONS` names. One minimal environment closes all
        ## three; `clew/kconfig_env.py` carries the measurements.
        with parse_environment(root) as refusals:
            import kconfiglib

            kconf = kconfiglib.Kconfig(str(location.path), warn_to_stderr=False)
            ## COPIED INSIDE THE BLOCK. The list is cleared when the context exits, and a
            ## parse that raises must still carry its refusals out — a refused expansion is a
            ## plausible CAUSE of the failure, so losing it on the error path loses the
            ## explanation exactly when it is needed.
            refused = list(refusals)
    except Exception as exc:
        logger.warning("kconfig: %s could not be parsed (%s)", location.path, exc)
        return KconfigModel(
            location=location,
            error=_served_parse_error(exc),
            shell_refused=tuple(refused),
        )
    escaped = _sourced_outside(kconf, root)
    if escaped:
        return KconfigModel(
            location=location,
            error=(
                f"refused: this Kconfig sources {len(escaped)} file(s) outside the "
                f"repository ({', '.join(escaped)}), so no configuration space was indexed"
            ),
            shell_refused=tuple(refused),
        )
    return _model_from_kconf(kconf, location, tuple(refused))

Activity · 16 steps
lines 412–412◇ if location.path is Nonelines 413–413return KconfigModel(location=location)lines 414–414root = Path(repo_root).expanduser().resolve()lines 415–415refused: list[str] = []lines 416–416trylines 422–422with parse_environment(root) as refusalslines 423–423import kconfigliblines 425–425kconf = kconfiglib.Kconfig(str(location.path), warn_to_stderr=False)lines 430–430refused = list(refusals)lines 431–431except Exception as exclines 432–432logger.warning("kconfig: %s could not be parsed (%s)", location.path, exc)lines 433–437return KconfigModel( location=location, error=_served_parse_error(exc), shell_refused=tuple(refused), )lines 438–438escaped = _sourced_outside(kconf, root)lines 439–439◇ if escapedlines 440–447return KconfigModel( location=location, error=( f"refused: this Kconfig sources {len(escaped)} file(s) outside the " f"repository ({', '.join(escaped)}), so no configuration space was indexed" ), shell_refused=tuple(refused), )lines 448–448return _model_from_kconf(kconf, location, tuple(refused))

Requirements

REQ-DDB-CONFIG-005

store_kconfig

int clew.kconfig.store_kconfig(Path db_path, KconfigModel model)

Persist a parsed configuration space into the index.

clew/kconfig.py:742

Source · 39 lines
def store_kconfig(db_path: Path, model: KconfigModel) -> int:
    """CREATES THE TABLES EVEN WHEN THERE IS NOTHING TO PUT IN THEM, as long as a
    Kconfig was FOUND. An empty table and an absent table say different things: the
    first is "we looked and this repo declares nothing", the second is "this layer
    never ran". A consumer distinguishing a correct negative from a detector failure
    needs both, and this repo has recorded the wrong one three times.

    A repo with NO Kconfig gets no tables at all, so its schema and its query results
    are byte-identical to a build before this module existed.

    @brief Write the Kconfig structure tables.
    @return Symbol row count.
    @version 1
    """
    if not model.found:
        return 0
    conn = sqlite3.connect(str(db_path))
    try:
        ensure_kconfig_tables(conn)
        conn.executemany(
            "INSERT OR REPLACE INTO kconfig_choices"
            "(key, name, prompt, default_expr, file_path, line) VALUES(?,?,?,?,?,?)",
            [(c.key, c.name, c.prompt, c.default, c.file_path, c.line) for c in model.choices],
        )
        conn.executemany(
            "INSERT OR REPLACE INTO kconfig_symbols"
            "(name, type, prompt, help, default_expr, choice_key, file_path, line) "
            "VALUES(?,?,?,?,?,?,?,?)",
            [
                (s.name, s.type, s.prompt, s.help, s.default, s.choice_key, s.file_path, s.line)
                for s in model.symbols
            ],
        )
        conn.commit()
    finally:
        conn.close()
    return len(model.symbols)

Activity · 9 steps
lines 756–756◇ if not model.foundlines 757–757return 0lines 758–758conn = sqlite3.connect(str(db_path))lines 759–759trylines 760–760ensure_kconfig_tables(conn)lines 761–765conn.executemany( "INSERT OR REPLACE INTO kconfig_choices" "(key, name, prompt, default_expr, file_path, line) VALUES(?,?,?,?,?,?)", [(c.key, c.name, c.prompt, c.default, c.file_path, c.line) for c in model.choices], )lines 766–774conn.executemany( "INSERT OR REPLACE INTO kconfig_symbols" "(name, type, prompt, help, default_expr, choice_key, file_path, line) " "VALUES(?,?,?,?,?,?,?,?)", [ (s.name, s.type, s.prompt, s.help, s.default, s.choice_key, s.file_path, s.line) for s in model.symbols ], )lines 775–775conn.commit()lines 778–778return len(model.symbols)

Requirements

REQ-DDB-CONFIG-005