served_spelling_audit.py

scripts/served_spelling_audit.py

WHEN `dossier` MISSED, HAD clew JUST SERVED THAT SPELLING?

audit_cell

tuple[Counter, Counter, Counter] served_spelling_audit.audit_cell(Path path)

Attribute one cell's missed subjects to the keys that served their spellings.

scripts/served_spelling_audit.py:115

Show on the map →

Called by main, test_a_batch_attributes_each_entry_separately, test_a_miss_is_attributed_to_the_key_that_served_it, test_a_repeated_block_is_counted_once, test_a_spelling_clew_never_served_is_not_attributed

Calls harvest_served, missed_subjects, shape

Source · 38 lines
def audit_cell(path: Path) -> tuple[Counter, Counter, Counter]:
    """TWO PASSES OVER ONE PAIRING. Every reply in the cell is harvested for served spellings
    first, then every missed subject is looked up in that set — so a spelling served LATER than
    the miss still counts. That is deliberate and it is the conservative direction for the claim
    being made: it can only overstate how much clew served, and the finding is that clew served
    too much of it.

    @brief Attribute a cell's misses.
    @return The three counters.
    @version 1
    """
    uses, results = _blocks(path)
    served: dict[str, set[str]] = {}
    for reply in results.values():
        try:
            parsed = json.loads(reply)
        except ValueError:
            continue
        harvest_served(parsed, served)

    totals: Counter = Counter()
    by_key: Counter = Counter()
    by_shape: Counter = Counter()
    for call_id, block in uses.items():
        if "dossier" not in str(block.get("name") or ""):
            continue
        raw = (block.get("input") or {}).get("subject")
        requested = [str(s) for s in (raw if isinstance(raw, list) else [raw])]
        for name in missed_subjects(results.get(call_id, ""), requested):
            totals["missed"] += 1
            by_shape[shape(name)] += 1
            keys = sorted(k for k, vals in served.items() if name in vals)
            if keys:
                totals["served_by_clew"] += 1
                by_key[", ".join(keys)] += 1
    return totals, by_key, by_shape

Activity · 24 steps
lines 126–126uses, results = _blocks(path)lines 127–127served: dict[str, set[str]] = {}lines 128–128◇ for reply in results.values()lines 129–129trylines 130–130parsed = json.loads(reply)lines 131–131except ValueErrorlines 132–132continuelines 133–133harvest_served(parsed, served)lines 135–135totals: Counter = Counter()lines 136–136by_key: Counter = Counter()lines 137–137by_shape: Counter = Counter()lines 138–138◇ for call_id, block in uses.items()lines 139–139◇ if "dossier" not in str(block.get("name") or "")lines 140–140continuelines 141–141raw = (block.get("input") or {}).get("subject")lines 142–142requested = [str(s) for s in (raw if isinstance(raw, list) else [raw])]lines 143–143◇ for name in missed_subjects(results.get(call_id, ""), requested)lines 144–144totals["missed"] += 1lines 145–145by_shape[shape(name)] += 1lines 146–146keys = sorted(k for k, vals in served.items() if name in vals)lines 147–147◇ if keyslines 148–148totals["served_by_clew"] += 1lines 149–149by_key[", ".join(keys)] += 1lines 150–150return totals, by_key, by_shape

Flows

harvest_served

None served_spelling_audit.harvest_served(object obj, dict[str, set[str]] out)

Every string an earlier reply offered under a name-like key.

scripts/served_spelling_audit.py:67

Show on the map →

Called by audit_cell, test_served_spellings_are_found_at_every_depth

Calls none

Source · 20 lines
def harvest_served(obj: object, out: dict[str, set[str]]) -> None:
    """RECURSIVE BECAUSE THE REPLIES ARE NESTED — a batch carries `results[]`, a dossier carries
    `callers[]`, a thread inventory carries `threads[]` — and the key that matters sits at a
    different depth in each. Keyed by the FIELD NAME so a finding can say which surface served
    the rejected spelling, which is what makes it fixable rather than merely counted.

    @brief Collect the spellings a reply put on the wire.
    @return None.
    @version 1
    """
    if isinstance(obj, dict):
        for key, value in obj.items():
            if key in NAME_KEYS and isinstance(value, str) and value:
                out.setdefault(key, set()).add(value)
            harvest_served(value, out)
    elif isinstance(obj, list):
        for value in obj:
            harvest_served(value, out)

Activity · 8 steps
lines 77–77◇ if isinstance(obj, dict)lines 78–78◇ for key, value in obj.items()lines 79–79◇ if key in NAME_KEYS and isinstance(value, str) and valuelines 80–80out.setdefault(key, set()).add(value)lines 81–81harvest_served(value, out)lines 82–82◇ elif isinstance(obj, list)lines 83–83◇ for value in objlines 84–84harvest_served(value, out)

Flows

main

int served_spelling_audit.main(Path run)

Audit every index-bearing cell of a run.

scripts/served_spelling_audit.py:158

Show on the map →

Called by none

Calls audit_cell

