scope.py

clew/scope.py

Resolve the index scope: a declaration, else the whole repository.

_declaration_advice

str clew.scope._declaration_advice()

How to declare an index scope, in this build's own spelling.

clew/scope.py:522

Source · 20 lines
def _declaration_advice() -> str:
    """A fallback scope reports that the boundary was not chosen; without this it does
    not report the fix, and a diagnosis an owner cannot act on is half a diagnosis
    (gh#32's lesson about the skew report, one tier up).

    Spellings are imported rather than written out, so the advice cannot drift from the
    names the loader actually accepts — the failure `test_declaration.py` pins for
    `index_scope` itself. Imported lazily because `declaration` reads a declaration and
    `scope` interprets one; the module-level cycle is what `_declared_index_scope`
    already avoids the same way.

    @brief Name the declarations that would narrow a fallback scope.
    @return The advice sentence.
    @version 4
    """
    from .declaration import DECLARATION_NAME

    return f"Declare an `{INDEX_SCOPE_SECTION}:` in {DECLARATION_NAME} to let the two differ."

Activity · 2 steps
lines 537–537from .declaration import DECLARATION_NAMElines 539–539return f"Declare an `{INDEX_SCOPE_SECTION}:` in {DECLARATION_NAME} to let the two differ."

Requirements

REQ-DDB-CONFIG-001

Flows

_declaration_note

str clew.scope._declaration_note(Path root)

Where a declaration was looked for, phrased for a fallback reason.

clew/scope.py:1441

Source · 18 lines
def _declaration_note(root: Path) -> str:
    """SAY WHERE WE LOOKED, BEFORE FALLING BACK (gh#16): "this repo declares no scope"
    and "we looked in the wrong place" must not produce the same message. There is one
    place now, `<root>/.clew.yaml`, so the clause names it and says whether it exists;
    a file that exists and declares no `index_scope:` (one that configures only the
    gate, say) is no contradiction.

    @brief Describe the declaration search for a fallback reason.
    @return A human-readable clause.
    """
    from .declaration import DECLARATION_NAME

    path = root / DECLARATION_NAME
    if not path.is_file():
        return f"no {DECLARATION_NAME} was found at {path}"
    return f"{path} exists but carries no {INDEX_SCOPE_SECTION}"

Activity · 5 steps
lines 1451–1451from .declaration import DECLARATION_NAMElines 1453–1453path = root / DECLARATION_NAMElines 1454–1454◇ if not path.is_file()lines 1455–1455return f"no {DECLARATION_NAME} was found at {path}"lines 1456–1456return f"{path} exists but carries no {INDEX_SCOPE_SECTION}"

Requirements

REQ-DDB-CONFIG-001

Flows

_declared_index_scope

DerivedScope | None clew.scope._declared_index_scope(Path root, dict|None stated=None)

Index scope declared directly in the repo's .clew.yaml .

clew/scope.py:1133

Source · 85 lines
def _declared_index_scope(root: Path, stated: dict | None = None) -> DerivedScope | None:
    """Read an explicit `index_scope:` declaration::

        index_scope:
          roots:    [clew, scripts, tests]
          excludes: [tests/fixtures]

    Roots are repo-relative so the declaration stays portable. A root that does
    not exist is dropped with a warning rather than passed to doxygen, which
    would otherwise emit a confusing "input not found" for a stale entry.

    Returns None when nothing usable is declared, which drops the resolution to the
    Doxyfile's own INPUT and then to the whole repository — the zero-config default
    for every repo that says nothing.

    A declared root is TAKEN AT ITS WORD AND NEVER WALKED, which is the whole point —
    and which means a clone of another repository beneath it is indexed with no walk
    to notice. Since gh#333 that is no longer a hazard to close but the behaviour to
    have: `external.py` walks for those trees after the build and TAGS their rows, so
    two codebases in one index can still be told apart in an answer.

    @brief Load a declared index scope.
    @return DerivedScope or None.
    @version 9
    """
    from .declaration import (
        DECLARATION_NAME,
        load_declaration_located,
    )

    if stated:
        ## gh#382 tier 1. Built through the SAME construction as a declared one, so a stated
        ## scope cannot differ from a written one in which paths it drops or how it reports
        ## itself. Only `reason` differs, and it has to: an owner reading "declared in
        ## <file>" for a scope that came from a tool call would go and edit a file that says
        ## nothing, which is the checkable-and-wrong attribution this function already fixed
        ## once for a declaration file.
        declaration, source_path = {INDEX_SCOPE_SECTION: stated}, None
    else:
        declaration, source_path = load_declaration_located(root)
    section = declaration.get(INDEX_SCOPE_SECTION)
    if section is None:
        return None
    where = str(source_path) if source_path else "the stated declaration"
    if not isinstance(section, dict):
        return _Rejected(
            f"{where} carries an {INDEX_SCOPE_SECTION} that is "
            f"{type(section).__name__}, not a mapping"
        )

    ## FAIL CLOSED AT THE ENTRY LEVEL, WHICH IS THE QUIETER ONE. The section name is validated
    ## against KNOWN_SECTIONS; the keys INSIDE it were not, so `exclude:` for `excludes:` parsed
    ## to a perfectly valid mapping that no consumer read. gh#5's reporter wrote exactly that,
    ## got "no index_scope is declared", and could not tell a schema slip from a bug. An
    ## accepted-but-unread key is this project's most repeated defect; this closes one more.
    unknown = sorted(str(k) for k in section if str(k) not in _INDEX_SCOPE_KEYS)
    if unknown:
        return _Rejected(
            f"{where} declares {INDEX_SCOPE_SECTION} with unknown key(s) "
            f"{', '.join(unknown)} — the accepted keys are "
            f"{', '.join(sorted(_INDEX_SCOPE_KEYS))}"
        )

    roots = _existing_paths(root, section.get("roots") or [], "root")
    if not roots:
        return _Rejected(
            f"{where} declares {INDEX_SCOPE_SECTION} but no usable `roots:` — `roots` REPLACES "
            f"the index scope and is REQUIRED; `excludes` alone does nothing, and a root that "
            f"does not exist on disk is dropped"
        )
    excludes = _existing_paths(root, section.get("excludes") or [], "exclude")
    return DerivedScope(
        source=SOURCE_DECLARED,
        ## NAMES THE FILE IT WAS ACTUALLY READ FROM, or the caller when the scope was
        ## stated — never a file that need not exist, which sends an owner to edit nothing.
        reason=(
            f"{INDEX_SCOPE_SECTION} stated by the caller (tier 1)"
            if stated
            else f"{INDEX_SCOPE_SECTION} declared in {source_path or root / DECLARATION_NAME}"
        ),
        roots=tuple(roots),
        excludes=tuple(excludes),
    )

