notindexed.py

clew/propose/notindexed.py

Report what is NOT indexed — and refuse to emit an `index_scope:` block.

_as_dirs

list[NotIndexedDir] clew.propose.notindexed._as_dirs(dict[str, dict] buckets)

Convert the grouping buckets into sorted NotIndexedDir records.

clew/propose/notindexed.py:210

Source · 17 lines
def _as_dirs(buckets: dict[str, dict]) -> list[NotIndexedDir]:
    """@brief Freeze the candidate-directory accumulator."""
    return sorted(
        (
            NotIndexedDir(
                name=name,
                files=len(data["files"]),
                definitions=data["defs"],
                shadowed=tuple(sorted(data["shadowed"])),
                entry_seeds=data["seeds"],
            )
            for name, data in buckets.items()
        ),
        key=lambda d: (-d.definitions, d.name),
    )

Activity · 1 steps
lines 212–224return sorted( ( NotIndexedDir( name=name, files=len(data["files"]), definitions=data["defs"], shadowed=tuple(sorted(data["shadowed"])), entry_seeds=data["seeds"], ) for name, data in buckets.items() ), key=lambda d: (-d.definitions, d.name), )

Flows

_dir_lines

list[str] clew.propose.notindexed._dir_lines(Sequence[NotIndexedDir] dirs)

One report line per candidate directory, with its hazards.

clew/propose/notindexed.py:303

Source · 21 lines
def _dir_lines(dirs: Sequence[NotIndexedDir]) -> list[str]:
    """@brief Describe each out-of-scope directory and what indexing it would do."""
    if not dirs:
        return ["No git-tracked source sits outside the derived index scope."]
    lines = [
        f"{len(dirs)} director(ies) hold git-tracked source outside it. Largest, with hazards:"
    ]
    for entry in dirs[:_MAX_DIRS]:
        hazards = []
        if entry.shadowed:
            hazards.append(
                f"{len(entry.shadowed)} symbol(s) SHADOW in-scope definitions "
                f"({', '.join(entry.shadowed[:3])})"
            )
        if entry.entry_seeds:
            hazards.append(f"{entry.entry_seeds} reachability entry-pattern match(es)")
        lines.append(
            f"  {entry.name:<12} {entry.files} file(s) / {entry.definitions} definition(s)"
            + (f" — {'; '.join(hazards)}" if hazards else "")
        )
    return lines

1 more lines, not shown

Activity · 11 steps
lines 305–305◇ if not dirslines 306–306return ["No git-tracked source sits outside the derived index scope."]lines 307–309lines = [ f"{len(dirs)} director(ies) hold git-tracked source outside it. Largest, with hazards:" ]lines 310–310◇ for entry in dirs[:_MAX_DIRS]lines 311–311hazards = []lines 312–312◇ if entry.shadowedlines 313–316hazards.append( f"{len(entry.shadowed)} symbol(s) SHADOW in-scope definitions " f"({', '.join(entry.shadowed[:3])})" )lines 317–317◇ if entry.entry_seedslines 318–318hazards.append(f"{entry.entry_seeds} reachability entry-pattern match(es)")lines 319–322lines.append( f" {entry.name:<12} {entry.files} file(s) / {entry.definitions} definition(s)" + (f" — {'; '.join(hazards)}" if hazards else "") )lines 323–323return lines

Flows

candidate_dirs

list[NotIndexedDir] clew.propose.notindexed.candidate_dirs(Context ctx, frozenset[str]|None tracked)

Group out-of-scope definitions into candidate directories.

clew/propose/notindexed.py:183

Source · 22 lines
def candidate_dirs(ctx: Context, tracked: frozenset[str] | None) -> list[NotIndexedDir]:
    """@brief Summarise the source that sits outside the derived index scope."""
    in_scope_names = {
        name for name, defs in ctx.corpus.defs.items() if any(d.in_scope for d in defs)
    }
    buckets: dict[str, dict] = {}
    for name, defs in ctx.corpus.defs.items():
        for fdef in defs:
            if fdef.in_scope or (tracked is not None and fdef.rel_path not in tracked):
                continue
            bucket = buckets.setdefault(
                fdef.rel_path.split("/")[0],
                {"files": set(), "defs": 0, "shadowed": set(), "seeds": 0},
            )
            bucket["files"].add(fdef.rel_path)
            bucket["defs"] += 1
            bucket["seeds"] += 1 if seeds_reachability(name) else 0
            if name in in_scope_names:
                bucket["shadowed"].add(name)
    return _as_dirs(buckets)