Source · 50 lines
def main(run: Path) -> int:
    """@brief Print the attribution table for one run.
    @return 0, or 2 when the run holds no readable transcript.
    @version 1
    """
    totals: Counter = Counter()
    by_key: Counter = Counter()
    by_shape: Counter = Counter()
    unreadable: list[str] = []

    for target in sorted(p.name for p in run.iterdir() if (p / "answers").is_dir()):
        for raw in sorted((run / target / "answers").glob("*.raw.json")):
            if "_baseline_" in raw.name:
                continue
            session = json.loads(raw.read_text("utf-8")).get("session_id")
            hits = sorted(PROJECTS.glob(f"*/{session}.jsonl")) if session else []
            if not hits:
                unreadable.append(f"{target}/{raw.stem}")
                continue
            t, k, s = audit_cell(hits[0])
            totals += t
            by_key += k
            by_shape += s

    missed = totals["missed"]
    if not missed and unreadable:
        print(f"no readable transcript for {len(unreadable)} cell(s); nothing measured")
        return 2
    served = totals["served_by_clew"]
    print(f"run: {run}")
    print(f"missed dossier subjects (index-bearing arms, de-duplicated by tool_use id): {missed}")
    if missed:
        print(
            f"of those, the spelling was SERVED by an earlier clew reply: {served} "
            f"({served / missed * 100:.1f}%)"
        )
    print("\nby spelling the caller used:")
    for name, n in by_shape.most_common():
        print(f"  {n:4d}  {name}")
    print("\nby the reply key that carried the rejected spelling:")
    for key, n in by_key.most_common():
        print(f"  {n:4d}  {key}")
    ## NAMED, NEVER COUNTED AS ZERO WASTE. A culled transcript is a cell this run cannot speak
    ## for, and reporting it as clean would be the flattering reading.
    print(f"\nunreadable transcripts: {len(unreadable)}")
    for cell in unreadable[:10]:
        print(f"  {cell}")
    return 0

Activity · 36 steps
lines 163–163totals: Counter = Counter()lines 164–164by_key: Counter = Counter()lines 165–165by_shape: Counter = Counter()lines 166–166unreadable: list[str] = []lines 168–168◇ for target in sorted(p.name for p in run.iterdir() if (p / "answers").is_dir())lines 169–169◇ for raw in sorted((run / target / "answers").glob("*.raw.json"))lines 170–170◇ if "_baseline_" in raw.namelines 171–171continuelines 172–172session = json.loads(raw.read_text("utf-8")).get("session_id")lines 173–173hits = sorted(PROJECTS.glob(f"*/{session}.jsonl")) if session else []lines 174–174◇ if not hitslines 175–175unreadable.append(f"{target}/{raw.stem}")lines 176–176continuelines 177–177t, k, s = audit_cell(hits[0])lines 178–178totals += tlines 179–179by_key += klines 180–180by_shape += slines 182–182missed = totals["missed"]lines 183–183◇ if not missed and unreadablelines 184–184print(f"no readable transcript for {len(unreadable)} cell(s); nothing measured")lines 185–185return 2lines 186–186served = totals["served_by_clew"]lines 187–187print(f"run: {run}")lines 188–188print(f"missed dossier subjects (index-bearing arms, de-duplicated by tool_use id): {missed}")lines 189–189◇ if missedlines 190–193print( f"of those, the spelling was SERVED by an earlier clew reply: {served} " f"({served / missed * 100:.1f}%)" )lines 194–194print("\nby spelling the caller used:")lines 195–195◇ for name, n in by_shape.most_common()lines 196–196print(f" {n:4d} {name}")lines 197–197print("\nby the reply key that carried the rejected spelling:")lines 198–198◇ for key, n in by_key.most_common()lines 199–199print(f" {n:4d} {key}")lines 202–202print(f"\nunreadable transcripts: {len(unreadable)}")lines 203–203◇ for cell in unreadable[:10]lines 204–204print(f" {cell}")lines 205–205return 0

Flows

shape

str served_spelling_audit.shape(str subject)

The shape of a missed subject, as a reader would have written it.

scripts/served_spelling_audit.py:92

Show on the map →

Called by audit_cell, test_shape_tests_a_path_before_a_qualification

Calls none

Source · 18 lines
def shape(subject: str) -> str:
    """SHAPE, NOT CAUSE. It says what the caller typed, which is all this function can know; why
    the index did not hold it is `selector_waste.classify_miss`'s question.

    A path is tested FIRST because a path contains a `.` and would otherwise read as a Python
    qualification — `src/app.ts` is not `src/app` dot `ts`.

    @brief Classify a missed subject by spelling.
    @return The shape.
    @version 1
    """
    if "/" in subject or _PATHISH.search(subject):
        return "file path"
    if "::" in subject or ("." in subject and not subject.startswith(".")):
        return "qualified"
    return "bare"

Activity · 5 steps
lines 103–103◇ if "/" in subject or _PATHISH.search(subject)lines 104–104return "file path"lines 105–105◇ if "::" in subject or ("." in subject and not subject.startswith("."))lines 106–106return "qualified"lines 107–107return "bare"

Flows