Activity · 19 steps
lines 1158–1161from .declaration import ( DECLARATION_NAME, load_declaration_located, )lines 1163–1163◇ if statedlines 1170–1170declaration, source_path = {INDEX_SCOPE_SECTION: stated}, Nonelines 1171–1171elselines 1172–1172declaration, source_path = load_declaration_located(root)lines 1173–1173section = declaration.get(INDEX_SCOPE_SECTION)lines 1174–1174◇ if section is Nonelines 1175–1175return Nonelines 1176–1176where = str(source_path) if source_path else "the stated declaration"lines 1177–1177◇ if not isinstance(section, dict)lines 1178–1181return _Rejected( f"{where} carries an {INDEX_SCOPE_SECTION} that is " f"{type(section).__name__}, not a mapping" )lines 1188–1188unknown = sorted(str(k) for k in section if str(k) not in _INDEX_SCOPE_KEYS)lines 1189–1189◇ if unknownlines 1190–1194return _Rejected( f"{where} declares {INDEX_SCOPE_SECTION} with unknown key(s) " f"{', '.join(unknown)} — the accepted keys are " f"{', '.join(sorted(_INDEX_SCOPE_KEYS))}" )lines 1196–1196roots = _existing_paths(root, section.get("roots") or [], "root")lines 1197–1197◇ if not rootslines 1198–1202return _Rejected( f"{where} declares {INDEX_SCOPE_SECTION} but no usable `roots:` — `roots` REPLACES " f"the index scope and is REQUIRED; `excludes` alone does nothing, and a root that " f"does not exist on disk is dropped" )lines 1203–1203excludes = _existing_paths(root, section.get("excludes") or [], "exclude")lines 1204–1215return DerivedScope( source=SOURCE_DECLARED, ## NAMES THE FILE IT WAS ACTUALLY READ FROM, or the caller when the scope was ## stated — never a file that need not exist, which sends an owner to edit nothing. reason=( f"{INDEX_SCOPE_SECTION} stated by the caller (tier 1)" if stated else f"{INDEX_SCOPE_SECTION} declared in {source_path or root / DECLARATION_NAME}" ), roots=tuple(roots), excludes=tuple(excludes), )

Flows

_descendable

list[str] clew.scope._descendable(Path here, list[str] dirnames, set[Path] already, list[Path] found)

Split one directory's children into those worth walking and those to exclude.

clew/scope.py:1103

Source · 25 lines
def _descendable(
    here: Path, dirnames: list[str], already: set[Path], found: list[Path]
) -> list[str]:
    """A NESTED REPOSITORY IS DESCENDED INTO (gh#333). It used to be skipped here,
    which was consistent while the scope excluded it wholesale; now that it is indexed
    and tagged, skipping it would leave its `.git` object store and its caches as the
    one part of the tree nothing prunes. `_skip_dir` catches `.git` itself, because it
    is a dot-directory like any other.

    @brief Choose which child directories to descend into.
    @return Descendable child names.
    @version 2
    """
    keep: list[str] = []
    for name in dirnames:
        child = here / name
        if any(_is_within(child, path) for path in already):
            continue
        if _skip_dir(name):
            found.append(child)
            continue
        keep.append(name)
    return keep

Activity · 10 steps
lines 1116–1116keep: list[str] = []lines 1117–1117◇ for name in dirnameslines 1118–1118child = here / namelines 1119–1119◇ if any(_is_within(child, path) for path in already)lines 1120–1120continuelines 1121–1121◇ if _skip_dir(name)lines 1122–1122found.append(child)lines 1123–1123continuelines 1124–1124keep.append(name)lines 1125–1125return keep

Flows

_direct_parent

Path clew.scope._direct_parent(Path tree, Path root, list[Path] all_nested)

The closest containing root for one nested tree, among a repo's own split.

clew/scope.py:218

Source · 16 lines
def _direct_parent(tree: Path, root: Path, all_nested: list[Path]) -> Path:
    """A TREE'S OWN SUB-INDEX MUST EXCLUDE ITS DIRECT CHILDREN ONLY, mirroring exactly what
    first-party already does relative to depth 1: `roots=[tree]` bounds a build's INPUT to
    everything under `tree`, so a GRANDCHILD nested tree is still inside that boundary and
    still needs an explicit exclude to stay out of it — this is what supplies that exclude
    to the right level, rather than every nested tree's exclude list naming every deeper
    descendant regardless of which parent actually contains it directly.

    @brief Find which root (the repo, or another nested tree) directly contains `tree`.
    @return The nearest containing ancestor.
    @version 1
    """
    ancestors = [c for c in (root, *all_nested) if c != tree and c in tree.parents]
    return max(ancestors, key=lambda p: len(p.parts))

Activity · 2 steps
lines 230–230ancestors = [c for c in (root, *all_nested) if c != tree and c in tree.parents]lines 231–231return max(ancestors, key=lambda p: len(p.parts))

Flows

_existing_paths

list[Path] clew.scope._existing_paths(Path root, list entries, str label)

Resolve declared repo-relative entries that exist INSIDE the repository.

clew/scope.py:1398

Source · 38 lines
def _existing_paths(root: Path, entries: list, label: str) -> list[Path]:
    """RESOLVE, THEN CONTAIN, THEN STAT — in that order, because the other orders are the
    bug (1.1.0 security audit, H5). `roots:` is repo-relative BY CONTRACT and nothing here
    enforced it: `(root / "/etc").resolve()` is `/etc`, since joining an absolute path
    discards the left operand, and `../` simply walks out. An index built from such a
    declaration is served as THIS repository's content under paths its owner never offered,
    and the declaration can be STATED by an MCP caller for a repository it merely names.

    Dropped with a warning rather than raised: this function already drops an entry that does
    not exist, and dropping every root leaves `roots` empty, which the caller above turns into
    the rejection an operator sees. One failure mode, one existing message path.

    @brief Resolve declared paths, dropping ones that escape the repo or do not exist.
    @return Contained, existing absolute paths.
    @version 2
    """
    found = []
    resolved_root = root.resolve()
    for entry in entries:
        path = (resolved_root / str(entry)).resolve()
        if not _is_within(path, resolved_root):
            logger.warning(
                "index_scope %s %r resolves to %s, OUTSIDE %s — refusing it. Declared paths "
                "are repository-relative; an absolute or `../` entry is not honoured.",
                label,
                entry,
                path,
                resolved_root,
            )
        elif path.exists():
            found.append(path)
        else:
            logger.warning(
                "index_scope %s %r does not exist under %s — ignoring", label, entry, root
            )
    return found

Activity · 11 steps
lines 1414–1414found = []lines 1415–1415resolved_root = root.resolve()lines 1416–1416◇ for entry in entrieslines 1417–1417path = (resolved_root / str(entry)).resolve()lines 1418–1418◇ if not _is_within(path, resolved_root)lines 1419–1426logger.warning( "index_scope %s %r resolves to %s, OUTSIDE %s — refusing it. Declared paths " "are repository-relative; an absolute or `../` entry is not honoured.", label, entry, path, resolved_root, )lines 1427–1427◇ elif path.exists()lines 1428–1428found.append(path)lines 1429–1429elselines 1430–1432logger.warning( "index_scope %s %r does not exist under %s — ignoring", label, entry, root )lines 1433–1433return found

Flows

_first_party

SubIndex clew.scope._first_party(Path root, list[Path] direct, set[Path] git_ignored)

The first-party SubIndex from a repository's direct nested trees and its ignores.

clew/scope.py:345

Source · 15 lines
def _first_party(root: Path, direct: list[Path], git_ignored: set[Path]) -> SubIndex:
    """ONE RULE FOR BOTH ROUTES, so the full split and the shortcut cannot drift into naming two
    different first-party scopes.

    @brief Assemble the first-party SubIndex.
    @return The SubIndex.
    @version 1
    """
    return SubIndex(
        name=FIRST_PARTY_INDEX,
        roots=(root,),
        excludes=tuple(direct + _own_ignores(root, direct, git_ignored)),
    )

Activity · 1 steps
lines 353–357return SubIndex( name=FIRST_PARTY_INDEX, roots=(root,), excludes=tuple(direct + _own_ignores(root, direct, git_ignored)), )

Flows

_gitignored_paths

IgnoreSweep clew.scope._gitignored_paths(Path root)

Paths the repo's own git configuration ignores.

clew/scope.py:969

Source · 59 lines
def _gitignored_paths(root: Path) -> IgnoreSweep:
    """`.gitignore` is the one scope declaration essentially every repo already
    writes, and it names exactly the trees the whole-repo tier must not swallow: the
    virtualenv, the build output, the tool caches, the vendored checkout.

    `--directory` collapses a wholly-ignored directory into a single entry, so the
    result is a handful of paths rather than one per ignored file.

    Git being absent, or the tree not being a repository, yields no exclusions and
    says so: the scope still works, it is just wider than the repo asked for, and a
    silently wider index is the outcome this project keeps paying for.

    @brief List the paths git ignores under a repo root.
    @return The sweep.
    @version 4
    """
    ## `git_argv` RATHER THAN A BARE "git": the tree being inspected can set
    ## `core.fsmonitor` in its OWN `.git/config`, which git then RUNS on this very query —
    ## so pointing clew at a cloned repository was arbitrary code execution. `-c` on the
    ## command line outranks the config file; see `gitenv.GIT_COMMAND_VALUED_KEYS`.
    command = git_argv(
        "-C",
        str(root),
        "ls-files",
        "-z",
        "--others",
        "--ignored",
        "--exclude-standard",
        "--directory",
    )
    try:
        ## `env=git_env()` and NOT the inherited environment: `git -C <root>` is OUTRANKED
        ## by an absolute `GIT_DIR`, which git exports to every hook it runs — so without
        ## this the ignore list belongs to whatever repository invoked us. See `gitenv`.
        proc = subprocess.run(
            command,
            capture_output=True,
            text=True,
            check=False,
            env=git_env(),
            timeout=GIT_TIMEOUT_SECONDS,
        )
    except OSError as exc:
        logger.warning("index_scope: git is unavailable (%s) — nothing ignored was excluded", exc)
        return IgnoreSweep((), False, f"git is unavailable ({exc})")
    if proc.returncode != 0:
        logger.warning(
            "index_scope: %s is not a git repository (git exit %d) — nothing ignored was "
            "excluded from the whole-repo scope",
            root,
            proc.returncode,
        )
        return IgnoreSweep(
            (), False, f"{root} is not a git repository (git exit {proc.returncode})"
        )
    found = tuple((root / entry).resolve() for entry in proc.stdout.split("\0") if entry)
    return IgnoreSweep(found, True)

Activity · 11 steps
lines 989–998command = git_argv( "-C", str(root), "ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory", )lines 999–999trylines 1003–1010proc = subprocess.run( command, capture_output=True, text=True, check=False, env=git_env(), timeout=GIT_TIMEOUT_SECONDS, )lines 1011–1011except OSError as exclines 1012–1012logger.warning("index_scope: git is unavailable (%s) — nothing ignored was excluded", exc)lines 1013–1013return IgnoreSweep((), False, f"git is unavailable ({exc})")lines 1014–1014◇ if proc.returncode != 0lines 1015–1020logger.warning( "index_scope: %s is not a git repository (git exit %d) — nothing ignored was " "excluded from the whole-repo scope", root, proc.returncode, )lines 1021–1023return IgnoreSweep( (), False, f"{root} is not a git repository (git exit {proc.returncode})" )lines 1024–1024found = tuple((root / entry).resolve() for entry in proc.stdout.split("\0") if entry)lines 1025–1025return IgnoreSweep(found, True)

Flows

_holds_git_tree

bool clew.scope._holds_git_tree(Path directory)

Whether a directory owns a git tree, as a SUBMODULE or as a clone.

clew/scope.py:1265

Show on the map →

Called by _nested_repos_under, test_the_git_tree_probe_answers_no_for_an_unreadable_directory

Calls none

Source · 39 lines
def _holds_git_tree(directory: Path) -> bool:
    """A SUBMODULE'S `.git` IS A FILE, NOT A DIRECTORY, and missing that made the
    whole nested-tree feature blind to the case it was built for. A `git submodule`
    checkout writes a 44-byte `gitdir: ../../.git/modules/<name>` POINTER file where
    a standalone clone has a directory — so `".git" in dirnames`, which is what this
    used to be, found nested CLONES and silently skipped every submodule.

    Measured on [tvanfossen/entropic](https://github.com/tvanfossen/entropic), which
    wraps llama.cpp as a submodule: the directory test reported 28 nested trees and
    `extern/llama.cpp` was not among them, while reporting 28 hits made the detector
    look like it was working. Every unit fixture used a `.git` DIRECTORY, so nothing
    in the suite could have caught it — the fixture matched the detector rather than
    the world.

    `exists()` covers both, and covers a worktree's `.git` file too.

    THIS PREDICATE ANSWERS EXACTLY ONE QUESTION — "is there a separate git tree here?" — and
    gh#352 half 2 first tried to make it answer two. Folding the gitlink test in (below) broke
    the OTHER consumer: `_whole_repo_scope` walks these trees to honour each one's own
    `.gitignore`, because `git ls-files` stops at any tree boundary, submodule or clone alike.
    A developer's nested clone still hides its build output from its parent, so descent has to
    see it whether or not the parent declared it. Ownership is a different question with a
    different predicate — see `_is_dependency_of_parent`.

    UNREADABLE IS "NO", SAID ONCE (#72 bug 1, 2.1): a directory without the search bit (a device log
    pulled in at mode 0644) raised PermissionError here and failed the whole index. It cannot hold a
    tree clew could read, so the answer is no, with a warning naming it.

    @brief Test whether a directory holds its own git tree.
    @return True for a nested clone, submodule or worktree.
    @version 3
    """
    try:
        return (directory / ".git").exists()
    except OSError as exc:
        logger.warning("skipping %s: it cannot be searched (%s)", directory, exc.strerror or exc)
        return False

Activity · 5 steps
lines 1297–1297trylines 1298–1298return (directory / ".git").exists()lines 1299–1299except OSError as exclines 1300–1300logger.warning("skipping %s: it cannot be searched (%s)", directory, exc.strerror or exc)lines 1301–1301return False

Flows

_ignore_clause

str clew.scope._ignore_clause(IgnoreSweep sweep)

The scope reason's clause about ignored paths, true to what git actually answered.

clew/scope.py:942

Source · 18 lines
def _ignore_clause(sweep: IgnoreSweep) -> str:
    """THE CLAUSE MUST NOT OUTRUN THE MEASUREMENT. It used to read "less the paths git ignores"
    unconditionally, so a tree git could not answer for got a reason claiming an exclusion that
    never happened — beside a WARNING saying the opposite.

    @brief Describe the ignore exclusion honestly.
    @return Clause text.
    @version 1
    """
    if sweep.asked:
        return "less the paths git ignores and the dot/cache directories."
    return (
        f"less ONLY the dot/cache directories: the ignore list could NOT be obtained "
        f"({sweep.detail}), so NOTHING git would ignore was excluded and this scope is wider "
        f"than the repository asked for."
    )

Activity · 3 steps
lines 951–951◇ if sweep.askedlines 952–952return "less the paths git ignores and the dot/cache directories."lines 953–957return ( f"less ONLY the dot/cache directories: the ignore list could NOT be obtained " f"({sweep.detail}), so NOTHING git would ignore was excluded and this scope is wider " f"than the repository asked for." )

Flows

_is_within

bool clew.scope._is_within(Path path, Path ancestor)

Whether a path is the same as, or inside, another.

clew/scope.py:1386

Source · 5 lines
def _is_within(path: Path, ancestor: Path) -> bool:
    """@brief Containment test used to suppress already-declared exclusions."""
    return path == ancestor or ancestor in path.parents

Activity · 1 steps
lines 1388–1388return path == ancestor or ancestor in path.parents

Flows

_nested_repos_under

list[Path] clew.scope._nested_repos_under(Path input_root)

Directories holding a .git strictly beneath one declared root.

clew/scope.py:1223

Source · 36 lines
def _nested_repos_under(input_root: Path) -> list[Path]:
    """A BOUNDED walk, not `rglob`. `rglob` would descend into the object stores of the
    repositories it finds and swallow an unreadable directory silently — and a swallowed
    error here reads exactly like "no nested repository", which is the answer that lets
    a foreign codebase into the index. `onerror` therefore WARNS: a directory we could
    not read is a gap in the check, not a clean result.

    Descent stops at a nested repository (its own nested repositories are already
    excluded with it) and at `_MAX_DEPTH`. The root itself never counts, so declaring a
    directory that IS a repository does not exclude the whole scope.

    @brief Find nested repositories under one declared root.
    @return Paths of nested repository directories.
    @version 2
    """
    found: list[Path] = []
    for dirpath, dirnames, _ in os.walk(input_root, onerror=_warn_unwalkable):
        here = Path(dirpath)
        if here != input_root and _holds_git_tree(here):
            found.append(here)
            dirnames[:] = []
            continue
        if len(here.relative_to(input_root).parts) >= _MAX_DEPTH:
            logger.warning(
                "index_scope: depth limit reached under %s — not checking %s for nested "
                "repositories",
                input_root,
                here,
            )
            _DEPTH_LIMITED.append(here)
            dirnames[:] = []
            continue
        dirnames[:] = [d for d in dirnames if not _skip_dir(d)]
    return found

Activity · 14 steps
lines 1238–1238found: list[Path] = []lines 1239–1239◇ for dirpath, dirnames, _ in os.walk(input_root, onerror=_warn_unwalkable)lines 1240–1240here = Path(dirpath)lines 1241–1241◇ if here != input_root and _holds_git_tree(here)lines 1242–1242found.append(here)lines 1243–1243dirnames[:] = []lines 1244–1244continuelines 1245–1245◇ if len(here.relative_to(input_root).parts) >= _MAX_DEPTHlines 1246–1251logger.warning( "index_scope: depth limit reached under %s — not checking %s for nested " "repositories", input_root, here, )lines 1252–1252_DEPTH_LIMITED.append(here)lines 1253–1253dirnames[:] = []lines 1254–1254continuelines 1255–1255dirnames[:] = [d for d in dirnames if not _skip_dir(d)]lines 1256–1256return found

Flows

_nested_trees_recursive

list[Path] clew.scope._nested_trees_recursive(Path under, set[Path] ignored)

Every nested git tree under one root, at ANY depth.

clew/scope.py:175

Source · 36 lines
def _nested_trees_recursive(under: Path, ignored: set[Path]) -> list[Path]:
    """`nested_repo_roots` ITSELF ALREADY STOPS DESCENT at the first `.git` it finds — by
    design, so a submodule's OWN internals are not walked for the boundary that owns them.
    That is exactly right for ONE level and exactly wrong for splitting: it is also why a
    vendored tree's OWN vendored trees (b12-slam's boost/opencv/pcl, libBissellIoT's own
    curl/mbedtls/paho) were swallowed whole into their parent's sub-index instead of getting
    their own. Recursing HERE — calling `nested_repo_roots` again from INSIDE each tree it
    finds — is what gives each of those its own identity, without changing what any single
    call does.

    `ignored` IS EXTENDED PER LEVEL, not reused unchanged. A tree's own `.gitignore` is
    invisible to a walk rooted above it (`git ls-files` stops at every boundary, the same
    reason `whole_repo_scope` asks each nested tree for its own ignores rather than the
    parent's), so a CMake `_deps`-style throwaway clone nested two levels down needs the
    SAME filtering a one-level-down one already gets — extending the set per level is what
    makes that consistent at any depth rather than only the first.

    BOUNDED BY THE FILESYSTEM, NOT BY A COUNTER. Each call's own walk is capped by
    `_MAX_DEPTH` as always; recursion terminates because real nesting bottoms out at a
    finite number of actual git-tree boundaries, which a vendored dependency graph never
    has many of even when it has more than one.

    @brief Recursively find nested git trees at every depth under one root.
    @return Every nested tree found, unsorted, at any depth.
    @version 2
    """
    direct = sorted(
        p for p in {q.resolve() for q in nested_repo_roots(under)} if not _under_any(p, ignored)
    )
    found = list(direct)
    for tree in direct:
        deeper_ignored = ignored | {p.resolve() for p in _gitignored_paths(tree).paths}
        found.extend(_nested_trees_recursive(tree, deeper_ignored))
    return found

Activity · 6 steps
lines 201–203direct = sorted( p for p in {q.resolve() for q in nested_repo_roots(under)} if not _under_any(p, ignored) )lines 204–204found = list(direct)lines 205–205◇ for tree in directlines 206–206deeper_ignored = ignored | {p.resolve() for p in _gitignored_paths(tree).paths}lines 207–207found.extend(_nested_trees_recursive(tree, deeper_ignored))lines 208–208return found

Flows

_own_ignores

list[Path] clew.scope._own_ignores(Path tree, list[Path] children, set[Path] git_ignored)

One tree's own gitignored paths, minus anything a child tree already excludes.

clew/scope.py:330

Source · 8 lines
def _own_ignores(tree: Path, children: list[Path], git_ignored: set[Path]) -> list[Path]:
    """@brief A tree's own ignores. @return Sorted paths. @version 1"""
    kids = set(children)
    return sorted(
        p for p in git_ignored if p != tree and _under_any(p, {tree}) and not _under_any(p, kids)
    )

Activity · 2 steps
lines 332–332kids = set(children)lines 333–335return sorted( p for p in git_ignored if p != tree and _under_any(p, {tree}) and not _under_any(p, kids) )

Flows

_pruned_dirs

list[Path] clew.scope._pruned_dirs(Path root, set[Path] already, set[Path] nested, list[Path]|None vendored=None)

Dot and cache directories anywhere under a whole-repo root.

clew/scope.py:1039

Source · 56 lines
def _pruned_dirs(
    root: Path,
    already: set[Path],
    nested: set[Path],
    vendored: list[Path] | None = None,
) -> list[Path]:
    """`_skip_dir` is this module's rule for a directory no repo declares and none
    wants indexed. Under a declared root it is applied by pruning the walk that
    builds the roots; the whole-repo root is never walked for its files, so the same
    rule has to reach doxygen as EXCLUDE entries instead.

    @brief Collect the dot/cache directories a whole-repo scope must exclude.
    @return Absolute directory paths.
    @version 4
    """
    found: list[Path] = []
    for dirpath, dirnames, _ in os.walk(root, onerror=_warn_unwalkable):
        here = Path(dirpath)
        ## gh#36. STOP AT A NESTED GIT TREE, taking its own top-level dot directories with us.
        ## Descending them cost ~24.6 s of every build on a repository vendoring boost, opencv
        ## and pcl — the whole 641 MB of boost read to collect `libs/*/.github` entries doxygen
        ## would skip by file pattern anyway, which were also 390-odd of the exclude entries
        ## that overflowed a client's reply limit (gh#37).
        ##
        ## gh#333's REASON IS KEPT, NOT DISCARDED. That change made this walk enter nested trees
        ## deliberately, because the whole-repo tier INDEXES them and their `.git` object store
        ## was the one part of the tree nothing pruned. So the tree's own top level is still
        ## collected — a nested CLONE's `.git` is a directory and is exactly that case — and
        ## only the descent below it stops. What is lost is a dot-directory eleven levels inside
        ## a vendored library, which is the thing that was never worth 641 MB to find.
        ##
        ## MEMBERSHIP, NOT A FILESYSTEM PROBE. The first version of this called `_holds_git_tree`
        ## per directory and cost two stats each — measured +68 ms on 6,000 first-party
        ## directories in a repository with nothing vendored, so the fix charged every repository
        ## for a boundary few have. The caller already holds the answer from gh#24's cached walk.
        if here in nested:
            found.extend(here / name for name in dirnames if _skip_dir(name))
            dirnames[:] = []
            continue
        if len(here.relative_to(root).parts) >= _MAX_DEPTH:
            logger.warning(
                "index_scope: depth limit reached under %s — not pruning below %s", root, here
            )
            _DEPTH_LIMITED.append(here)
            dirnames[:] = []
            continue
        dirnames[:] = _descendable(here, dirnames, already, found)
        ## ON THE WALK THAT ALREADY HAPPENS, never a second one: gh#36 measured this walk at
        ## 24.6 s on a repository vendoring boost, and a separate probe cost +68 ms per 6,000
        ## directories. Only children the walk is about to DESCEND are considered, so an
        ## excluded or ignored tree is never reported as indexed.
        if vendored is not None:
            vendored.extend(here / n for n in dirnames if n.lower() in _VENDORED_DIR_NAMES)
    return found

Activity · 16 steps
lines 1054–1054found: list[Path] = []lines 1055–1055◇ for dirpath, dirnames, _ in os.walk(root, onerror=_warn_unwalkable)lines 1056–1056here = Path(dirpath)lines 1074–1074◇ if here in nestedlines 1075–1075found.extend(here / name for name in dirnames if _skip_dir(name))lines 1076–1076dirnames[:] = []lines 1077–1077continuelines 1078–1078◇ if len(here.relative_to(root).parts) >= _MAX_DEPTHlines 1079–1081logger.warning( "index_scope: depth limit reached under %s — not pruning below %s", root, here )lines 1082–1082_DEPTH_LIMITED.append(here)lines 1083–1083dirnames[:] = []lines 1084–1084continuelines 1085–1085dirnames[:] = _descendable(here, dirnames, already, found)lines 1090–1090◇ if vendored is not Nonelines 1091–1091vendored.extend(here / n for n in dirnames if n.lower() in _VENDORED_DIR_NAMES)lines 1092–1092return found

Flows

_skip_dir

bool clew.scope._skip_dir(str name)

Whether a directory entry should be skipped outright by the walk.

clew/scope.py:513

Source · 5 lines
def _skip_dir(name: str) -> bool:
    """@brief Prune dot-directories and cache directories from the walk."""
    return name.startswith(".") or name in _SKIP_DIR_NAMES

Activity · 1 steps
lines 515–515return name.startswith(".") or name in _SKIP_DIR_NAMES

Flows

_sub_index_name

str clew.scope._sub_index_name(Path nested, Path repo_root)

Name a nested tree by its repo-relative path, safe as a directory component.

clew/scope.py:133

Source · 16 lines
def _sub_index_name(nested: Path, repo_root: Path) -> str:
    """DERIVED FROM THE RELATIVE PATH, NOT THE BASENAME, because two vendored trees can share a
    basename — `a/dep` and `b/dep` — and colliding names would land both on one database, which
    is the wrong-index failure this project has recorded as its most expensive.

    Stability matters as much as uniqueness: nothing persists a mapping from name to database, so
    this derivation IS the mapping, exactly as the path digest is for a whole-repo slug.

    @brief Name one nested tree.
    @return The sub-index name.
    @version 1
    """
    relative = nested.relative_to(repo_root).as_posix()
    return "-".join(part for part in relative.split("/") if part)

Activity · 2 steps
lines 145–145relative = nested.relative_to(repo_root).as_posix()lines 146–146return "-".join(part for part in relative.split("/") if part)

Flows

_under_any

bool clew.scope._under_any(Path path, set[Path] roots)

Whether a path is one of, or inside, any of the given roots.

clew/scope.py:155

Source · 12 lines
def _under_any(path: Path, roots: set[Path]) -> bool:
    """EQUALITY AS WELL AS CONTAINMENT. An exclusion names the directory itself, so testing only
    `parents` would keep a nested tree that IS the excluded path — and `build/_deps/catch2-src`
    excluded exactly is the shape that occurs.

    @brief Test containment against a set of roots.
    @return Whether the path falls under any root.
    @version 1
    """
    return path in roots or any(parent in roots for parent in path.parents)

Activity · 1 steps
lines 164–164return path in roots or any(parent in roots for parent in path.parents)

Flows

_vendored_clause

str clew.scope._vendored_clause(Path root, list[Path] vendored)

Name the indexed trees that look vendored, and how to exclude them.

clew/scope.py:906

Source · 31 lines
def _vendored_clause(root: Path, vendored: list[Path]) -> str:
    """ONLY THE OUTERMOST. `pkg/vendor/foo/vendor` is one vendored tree, not two, so a match
    nested inside another match is dropped before counting — otherwise the count overstates how
    much third-party code there is, and the count is the part a reader acts on.

    BOUNDED, BUT THE TRUE COUNT SURVIVES. gh#37 is why the names are capped; a summary that
    dropped the count would make 400 vendored trees read like 5.

    @brief Disclose vendored-looking indexed trees.
    @return Clause text.
    @version 1
    """
    outer = sorted(v for v in set(vendored) if not any(o != v and o in v.parents for o in vendored))
    if not outer:
        return ""
    rels = [v.relative_to(root).as_posix() for v in outer]
    shown = ", ".join(rels[:_VENDORED_NAMED])
    if len(rels) > _VENDORED_NAMED:
        shown += f" and {len(rels) - _VENDORED_NAMED} more"
    one = len(rels) == 1
    subject = (
        "1 tree that looks vendored IS" if one else f"{len(rels)} trees that look vendored ARE"
    )
    pronoun = "it is" if one else "they are"
    return (
        f" {subject} indexed: {shown}. A committed dependency is excluded by no ignore rule; if "
        f"{pronoun} third-party code, declare `{INDEX_SCOPE_SECTION}` in .clew.yaml to narrow "
        f"the scope (propose_declaration drafts one)."
    )

Activity · 11 steps
lines 918–918outer = sorted(v for v in set(vendored) if not any(o != v and o in v.parents for o in vendored))lines 919–919◇ if not outerlines 920–920return ""lines 921–921rels = [v.relative_to(root).as_posix() for v in outer]lines 922–922shown = ", ".join(rels[:_VENDORED_NAMED])lines 923–923◇ if len(rels) > _VENDORED_NAMEDlines 924–924shown += f" and {len(rels) - _VENDORED_NAMED} more"lines 925–925one = len(rels) == 1lines 926–928subject = ( "1 tree that looks vendored IS" if one else f"{len(rels)} trees that look vendored ARE" )lines 929–929pronoun = "it is" if one else "they are"lines 930–934return ( f" {subject} indexed: {shown}. A committed dependency is excluded by no ignore rule; if " f"{pronoun} third-party code, declare `{INDEX_SCOPE_SECTION}` in .clew.yaml to narrow " f"the scope (propose_declaration drafts one)." )

Flows

_warn_unwalkable

None clew.scope._warn_unwalkable(OSError error)

Report a directory the nested-repository check could not read.

clew/scope.py:1371

Show on the map →

Called by none

Calls none

Source · 9 lines
def _warn_unwalkable(error: OSError) -> None:
    """@brief Warn that a directory was unreadable, so a gap never reads as a pass."""
    logger.warning(
        "index_scope: could not read %s (%s) — it was NOT checked for a nested repository",
        getattr(error, "filename", "?"),
        error,
    )

Activity · 1 steps
lines 1373–1377logger.warning( "index_scope: could not read %s (%s) — it was NOT checked for a nested repository", getattr(error, "filename", "?"), error, )

Flows

declared_scope_rejection

str | None clew.scope.declared_scope_rejection(Path repo_root, dict|None stated=None)

Whether the repo's own index_scope would be REJECTED, without the fallback.

clew/scope.py:635

Source · 22 lines
def declared_scope_rejection(repo_root: Path, stated: dict | None = None) -> str | None:
    """`derive_scope` ABSORBS a rejected declaration into the whole-repo tier — a
    deliberate choice for every INTERNAL pipeline caller, which must always get back a
    usable scope rather than an exception. That absorption is exactly what let an
    excludes-only `.clew.yaml` cost B12_single_rgb a 900s doxygen timeout under a
    vendored tree its own declaration was trying to keep out: the WARNING logged the
    contradiction, and the build proceeded into the widest possible scope anyway.

    This is the SEPARATE, BUILD-TIME check a caller who can still refuse (the MCP refresh
    path, the CLI) runs before committing to a scope — the same relationship
    `stale_code_refusal` has to the build it guards: a guard function, not a change to
    what the guarded thing itself does. `derive_scope`'s own contract is untouched, so
    every existing caller of THAT function keeps its current behaviour exactly.

    @brief Report whether the declared or stated index_scope would be rejected.
    @return The rejection reason, or None.
    @version 1
    """
    declared = _declared_index_scope(Path(repo_root).expanduser().resolve(), stated)
    return str(declared) if isinstance(declared, _Rejected) else None

Activity · 2 steps
lines 653–653declared = _declared_index_scope(Path(repo_root).expanduser().resolve(), stated)lines 654–654return str(declared) if isinstance(declared, _Rejected) else None

Requirements

REQ-DDB-CONFIG-001

Flows

declared_sub_index_excludes

tuple[str, ...] clew.scope.declared_sub_index_excludes(Path repo_root, str name, tuple[str,...]|Callable[[], tuple[str,...]] buildable, dict|None stated=None)

Excludes the parent repository declares for one of its named sub-indexes.

clew/scope.py:556

Source · 73 lines
def declared_sub_index_excludes(
    repo_root: Path,
    name: str,
    buildable: tuple[str, ...] | Callable[[], tuple[str, ...]],
    stated: dict | None = None,
) -> tuple[str, ...]:
    """gh#39. A REPOSITORY VENDORING A TREE THAT VENDORS NINE MORE could say nothing about it.
    `_sub_index_scope` builds a vendored sub-index from its `roots` alone; a `.clew.yaml` inside
    the nested tree is never read, because discovery is rooted at the parent and the tree is
    upstream's anyway. So a 641 MB boost, a 217 MB opencv and a 142 MB pcl were indexed as part
    of their parent and the build could not finish inside the 900 s doxygen cap.

    THE PARENT'S DECLARATION RATHER THAN CALL METADATA, which was the alternative: excludes
    stashed in the sub-index's own database on its first build and replayed afterwards. That
    puts the value somewhere only the operator who made the call can see, so two operators of
    one commit hold different indexes — the shape gh#352 rejected, and the reason the
    `options.*` tier rows exist at all. A declaration is durable, reviewable in the same diff as
    the code, and readable by everyone who clones the repository.

    EVERY DECLARED NAME IS VALIDATED, not just the one being built. A block naming a tree this
    repository does not vendor would otherwise sit in the file doing nothing while its author
    believed it was trimming a build — this project's most repeated defect, and the reason the
    keys inside an `index_scope` are checked as well as the section itself.

    A STATED BLOCK REPLACES THE DECLARED ONE, tier 1 over tier 2, exactly as every other option
    resolves — and replacing rather than adding is what lets an operator WITHDRAW a declared
    exclude they disagree with. `declared_scope_rejection` takes `stated` for the same reason
    one section over: a declaration section that could only be written into the target's tree is
    unreachable for an operator who does not own it.

    `buildable` MAY BE A CALLABLE, resolved only when there is a block to validate. The names
    come from the full split, which walks every vendored tree, and most repositories declare no
    `sub_indexes:` block, so a first-party refresh should not pay for a check with nothing to check.

    @brief Read the declared or stated excludes for one sub-index, refusing what cannot apply.
    @return The excludes, or ().
    @version 3
    """
    from .declaration import SECTION_SUB_INDEXES, load_declaration

    declared = (
        stated if stated is not None else load_declaration(repo_root).get(SECTION_SUB_INDEXES)
    )
    if not declared:
        return ()
    if not isinstance(declared, dict):
        raise ValueError(
            f"{SECTION_SUB_INDEXES} is {type(declared).__name__}, not a mapping of sub-index "
            f"name to its scope."
        )
    if callable(buildable):
        buildable = buildable()
    unknown = sorted(str(k) for k in declared if str(k) not in buildable)
    if unknown:
        raise ValueError(
            f"{SECTION_SUB_INDEXES} names {', '.join(repr(u) for u in unknown)}, which this "
            f"repository does not derive. Buildable: {', '.join(repr(b) for b in buildable)}. "
            f"Refusing rather than ignoring it, so a block that trims nothing cannot read as "
            f"one that does."
        )
    entry = declared.get(name) or {}
    if not isinstance(entry, dict):
        raise ValueError(f"{SECTION_SUB_INDEXES}.{name} is {type(entry).__name__}, not a mapping.")
    bad_keys = sorted(str(k) for k in entry if str(k) not in _SUB_INDEX_KEYS)
    if bad_keys:
        raise ValueError(
            f"{SECTION_SUB_INDEXES}.{name} carries {', '.join(repr(k) for k in bad_keys)}; only "
            f"{', '.join(sorted(_SUB_INDEX_KEYS))} is accepted. A sub-index's roots are its "
            f"tree, derived from the repository, and are not restatable here."
        )
    return tuple(str(p) for p in (entry.get("excludes") or []))

Activity · 18 steps
lines 594–594from .declaration import SECTION_SUB_INDEXES, load_declarationlines 596–598declared = ( stated if stated is not None else load_declaration(repo_root).get(SECTION_SUB_INDEXES) )lines 599–599◇ if not declaredlines 600–600return ()lines 601–601◇ if not isinstance(declared, dict)lines 602–605raise ValueError( f"{SECTION_SUB_INDEXES} is {type(declared).__name__}, not a mapping of sub-index " f"name to its scope." )lines 606–606◇ if callable(buildable)lines 607–607buildable = buildable()lines 608–608unknown = sorted(str(k) for k in declared if str(k) not in buildable)lines 609–609◇ if unknownlines 610–615raise ValueError( f"{SECTION_SUB_INDEXES} names {', '.join(repr(u) for u in unknown)}, which this " f"repository does not derive. Buildable: {', '.join(repr(b) for b in buildable)}. " f"Refusing rather than ignoring it, so a block that trims nothing cannot read as " f"one that does." )lines 616–616entry = declared.get(name) or {}lines 617–617◇ if not isinstance(entry, dict)lines 618–618raise ValueError(f"{SECTION_SUB_INDEXES}.{name} is {type(entry).__name__}, not a mapping.")lines 619–619bad_keys = sorted(str(k) for k in entry if str(k) not in _SUB_INDEX_KEYS)lines 620–620◇ if bad_keyslines 621–625raise ValueError( f"{SECTION_SUB_INDEXES}.{name} carries {', '.join(repr(k) for k in bad_keys)}; only " f"{', '.join(sorted(_SUB_INDEX_KEYS))} is accepted. A sub-index's roots are its " f"tree, derived from the repository, and are not restatable here." )lines 626–626return tuple(str(p) for p in (entry.get("excludes") or []))

Requirements

REQ-DDB-CONFIG-001

Flows

dependency_roots

list[Path] clew.scope.dependency_roots(Path repo_root)

Nested trees the repo itself DECLARES as dependencies (submodule gitlinks).

clew/scope.py:856

Show on the map →

Called by external_roots

Calls _is_dependency_of_parent, nested_repo_roots

Source · 18 lines
def dependency_roots(repo_root: Path) -> list[Path]:
    """THE SUBSET OF `nested_repo_roots` THE PARENT OWNS UP TO. Two questions were being
    answered by one predicate until gh#352 half 2: descent (does this tree hide its own build
    output from its parent?) and ownership (is this somebody else's code?). Both walks are the
    same walk; only the filter differs, so they share `_nested_repos_under` and diverge here.

    Descent must see every separate git tree, including a developer's stray clone, because
    `git ls-files` stops at any tree boundary. Ownership must see only what the repository
    committed as a gitlink — see `_is_dependency_of_parent` for the measurement that forced
    the split.

    @brief List the nested trees the repo declares as dependencies.
    @return Absolute paths of dependency trees.
    @version 1
    """
    return [n for n in nested_repo_roots(repo_root) if _is_dependency_of_parent(n)]

Activity · 1 steps
lines 871–871return [n for n in nested_repo_roots(repo_root) if _is_dependency_of_parent(n)]

Requirements

REQ-DDB-CONFIG-001

derive_scope

DerivedScope clew.scope.derive_scope(Path repo_root, dict|None stated=None)

Resolve the index scope: a declared index_scope, else the whole repository.

clew/scope.py:662

Source · 39 lines
def derive_scope(repo_root: Path, stated: dict | None = None) -> DerivedScope:
    """Read the declaration and hand back its roots. Every failure mode — no config,
    no `index_scope:` section, no declared root that exists — falls through to
    `whole_repo_scope`, which carries the REASON, so the caller can log which scope
    was used and why. Nothing is ever silently guessed.

    THE DOXYFILE FALLBACK IS GONE (gh#333). It used to sit here and name no roots at
    all, which handed the indexed tree to the Doxyfile's own INPUT — a documentation
    target standing in for a reasoning boundary. `_doxyfile_fallback`'s one surviving
    job, saying WHERE a declaration was looked for, is now a clause inside the
    whole-repo reason.

    NO CONTAINMENT PASS. Every scope this module handed out used to run through
    `_with_nested_repos_contained`, which cut nested git trees out of it. They are
    now indexed and tagged instead (`external.py`), so the choke point was removed
    rather than bypassed — a containment call left in place with its callers removed
    is a safety property that reads as enforced and is not.

    @brief Resolve INPUT roots from the repo's own index-scope declaration.
    @return The declared scope, or the whole-repo tier.
    @version 9
    """
    ## CLEARED HERE BECAUSE THIS IS THE SINGLE ENTRY POINT, so `depth_limited_paths()` after a
    ## derivation describes THAT derivation and not an accumulation across several. The build
    ## derives more than once — `_scope_provenance` re-derives on the whole-repo tier — and a
    ## record that grew across them would report the same directory two or three times and read
    ## as a wider problem than exists.
    _DEPTH_LIMITED.clear()
    root = Path(repo_root).expanduser().resolve()
    declared = _declared_index_scope(root, stated)
    if isinstance(declared, _Rejected):
        ## SAID OUT LOUD, not only returned. The contradiction gh#5 reports is between two LOG
        ## lines, so the correction has to reach the log too — a reason carried only in the
        ## payload leaves the WARNING still claiming absence.
        logger.warning("index_scope: %s", declared)
        return whole_repo_scope(root, rejected=str(declared))
    return declared or whole_repo_scope(root)

Activity · 7 steps
lines 689–689_DEPTH_LIMITED.clear()lines 690–690root = Path(repo_root).expanduser().resolve()lines 691–691declared = _declared_index_scope(root, stated)lines 692–692◇ if isinstance(declared, _Rejected)lines 696–696logger.warning("index_scope: %s", declared)lines 697–697return whole_repo_scope(root, rejected=str(declared))lines 698–698return declared or whole_repo_scope(root)

Requirements

REQ-DDB-CONFIG-001

Flows

derive_scope_logged

DerivedScope clew.scope.derive_scope_logged(Path repo_root, dict|None stated=None)

Derive a scope and log which scope was used and why.

clew/scope.py:1464

Source · 25 lines
def derive_scope_logged(repo_root: Path, stated: dict | None = None) -> DerivedScope:
    """Fail SAFE and LOUD: a declared derivation logs its roots at INFO, the
    whole-repo default logs its reason at WARNING so a boundary nobody chose is never
    mistaken for one somebody did.

    The undeclared branch no longer says "falling back to the Doxyfile INPUT", which
    since gh#333 would be a checkable and wrong statement about what got indexed —
    the same defect class as stamping `source: doxyfile` on a whole-repo build.

    @brief Derive the index scope with an explicit log line.
    @return The derived (or whole-repo) scope.
    @version 6
    """
    scope = derive_scope(repo_root, stated)
    if scope.is_derived():
        logger.info(
            "scope: declared — %s — %d INPUT root(s), %d EXCLUDE(s): %s",
            scope.reason,
            len(scope.roots),
            len(scope.excludes),
            ", ".join(str(p) for p in scope.roots),
        )
    else:
        logger.warning("scope: indexing the WHOLE repository — %s", scope.reason)
    return scope

1 more lines, not shown

Activity · 6 steps
lines 1477–1477scope = derive_scope(repo_root, stated)lines 1478–1478◇ if scope.is_derived()lines 1479–1485logger.info( "scope: declared — %s — %d INPUT root(s), %d EXCLUDE(s): %s", scope.reason, len(scope.roots), len(scope.excludes), ", ".join(str(p) for p in scope.roots), )lines 1486–1486elselines 1487–1487logger.warning("scope: indexing the WHOLE repository — %s", scope.reason)lines 1488–1488return scope

Requirements

REQ-DDB-CONFIG-001

derive_sub_indexes

list[SubIndex] clew.scope.derive_sub_indexes(Path repo_root)

Split a repository into first-party and per-nested-tree indexes, at any depth.

clew/scope.py:241

Source · 82 lines
def derive_sub_indexes(repo_root: Path) -> list[SubIndex]:
    """EMPTY MEANS "DO NOT SPLIT", and that is the compatibility contract. A repository with
    nothing vendored must keep building to one index under the slug it already has — splitting it
    would allocate a new slug and strand the index on disk, whose symptom is "no database has been
    built" against a perfectly good one.

    REUSES `nested_repo_roots`, which the pipeline already runs on every build and which handles
    BOTH on-disk shapes of a nested repository: a clone's `.git` directory and a submodule's
    `gitdir:` pointer FILE. That distinction is not academic — a detector seeing only directories
    finds nested clones and silently skips every submodule, which is the case this split exists
    for.

    N LEVELS DEEP, NOT ONE. Field-reported: a vendored dependency that itself vendors several
    more (a 1.2GB tree carrying boost, opencv, pcl and six others as its own submodules) was
    getting ONE sub-index for the whole thing, dominated entirely by code none of it wrote.
    Every nested tree found anywhere in the repository — at any depth — gets its own name and
    its own sub-index; each one's `excludes` names exactly its own direct children, the same
    relationship first-party already has to depth 1, so building it does not silently swallow
    what belongs one level further down.

    @brief Derive the sub-index split from nested git trees, at any depth.
    @return The split, or [] to build the repository whole.
    @version 6
    """
    root = Path(repo_root).expanduser().resolve()
    ## THE SPLIT USES THE BUILD'S OWN RULE, and skipping this cost a real target twenty minutes.
    ## `nested_repo_roots` walks the WHOLE tree, so it finds every git clone on disk — including
    ## CMake FetchContent output under `build/`, which is a genuine clone and pure throwaway.
    ## Driving a real repository produced sub-indexes named `build-coverage-_deps-catch2-src`,
    ## `build-dev-_deps-httplib-src` and six more, each being indexed in turn, while every
    ## fixture test passed.
    ##
    ## `whole_repo_scope` already computes what the build excludes — git-ignored paths, plus each
    ## nested tree's own ignores, which `git ls-files` cannot see through. Reusing it is what
    ## keeps the split and the build agreeing about what the repository contains; deriving a
    ## second rule here would leave the split free to index trees the build would never touch,
    ## and the split is the one nobody looks at.
    ignored = {p.resolve() for p in whole_repo_scope(root).excludes}
    nested = sorted(set(_nested_trees_recursive(root, ignored)))
    if not nested:
        return []
    ## EACH TREE EXCLUDES ONLY ITS OWN DIRECT CHILDREN, not every deeper descendant — a
    ## grandchild is already excluded from ITS OWN parent's build, which is the tree one level
    ## up from it, not from every ancestor above that.
    children_of: dict[Path, list[Path]] = {}
    for tree in nested:
        parent = _direct_parent(tree, root, nested)
        children_of.setdefault(parent, []).append(tree)

    ## gh#23. A DERIVED SCOPE IS NOT A CURATED ONE, and that is why it must carry the ignores.
    ## A sub-index builds through a DECLARED `index_scope`, which the resolver takes at its word
    ## and never walks — correct for a human-written `.clew.yaml`, where walking would overrule
    ## the author. But THIS declaration is machine-derived, so nobody ever told it to skip the
    ## vendored tree's own `build/`, and a vendored dependency shipping generated headers there
    ## had `search` resolving symbols into throwaway output.
    ##
    ## ASKS GIT, NOT THE MERGED EXCLUDE SET. `ignored` above is gitignored paths PLUS the dot
    ## and cache directories `_pruned_dirs` adds, and folding those in would put `.git` into
    ## every sub-index's excludes — harmless but untrue to what this is for, and it broke the
    ## split test's own statement that a tree with no ignores of its own excludes nothing.
    ## What belongs here is exactly what the tree's own git says to ignore.
    ##
    ## Per tree rather than per repository, so this stays proportional to the number of
    ## vendored trees rather than repeating the whole-tree walk gh#24 just removed.
    git_ignored = {p.resolve() for p in _gitignored_paths(root).paths}
    for tree in nested:
        git_ignored |= {p.resolve() for p in _gitignored_paths(tree).paths}

    first = _first_party(root, children_of.get(root, []), git_ignored)
    others = []
    for tree in nested:
        kids = children_of.get(tree, [])
        others.append(
            SubIndex(
                name=_sub_index_name(tree, root),
                roots=(tree,),
                excludes=tuple(kids + _own_ignores(tree, kids, git_ignored)),
            )
        )
    return [first] + others

Activity · 18 steps
lines 265–265root = Path(repo_root).expanduser().resolve()lines 278–278ignored = {p.resolve() for p in whole_repo_scope(root).excludes}lines 279–279nested = sorted(set(_nested_trees_recursive(root, ignored)))lines 280–280◇ if not nestedlines 281–281return []lines 285–285children_of: dict[Path, list[Path]] = {}lines 286–286◇ for tree in nestedlines 287–287parent = _direct_parent(tree, root, nested)lines 288–288children_of.setdefault(parent, []).append(tree)lines 305–305git_ignored = {p.resolve() for p in _gitignored_paths(root).paths}lines 306–306◇ for tree in nestedlines 307–307git_ignored |= {p.resolve() for p in _gitignored_paths(tree).paths}lines 309–309first = _first_party(root, children_of.get(root, []), git_ignored)lines 310–310others = []lines 311–311◇ for tree in nestedlines 312–312kids = children_of.get(tree, [])lines 313–319others.append( SubIndex( name=_sub_index_name(tree, root), roots=(tree,), excludes=tuple(kids + _own_ignores(tree, kids, git_ignored)), ) )lines 320–320return [first] + others

Requirements

REQ-DDB-INDEX-002

Flows

first_party_sub_index

SubIndex | None clew.scope.first_party_sub_index(Path repo_root)

The first-party sub-index of a split repository, without walking any vendored tree.

clew/scope.py:367

Source · 27 lines
def first_party_sub_index(repo_root: Path) -> SubIndex | None:
    """gh#48's "<10 s nominally", on the repository that set the bar. `derive_sub_indexes`
    recurses INTO every vendored tree to find the trees nested inside it: 24.6 s per pass on a
    repository vendoring boost, opencv and pcl. A first-party refresh paid for four passes. None
    of that recursion can change first-party's scope. First-party excludes its DIRECT nested
    trees whole, so what lies inside them is irrelevant, and the ignore paths a vendored tree
    contributes all sit under a direct child and are filtered out.

    So this reads only what the full derivation's first entry reads: the root's non-ignored
    direct nested trees, from a walk that stops at every nested boundary, and the root's own git
    ignores. `tests/test_first_party_walk.py` pins equality with the full derivation on a
    depth-2 fixture with ignored clones on both sides of a boundary.

    @brief Derive only the first-party sub-index, cheaply.
    @return The SubIndex, or None when the repository has no nested trees.
    @version 2
    """
    root = Path(repo_root).expanduser().resolve()
    ignored = {p.resolve() for p in whole_repo_scope(root).excludes}
    direct = sorted(
        p for p in {q.resolve() for q in nested_repo_roots(root)} if not _under_any(p, ignored)
    )
    if not direct:
        return None
    return _first_party(root, direct, {p.resolve() for p in _gitignored_paths(root).paths})

Activity · 6 steps
lines 384–384root = Path(repo_root).expanduser().resolve()lines 385–385ignored = {p.resolve() for p in whole_repo_scope(root).excludes}lines 386–388direct = sorted( p for p in {q.resolve() for q in nested_repo_roots(root)} if not _under_any(p, ignored) )lines 389–389◇ if not directlines 390–390return Nonelines 391–391return _first_party(root, direct, {p.resolve() for p in _gitignored_paths(root).paths})

Requirements

REQ-DDB-INDEX-002

Flows

is_derived

bool clew.scope.DerivedScope.is_derived(self)

Whether this scope should override the Doxyfile's INPUT.

clew/scope.py:503

Source · 5 lines
    def is_derived(self) -> bool:
        """@brief Whether a declaration produced usable roots."""
        return self.source == SOURCE_DECLARED and bool(self.roots)

Activity · 1 steps
lines 505–505return self.source == SOURCE_DECLARED and bool(self.roots)

Requirements

REQ-DDB-CONFIG-001

Flows

nested_repo_roots

list[Path] clew.scope.nested_repo_roots(Path repo_root)

Directories holding their own git tree anywhere under a repo root.

clew/scope.py:819

Source · 32 lines
def nested_repo_roots(repo_root: Path) -> list[Path]:
    """THE SAME WALK THAT USED TO EXCLUDE THESE TREES, made public so gh#335 can tag
    them instead. The pipeline already computed this answer on every build and threw
    it away into a WARNING — the identical shape as the scope provenance that gh#319
    persisted, and as the macro hop doxygen was already emitting.

    A directory holding `.git` is a DIFFERENT repository. That is the ONLY test, and
    the rule is deliberately not name-based: `vendor/` and `third_party/` are
    conventions, not facts, and a copied-in third-party header with no git tree of its
    own IS first party — the repo committed it and owns it, so its metrics should say
    so.

    The root ITSELF is never nested, so a root that IS a repository does not report
    itself.

    SHARED ACROSS ONE BUILD (gh#24) when `nested_tree_cache` is active, because three
    callers ask this same question about the same root and a walk of a large tree is the
    dominant cost of an otherwise-incremental refresh. Keyed on the RESOLVED root so two
    callers spelling the same tree differently still share the answer.

    @brief Find the nested git trees under a repo root.
    @return Absolute paths of nested repository directories.
    @version 2
    """
    root = Path(repo_root).expanduser().resolve()
    if _NESTED_CACHE is None:
        return _nested_repos_under(root)
    if root not in _NESTED_CACHE:
        _NESTED_CACHE[root] = _nested_repos_under(root)
    return _NESTED_CACHE[root]

Activity · 6 steps
lines 843–843root = Path(repo_root).expanduser().resolve()lines 844–844◇ if _NESTED_CACHE is Nonelines 845–845return _nested_repos_under(root)lines 846–846◇ if root not in _NESTED_CACHElines 847–847_NESTED_CACHE[root] = _nested_repos_under(root)lines 848–848return _NESTED_CACHE[root]

Requirements

REQ-DDB-CONFIG-001

Flows

nested_tree_cache

Iterator[None] clew.scope.nested_tree_cache()

Share one nested-tree walk across everything a single build asks.

clew/scope.py:794

Source · 20 lines
def nested_tree_cache() -> Iterator[None]:
    """REENTRANT, AND THE OUTERMOST WINS. `build_index` opens one; a caller that has already
    opened its own must not have the inner exit clear the cache out from under the rest of
    the build, so an inner activation is inert rather than a second scope.

    @brief Cache nested-tree walks for the duration of one build.
    @return Generator yielding once.
    @version 1
    """
    global _NESTED_CACHE
    if _NESTED_CACHE is not None:
        yield
        return
    _NESTED_CACHE = {}
    try:
        yield
    finally:
        _NESTED_CACHE = None

Activity · 7 steps
lines 803–803global _NESTED_CACHElines 804–804◇ if _NESTED_CACHE is not Nonelines 805–805yieldlines 806–806returnlines 807–807_NESTED_CACHE = {}lines 808–808trylines 809–809yield

Requirements

REQ-DDB-CONFIG-001

Flows

normalize_scope

str | None clew.scope.normalize_scope(str|None scope)

Resolve a caller's scope spelling to the value this codebase records.

clew/scope.py:464

Source · 13 lines
def normalize_scope(scope: str | None) -> str | None:
    """NORMALIZING IS NOT VALIDATING, and the distinction is load-bearing. The refusal for an
    unknown scope lives where the Doxyfile is resolved and already names the two values it
    accepts with a reason; mapping an unknown value onto a default here would build a boundary
    the caller never asked for and then report success — the silent-success failure this
    release spent its blockers on.

    @brief Map the `from-declaration` alias onto the recorded `from-guard`.
    @return The recorded spelling, or the input unchanged.
    """
    return SCOPE_FROM_GUARD if scope == SCOPE_FROM_DECLARATION else scope

Activity · 1 steps
lines 474–474return SCOPE_FROM_GUARD if scope == SCOPE_FROM_DECLARATION else scope

Requirements

REQ-DDB-CONFIG-001

whole_repo_scope

DerivedScope clew.scope.whole_repo_scope(Path repo_root, str rejected="")

The whole repository as one INPUT root, less only what git ignores.

clew/scope.py:711

Source · 64 lines
def whole_repo_scope(repo_root: Path, rejected: str = "") -> DerivedScope:
    """THE DEFAULT TIER since gh#333, not the last resort: reached whenever a repo
    declares no `index_scope:`, whether or not it ships a Doxyfile.

    Its single root is the whole repository, so a foreign clone parked anywhere
    inside is inside it BY CONSTRUCTION — and since gh#333 that is the intent rather
    than the hazard it used to be. entropic wraps llama.cpp; a `chain_trace` that
    stopped at the submodule boundary said "this call leaves the repo" when it could
    have said what the call does. `external.py` tags those rows so the two codebases
    are still told apart in an answer.

    The subtractions are what the repo has already said about itself — the paths git
    ignores, on BOTH sides of every submodule boundary — plus the dot and cache
    directories no repo restates. The doxygen-guard gate is NOT read here: the gate
    answers what must be DOCUMENTED, and this tier exists because that is a different
    question from what should be indexed.

    @brief Build the whole-repo index scope.
    @return The whole-repo scope.
    @version 5
    """
    root = Path(repo_root).expanduser().resolve()
    sweep = _gitignored_paths(root)
    ignored = list(sweep.paths)
    ## A SUBMODULE'S OWN `.gitignore` IS INVISIBLE TO THE PARENT. `git ls-files` stops
    ## at a submodule boundary, so the sweep above reports nothing inside a nested
    ## tree — and a nested tree is now INDEXED rather than excluded, which is exactly
    ## when its build output starts to matter. Asked per nested repo instead.
    ##
    ## gh#36. THE SAME LIST BOUNDS THE PRUNE WALK BELOW, which is what makes stopping at a
    ## nested tree free. `nested_repo_roots` is the walk gh#24 cached per build and this call
    ## site already paid for it; probing each directory for a `.git` instead cost two stats per
    ## directory everywhere — measured +68 ms on 6,000 first-party directories in a repository
    ## that vendors nothing, which is most of them.
    nested_trees = nested_repo_roots(root)
    for nested in nested_trees:
        ignored.extend(_gitignored_paths(nested).paths)
    vendored: list[Path] = []
    excludes = [
        *ignored,
        *_pruned_dirs(root, set(ignored), {p.resolve() for p in nested_trees}, vendored),
    ]
    return DerivedScope(
        source=SOURCE_WHOLE_REPO,
        ## PRESENT-BUT-UNUSABLE IS NOT ABSENT (gh#5). A declaration carrying an `index_scope:`
        ## that yields no roots used to land here and report "no index_scope is declared" — while
        ## the loader had already logged "<file> declares index_scope" seconds earlier. A reporter
        ## got both lines from one build and could not tell whether to fix their YAML or file a
        ## bug; only `propose_declaration` settled it, and nobody reaches for that after a build
        ## reports success. `rejected` REPLACES the absence clause, never appends to it.
        reason=(
            (rejected if rejected else f"no {INDEX_SCOPE_SECTION} is declared for this repo")
            + f" — {_declaration_note(root)} — so the whole repository is the "
            f"index scope, INCLUDING any nested git trees, {_ignore_clause(sweep)}"
            f"{_vendored_clause(root, vendored)} "
            f"A Doxyfile, if the repo ships one, still "
            f"supplies ALIASES and PREDEFINED but no longer supplies the INPUT: that is "
            f"a documentation target, not a reasoning boundary. {_declaration_advice()}"
        ),
        roots=(root,),
        excludes=tuple(excludes),
    )

Activity · 9 steps
lines 732–732root = Path(repo_root).expanduser().resolve()lines 733–733sweep = _gitignored_paths(root)lines 734–734ignored = list(sweep.paths)lines 745–745nested_trees = nested_repo_roots(root)lines 746–746◇ for nested in nested_treeslines 747–747ignored.extend(_gitignored_paths(nested).paths)lines 748–748vendored: list[Path] = []lines 749–752excludes = [ *ignored, *_pruned_dirs(root, set(ignored), {p.resolve() for p in nested_trees}, vendored), ]lines 753–772return DerivedScope( source=SOURCE_WHOLE_REPO, ## PRESENT-BUT-UNUSABLE IS NOT ABSENT (gh#5). A declaration carrying an `index_scope:` ## that yields no roots used to land here and report "no index_scope is declared" — while ## the loader had already logged "<file> declares index_scope" seconds earlier. A reporter ## got both lines from one build and could not tell whether to fix their YAML or file a ## bug; only `propose_declaration` settled it, and nobody reaches for that after a build ## reports success. `rejected` REPLACES the absence clause, never appends to it. reason=( (rejected if rejected else f"no {INDEX_SCOPE_SECTION} is declared for this repo") + f" — {_declaration_note(root)} — so the whole repository is the " f"index scope, INCLUDING any nested git trees, {_ignore_clause(sweep)}" f"{_vendored_clause(root, vendored)} " f"A Doxyfile, if the repo ships one, still " f"supplies ALIASES and PREDEFINED but no longer supplies the INPUT: that is " f"a documentation target, not a reasoning boundary. {_declaration_advice()}" ), roots=(root,), excludes=tuple(excludes), )

Requirements

REQ-DDB-CONFIG-001

Flows