Activity · 13 steps
lines 185–187in_scope_names = { name for name, defs in ctx.corpus.defs.items() if any(d.in_scope for d in defs) }lines 188–188buckets: dict[str, dict] = {}lines 189–189◇ for name, defs in ctx.corpus.defs.items()lines 190–190◇ for fdef in defslines 191–191◇ if fdef.in_scope or (tracked is not None and fdef.rel_path not in tracked)lines 192–192continuelines 193–196bucket = buckets.setdefault( fdef.rel_path.split("/")[0], {"files": set(), "defs": 0, "shadowed": set(), "seeds": 0}, )lines 197–197bucket["files"].add(fdef.rel_path)lines 198–198bucket["defs"] += 1lines 199–199bucket["seeds"] += 1 if seeds_reachability(name) else 0lines 200–200◇ if name in in_scope_nameslines 201–201bucket["shadowed"].add(name)lines 202–202return _as_dirs(buckets)

Requirements

REQ-DDB-CONFIG-001

Flows

cross_section_conflicts

tuple[str, ...] clew.propose.notindexed.cross_section_conflicts(Sequence[SectionProposal] sections, Sequence[NotIndexedDir] dirs)

Warn when a proposed section's evidence reaches outside the index.

clew/propose/notindexed.py:233

Source · 29 lines
def cross_section_conflicts(
    sections: Sequence[SectionProposal], dirs: Sequence[NotIndexedDir]
) -> tuple[str, ...]:
    """The proposals above are computed from the CURRENT scope. If an owner
    widens the index, the accessor families and spawn censuses change — so a
    proposal whose own evidence already mentions a not-indexed directory has to
    say that its numbers are conditional.

    @brief Cross-warn when a proposal's evidence crosses the scope boundary.
    @version 1
    """
    names = {d.name for d in dirs}
    hits = {
        line.strip()
        for section in sections
        for entry in section.entries
        for line in entry.evidence
        if "OUTSIDE the index scope" in line
    }
    if not hits or not names:
        return ()
    return (
        "CONFLICT: a proposal above has call sites outside the index scope. "
        "If you widen the index, RE-RUN this command — the proposals are "
        "computed from the current scope and will change.",
        *sorted(hits),
    )

Activity · 5 steps
lines 244–244names = {d.name for d in dirs}lines 245–251hits = { line.strip() for section in sections for entry in section.entries for line in entry.evidence if "OUTSIDE the index scope" in line }lines 252–252◇ if not hits or not nameslines 253–253return ()lines 254–259return ( "CONFLICT: a proposal above has call sites outside the index scope. " "If you widen the index, RE-RUN this command — the proposals are " "computed from the current scope and will change.", *sorted(hits), )

Requirements

REQ-DDB-CONFIG-001

Flows

report_not_indexed

SectionProposal clew.propose.notindexed.report_not_indexed(Context ctx, Sequence[SectionProposal] sections)

Build the report-only index_scope section.

clew/propose/notindexed.py:268

Source · 30 lines
def report_not_indexed(ctx: Context, sections: Sequence[SectionProposal]) -> SectionProposal:
    """@brief Report out-of-scope source without proposing any index_scope YAML."""
    tracked = tracked_files(ctx.repo_root)
    dirs = candidate_dirs(ctx, tracked)
    notes = [
        f"Your derived scope is {ctx.scope.source} — {len(ctx.scope.roots)} root(s), "
        f"{len(ctx.scope.excludes)} exclude(s), covering "
        f"{ctx.corpus.files_in_scope} of {ctx.corpus.files_parsed} parsed source files.",
        *_dir_lines(dirs),
        _REPLACE_SEMANTICS,
        *cross_section_conflicts(sections, dirs),
    ]
    if tracked is None:
        notes.append(
            "NOTE: `git ls-files` was unavailable, so vendored/submodule trees "
            "could not be excluded from the directory list above."
        )
    return SectionProposal(
        name=INDEX_SCOPE_SECTION,
        status=SectionStatus.REPORT_ONLY,
        reason="NOT PROPOSED BY DESIGN — see the note below (report only, no YAML).",
        checked={
            "directories_outside_scope": len(dirs),
            "definitions_outside_scope": sum(d.definitions for d in dirs),
            "shadowed_symbols": sum(len(d.shadowed) for d in dirs),
        },
        notes=tuple(notes),
    )

Activity · 6 steps
lines 270–270tracked = tracked_files(ctx.repo_root)lines 271–271dirs = candidate_dirs(ctx, tracked)lines 272–279notes = [ f"Your derived scope is {ctx.scope.source} — {len(ctx.scope.roots)} root(s), " f"{len(ctx.scope.excludes)} exclude(s), covering " f"{ctx.corpus.files_in_scope} of {ctx.corpus.files_parsed} parsed source files.", *_dir_lines(dirs), _REPLACE_SEMANTICS, *cross_section_conflicts(sections, dirs), ]lines 280–280◇ if tracked is Nonelines 281–284notes.append( "NOTE: `git ls-files` was unavailable, so vendored/submodule trees " "could not be excluded from the directory list above." )lines 285–295return SectionProposal( name=INDEX_SCOPE_SECTION, status=SectionStatus.REPORT_ONLY, reason="NOT PROPOSED BY DESIGN — see the note below (report only, no YAML).", checked={ "directories_outside_scope": len(dirs), "definitions_outside_scope": sum(d.definitions for d in dirs), "shadowed_symbols": sum(len(d.shadowed) for d in dirs), }, notes=tuple(notes), )

Requirements

REQ-DDB-CONFIG-001

Flows

seeds_reachability

bool clew.propose.notindexed.seeds_reachability(str name)

Whether a name matches one of the reachability entry-point patterns.

clew/propose/notindexed.py:117

Source · 27 lines
def seeds_reachability(name: str) -> bool:
    """Mirrors `reachability.DEFAULT_ENTRY_PATTERNS` as SQLite would apply it:
    LIKE is ASCII-case-insensitive and `%` is any run of characters.

    THE SECOND CONSUMER of that constant, and it reads the WHOLE default set on
    purpose. gh#319 split the constant into a tier-3 half (`ENTRY_PATTERN_FACTS` —
    `main`, `app_main`) and a tier-5 half (`ENTRY_PATTERN_HEURISTICS`); reading
    either half alone here would make the proposer and the reachability pass
    disagree about what an entry point is, and the disagreement would surface as a
    hazard warning that omits the very `main` collision this module exists to warn
    about. `DEFAULT_ENTRY_PATTERNS` is the composed set, so the two cannot drift —
    and `tests/test_tiers.py` pins the agreement against the resolver's own
    no-statement result rather than against the constant, so a change to how the
    default set is composed fails here too.

    Deliberately reads the DEFAULT set and not the resolved one: the proposer runs
    before any build and has no `args`, no declaration-driven resolution and no
    stamped record to consult. It is warning about what a build WOULD do absent a
    statement, which is exactly the default set.

    @brief Test a name against the reachability entry-point seeds.
    @version 2
    """
    lowered = name.lower()
    return any(_like(lowered, pattern) for pattern in DEFAULT_ENTRY_PATTERNS)

Activity · 2 steps
lines 140–140lowered = name.lower()lines 141–141return any(_like(lowered, pattern) for pattern in DEFAULT_ENTRY_PATTERNS)

Requirements

REQ-DDB-CONFIG-001

tracked_files

frozenset[str] | None clew.propose.notindexed.tracked_files(Path repo_root)

Git-tracked repo-relative paths, or None when git is unavailable.

clew/propose/notindexed.py:84

Source · 28 lines
def tracked_files(repo_root: Path) -> frozenset[str] | None:
    """Tracked-only is what keeps submodule and vendored trees out of the
    report: a gitlink's contents are not listed by the superproject, so a
    third-party checkout never appears as a directory an owner should index.

    @brief List the repo's git-tracked files.
    @version 4
    """
    try:
        ## `env=git_env()`: an absolute `GIT_DIR` exported to a hook overrides `cwd`, so
        ## without it this lists the HOOK's repository and every file in the target repo
        ## reads as untracked. See `clew.gitenv`.
        proc = subprocess.run(
            git_argv("ls-files", "-z"),
            cwd=str(repo_root),
            capture_output=True,
            text=True,
            timeout=GIT_TIMEOUT_SECONDS,
            check=False,
            env=git_env(),
        )
    except OSError:
        return None
    if proc.returncode != 0:
        return None
    return frozenset(part for part in proc.stdout.split("\0") if part)

Activity · 7 steps
lines 92–92trylines 96–104proc = subprocess.run( git_argv("ls-files", "-z"), cwd=str(repo_root), capture_output=True, text=True, timeout=GIT_TIMEOUT_SECONDS, check=False, env=git_env(), )lines 105–105except OSErrorlines 106–106return Nonelines 107–107◇ if proc.returncode != 0lines 108–108return Nonelines 109–109return frozenset(part for part in proc.stdout.split("\0") if part)

Requirements

REQ-DDB-CONFIG-001

Flows