mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-28 22:49:12 +01:00
Compare commits
6 Commits
078d3463bd
...
f65d247c23
| Author | SHA1 | Date | |
|---|---|---|---|
| f65d247c23 | |||
| 347222b921 | |||
| d58910d916 | |||
| 11aea86920 | |||
| 29b8c5a788 | |||
| 81191f40e6 |
@ -1,21 +1,44 @@
|
|||||||
# Next session: fix the coverage INSTRUMENT, then keep clearing the allowlist
|
# Next session: the instrument is FIXED — go clear the allowlist
|
||||||
|
|
||||||
> **Paste this whole file into a fresh Claude session opened in `~/testsAndMisc`.**
|
> **Paste this whole file into a fresh Claude session opened in `~/testsAndMisc`.**
|
||||||
> It is self-contained. Do not go looking for the previous session's context.
|
> It is self-contained. Do not go looking for the previous session's context.
|
||||||
|
|
||||||
## Status in one table
|
## What changed: the bottleneck is gone
|
||||||
|
|
||||||
| Thing | Number |
|
The previous handoff said "the instrument is the bottleneck, not the tests."
|
||||||
| ------------------------------- | -------------------------------------- |
|
That is **no longer true**. Both kcov defects are fixed and pushed
|
||||||
| In-scope shell libs | **201** |
|
(`81191f40`, `29b8c5a7`). The two libs that were pinned at absurd numbers were
|
||||||
| Passing the gate today | **98** |
|
never test-limited:
|
||||||
| Still allowlisted (exempt) | **103** |
|
|
||||||
| Directories with a test harness | 7 |
|
|
||||||
| Cleared this session | 2 (`unity_handler`, `transcribe_venv`) |
|
|
||||||
|
|
||||||
The gate itself is **built and ready to arm**. `is_covered()` reads `jail_args`
|
| lib | was | now |
|
||||||
and passes `--fail-on-case-error`. Only the allowlist stands between here and
|
| ------------------------- | --------------- | ------------------- |
|
||||||
wiring it into pre-commit, pre-push and CI. CI is green.
|
| `dwm_config.sh` | 35/73 = 47.95% | **65/66 = 98.48%** |
|
||||||
|
| `rpi_nc_install.sh` | 10/88 = 11.36% | **85/88 = 96.59%** |
|
||||||
|
| `rpi_nc_ca.sh` | 72/73 = 98.63% | **73/73 = 100.00%** |
|
||||||
|
| `aw_autostart.sh` | 68/82 = 82.93% | **80/82 = 97.56%** |
|
||||||
|
| `clean_audio_filters.sh` | 83/93 = 89.25% | **85/93 = 91.40%** |
|
||||||
|
| `dot_resolver_install.sh` | 39/39 = 100.00% | 39/39 = 100.00% |
|
||||||
|
|
||||||
|
Nothing went down. **Every allowlisted lib is worth re-measuring before you
|
||||||
|
write a single new test** — several are probably already at or near 100%.
|
||||||
|
|
||||||
|
## How the instrument works now (read before changing it)
|
||||||
|
|
||||||
|
Coverage = `(PS4-traced lines | kcov hits) & (kcov line set - continuation lines)`
|
||||||
|
|
||||||
|
Two passes over the same cases, in two fresh namespaces. They **cannot** be
|
||||||
|
merged: kcov's ptrace and bash's xtrace are mutually exclusive — under
|
||||||
|
`SHELLOPTS=xtrace` every line kcov recorded as `hits="1"` comes back
|
||||||
|
`hits="0"`, measured A/B.
|
||||||
|
|
||||||
|
**The trace must never supply the denominator.** A trace reports only lines
|
||||||
|
that RAN, so trace-as-denominator makes every subject 100.00% and gates on
|
||||||
|
nothing. kcov's line set is what keeps the gate meaningful.
|
||||||
|
|
||||||
|
Full detail, including the three findings that each yield a silently wrong
|
||||||
|
trace, is in `docs/kcov-under-report.md`. The load-bearing one: **bash under
|
||||||
|
`unshare --map-root-user` runs privileged and DISCARDS an inherited `PS4`**,
|
||||||
|
so tracing is delivered through a `BASH_ENV` file instead.
|
||||||
|
|
||||||
## The scoping answers are SETTLED. Do not re-ask them.
|
## The scoping answers are SETTLED. Do not re-ask them.
|
||||||
|
|
||||||
@ -23,141 +46,148 @@ Repo-wide gate (not a ratchet) · **100%** line coverage · **ALL** `.sh` ·
|
|||||||
pre-commit **AND** pre-push **AND** CI · tests first, arm the gate last ·
|
pre-commit **AND** pre-push **AND** CI · tests first, arm the gate last ·
|
||||||
hardest first.
|
hardest first.
|
||||||
|
|
||||||
## START HERE — the instrument is the bottleneck, not the tests
|
## START HERE — re-measure the allowlist
|
||||||
|
|
||||||
**kcov has two separate defects. One is fixable today; the other caps libs at
|
103 libs are allowlisted on numbers produced by a broken instrument. Sweep
|
||||||
numbers no test can move.** Full detail and the seven DISPROVEN hypotheses are
|
them with the fixed one before writing tests. The invocation:
|
||||||
in `docs/kcov-under-report.md` — read it first and do not retry them.
|
|
||||||
|
|
||||||
- **(a) Wrong denominator.** Continuation lines inside a multi-line quoted
|
|
||||||
argument (a `perl -0777 -pe '...'` block) are counted as statements. A
|
|
||||||
`bash -x` tracer never reports them as executable at all. This is what holds
|
|
||||||
`dwm_config.sh` down.
|
|
||||||
- **(b) Wrong numerator.** Ordinary statements execute but are not recorded.
|
|
||||||
**Proven against an independent instrument:** driving `rpi_nc_install.sh`
|
|
||||||
under `PS4='+PS4:${BASH_SOURCE##*/}:${LINENO} '` with `set -x`, 55 lines
|
|
||||||
trace as executed, and **45 of them are lines kcov calls uncovered** —
|
|
||||||
including 61, 62, 63, 66, 68, 102, 118, 146. This is why that lib sits at
|
|
||||||
11.36% while all 29 of its assertions pass.
|
|
||||||
|
|
||||||
### Step 1 — fix (a) in `meta/scripts/shell_coverage_report.py`
|
|
||||||
|
|
||||||
Exclude continuation lines of multi-line quoted arguments from the
|
|
||||||
denominator. It already parses the kcov XML and has the source path from the
|
|
||||||
`filename` attribute, so this is a local change.
|
|
||||||
|
|
||||||
### Step 2 — fix (b) by replacing kcov's numerator with a PS4 tracer
|
|
||||||
|
|
||||||
Inside the jail the trace must land on a path the caller controls: `/root` and
|
|
||||||
`/var` are both bind-mounted to throwaway dirs, and `shell_coverage_jail.sh`
|
|
||||||
sends every case's stdout to `/dev/null`. Bind a dedicated output dir, or
|
|
||||||
teach the jail to copy the trace out before teardown.
|
|
||||||
|
|
||||||
### Acceptance test for ANY instrument change
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# must still be 39/39 = 100.00%
|
|
||||||
--measure dot_resolver_install.sh --min 100
|
|
||||||
# must not regress below 98.63%
|
|
||||||
--measure rpi_nc_ca.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
If either moves the wrong way, the change is wrong. Both are measured through
|
|
||||||
`run_all.sh`, never a single test file.
|
|
||||||
|
|
||||||
## If the instrument work stalls, there is always forward motion
|
|
||||||
|
|
||||||
Two directories have libs and no harness at all:
|
|
||||||
|
|
||||||
```
|
|
||||||
22 libs linux_configuration/scripts/single_use/fixes/lib/
|
|
||||||
9 libs phone_focus_mode/lib/
|
|
||||||
41 libs linux_configuration/scripts/single_use/features/lib/ (harness exists)
|
|
||||||
```
|
|
||||||
|
|
||||||
Building a harness for `fixes/lib` unblocks 22 libs at once, the way this
|
|
||||||
session's `testsAndMisc-bash` harness unblocked 5.
|
|
||||||
|
|
||||||
## The invocation that works
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash -c '
|
bash -c '
|
||||||
ja=(); while IFS= read -r l; do ja+=("$l"); done \
|
ja=(); while IFS= read -r l; do ja+=("$l"); done \
|
||||||
< <(grep -v "^#\|^$" linux_configuration/scripts/single_use/features/lib/tests/jail_args)
|
< <(grep -v "^#\|^$" <suite>/tests/jail_args)
|
||||||
timeout 300s bash meta/scripts/shell_coverage_jail.sh \
|
timeout 900s bash meta/scripts/shell_coverage_jail.sh \
|
||||||
--subject linux_configuration/scripts/single_use/features/lib/tests/run_all.sh \
|
--subject <suite>/tests/run_all.sh \
|
||||||
"${ja[@]}" --measure <lib>.sh --min 1 --fail-on-case-error -- ""'
|
"${ja[@]}" --measure <lib>.sh --min 1 --fail-on-case-error -- ""'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Omit the `ja` array entirely for suites with no `jail_args` (transcribe,
|
||||||
|
fixes) — those confine their writes to a `mktemp -d` and run bare.
|
||||||
|
|
||||||
**Always measure through `run_all.sh`, never a single test file.** That is the
|
**Always measure through `run_all.sh`, never a single test file.** That is the
|
||||||
subject `is_covered()` builds, and the runner's number can be LOWER than the
|
subject `is_covered()` builds.
|
||||||
suite's own — `rpi_nc_ca.sh` is 100% alone and 98.63% through the runner.
|
|
||||||
|
|
||||||
A suite declares its jail needs in a **`jail_args`** file beside its
|
## Directories and their harness state
|
||||||
`run_all.sh`; `ci_mirror.sh`, `shell-tests.yml` and `is_covered()` all read it.
|
|
||||||
No marker means the suite runs bare.
|
|
||||||
|
|
||||||
## Measured so far (all through `run_all.sh`)
|
```
|
||||||
|
41 libs linux_configuration/scripts/single_use/features/lib/ harness + jail_args
|
||||||
|
5 libs .../misc/testsAndMisc-bash/lib/ harness, no jail_args
|
||||||
|
22 libs .../single_use/fixes/lib/ run_all.sh ADDED this session; 6 of 22 tested
|
||||||
|
9 libs phone_focus_mode/lib/ NO harness
|
||||||
|
```
|
||||||
|
|
||||||
| lib | coverage | state |
|
`fixes/lib` was listed as "no harness at all" in the previous handoff. That
|
||||||
| ------------------------- | ------------------- | ------------- |
|
was wrong — 8 test files and 2 harnesses already existed; what was missing was
|
||||||
| `dot_resolver_install.sh` | **39/39 = 100.00%** | off allowlist |
|
`run_all.sh`, which is what `is_covered()` measures through. It now exists and
|
||||||
| `unity_handler.sh` | **32/32 = 100.00%** | off allowlist |
|
all 8 test files pass through it. **16 of the 22 libs there still have no
|
||||||
| `transcribe_venv.sh` | **53/53 = 100.00%** | off allowlist |
|
tests at all** — that is the largest remaining block of real test-writing work.
|
||||||
| `rpi_nc_ca.sh` | 72/73 = 98.63% | allowlisted |
|
|
||||||
| `nc_php.sh` | 84/85 = 98.82% | allowlisted |
|
|
||||||
| `transcribe_pkgmgr.sh` | 49/50 = 98.00% | allowlisted |
|
|
||||||
| `transcribe_deps.sh` | 48/52 = 92.31% | allowlisted |
|
|
||||||
| `clean_audio_filters.sh` | 83/93 = 89.25% | allowlisted |
|
|
||||||
| `aw_autostart.sh` | 68/82 = 82.93% | allowlisted |
|
|
||||||
| `dwm_config.sh` | 35/73 = 47.95% | defect (a) |
|
|
||||||
| `rpi_nc_install.sh` | 10/88 = 11.36% | defect (b) |
|
|
||||||
|
|
||||||
The last two are instrument-limited, not test-limited. **Writing more tests
|
## Already measured this session — do NOT redo these
|
||||||
for them will not move the number** — their assertions already pass and their
|
|
||||||
writes provably land on disk.
|
All through `run_all.sh` on the fixed instrument. `fixes/lib` needs no
|
||||||
|
`jail_args`; the features libs use the one beside their `run_all.sh`.
|
||||||
|
|
||||||
|
| lib | coverage | note |
|
||||||
|
| ------------------------------ | ------------------- | ------------------------- |
|
||||||
|
| `rpi_nc_ca.sh` | **73/73 = 100.00%** | measured 3x, solid |
|
||||||
|
| `dot_resolver_install.sh` | **39/39 = 100.00%** | acceptance baseline |
|
||||||
|
| `pacman_hook_stall_capture.sh` | **59/59 = 100.00%** | fixes/lib |
|
||||||
|
| `pacman_hook_stall_load.sh` | **25/25 = 100.00%** | fixes/lib |
|
||||||
|
| `pacman_hook_stall_summary.sh` | **18/18 = 100.00%** | fixes/lib; off-set: 36 |
|
||||||
|
| `pacman_hook_stall_watch.sh` | **24/24 = 100.00%** | fixes/lib |
|
||||||
|
| `pacman_hook_stall_usage.sh` | **1/1 = 100.00%** | body is one heredoc |
|
||||||
|
| `dwm_config.sh` | 65/66 = 98.48% | line 39 is `done < <(…)` |
|
||||||
|
| `pacman_hook_stall_setup.sh` | 26/27 = 96.30% | uncovered: 7 |
|
||||||
|
| `aw_autostart.sh` | 80/82 = 97.56% | 11 off-set lines |
|
||||||
|
| `rpi_nc_install.sh` | 85/88 = 96.59% | uncovered: 70, 202, 216 |
|
||||||
|
| `transcribe_pkgmgr.sh` | 49/50 = 98.00% | uncovered: 42 |
|
||||||
|
| `clean_audio_filters.sh` | 85/93 = 91.40% | uncovered incl. 52-58 |
|
||||||
|
| `transcribe_deps.sh` | 48/52 = 92.31% | uncovered: 19, 52, 53, 55 |
|
||||||
|
|
||||||
|
**The seven at 100.00% are allowlist-removal candidates.** They were NOT
|
||||||
|
removed this session: `fixes/lib`'s suites drive `watch_forever` timing loops,
|
||||||
|
and a timing-dependent suite can vary its line set run to run (`dwm_config.sh`
|
||||||
|
was seen to). Reproduce each at `--min 100` twice before editing
|
||||||
|
`meta/shell-coverage-allowlist.txt`. A flaky 100% becomes a red CI job whose
|
||||||
|
cause is invisible.
|
||||||
|
|
||||||
|
Allowlist entries are **static per-file lines**, verified: adding
|
||||||
|
`fixes/lib/tests/run_all.sh` did NOT start failing the 16 untested libs in
|
||||||
|
that directory — `check_shell_coverage.sh <one of them>` still exits 0,
|
||||||
|
because each is listed explicitly. The allowlist header's "every file in that
|
||||||
|
directory is enforced" describes intent, not current mechanics.
|
||||||
|
|
||||||
|
## Two instrument bounds you must know
|
||||||
|
|
||||||
|
**Defect (c): kcov's LINE SET is incomplete too.** The report now prints, per
|
||||||
|
subject, any line the trace saw run that kcov never listed:
|
||||||
|
|
||||||
|
```
|
||||||
|
outside kcov's line set (ran, but counted in neither half): 68, 70, 73, ...
|
||||||
|
```
|
||||||
|
|
||||||
|
This **cannot inflate a percentage**. A line reaches that list only because
|
||||||
|
the trace saw it EXECUTE, so folding them in only ever raises the number
|
||||||
|
(`aw_autostart.sh` 80/82 = 97.56% -> 91/93 = 97.85%). It can never hide an
|
||||||
|
untested line. What it does mean: such a subject is measured over a SUBSET of
|
||||||
|
its statements. Read the list before clearing that lib.
|
||||||
|
|
||||||
|
`aw_autostart.sh` is the known case — kcov lists nothing after the
|
||||||
|
`{ ... } >>"$file"` command group at lines 61-65.
|
||||||
|
|
||||||
|
**`nc_php.sh` does not measure at all.** "kcov instrumented no lines", on the
|
||||||
|
fixed instrument AND on the pre-fix one (checked at `078d3463` in a throwaway
|
||||||
|
worktree). Not a regression. The 84/85 = 98.82% in older notes does not
|
||||||
|
reproduce — treat it as unverified.
|
||||||
|
|
||||||
## Traps that cost real time
|
## Traps that cost real time
|
||||||
|
|
||||||
- **`--fail-on-case-error` or you are flying blind.** The jail suppresses a
|
- **`--fail-on-case-error` or you are flying blind.** The jail suppresses a
|
||||||
suite's stdout, so assertions fail invisibly without it.
|
suite's stdout, so assertions fail invisibly without it.
|
||||||
- **To find WHERE a suite dies, use an `exit <n>` sentinel.** Temporarily end
|
- **To find WHERE a suite dies, use an `exit <n>` sentinel.** The jail
|
||||||
the suite with `exit 42`; the jail surfaces the code. The only way to tell a
|
surfaces the code. The only way to tell a tracing failure from an abort.
|
||||||
tracing failure from an aborted suite.
|
|
||||||
- **`rm -f "$TEST_TMPDIR/bin/foo"` does NOT hide foo.** bash caches executable
|
- **`rm -f "$TEST_TMPDIR/bin/foo"` does NOT hide foo.** bash caches executable
|
||||||
locations. Both harnesses ship `_t_unstub`, which also runs `hash -r`. Three
|
locations. Use the harnesses' `_t_unstub`, which also runs `hash -r`.
|
||||||
assertions in this repo were asserting the opposite of their own names.
|
- **A prepended stub dir cannot hide a real binary.** If the host genuinely
|
||||||
- **A prepended stub dir cannot hide a real binary.** If the host genuinely has
|
has the tool, REPLACE PATH or jail it.
|
||||||
the tool (`pacman`, `aw-qt`, `/usr/lib/libsndfile.so`), REPLACE PATH or jail
|
- **A stub must materialise what the real tool creates.** A record-only stub
|
||||||
it, or the "not installed" case tests nothing.
|
in a `[[ ! -s $file ]]` chain silently exercises the NEXT branch.
|
||||||
- **A stub must materialise what the real tool creates.** A record-only stub in
|
|
||||||
a `[[ ! -s $file ]]` fallback chain silently exercises the NEXT branch.
|
|
||||||
- **A top-level stub function SHADOWS the subject's own** for every later
|
- **A top-level stub function SHADOWS the subject's own** for every later
|
||||||
assertion. Put redefinitions in a subshell.
|
assertion. Put redefinitions in a subshell.
|
||||||
- **`2>/dev/null` swallows a PS4 trace too** — it cost a bogus "0 lines traced"
|
- **`shfmt` and `prettier` reformat after your own check passes** — re-check
|
||||||
reading before the redirect was noticed.
|
the 250-line cap after staging, and expect the pre-push prettier hook to
|
||||||
- **`shfmt` reformats after your own check passes** — re-check the 250-line cap
|
reject markdown you hand-formatted.
|
||||||
after staging.
|
- **Commits and pushes exceed a 2-minute foreground timeout.** Background them.
|
||||||
- **Commits exceed a 2-minute foreground timeout.** Use `run_in_background`.
|
- **Never edit the working tree while a measurement runs.** The jail
|
||||||
|
fingerprints `git status --porcelain` before each case and aborts with
|
||||||
|
"the subject modified the working tree; a write escaped the jail" if it
|
||||||
|
changed. Editing an unrelated file mid-run produces that error and it is a
|
||||||
|
FALSE alarm — cost two runs this session, twice.
|
||||||
|
- **A sweep's output file buffers.** `pgrep -f shell_coverage_jail` is the
|
||||||
|
liveness signal, not file growth. A measurement that has printed nothing for
|
||||||
|
minutes is usually still running; `fixes/lib`'s timing-loop suites take 30s+
|
||||||
|
per kcov pass.
|
||||||
- **Two-strike rule.** Two failed attempts at the same thing -> stop, document,
|
- **Two-strike rule.** Two failed attempts at the same thing -> stop, document,
|
||||||
keep the working state.
|
keep the working state.
|
||||||
|
|
||||||
## Rules that will bite you
|
## Rules that will bite you
|
||||||
|
|
||||||
- **No suppressions, ever.** Fix SC2016/SC2155 at the source.
|
- **No suppressions, ever.** Fix SC2016/SC2155/EXE001/PLR2004 at the source.
|
||||||
- **Every commit touching code needs evidence** in
|
- **Every commit touching code needs evidence** in
|
||||||
`docs/superpowers/evidence/<slug>-<date>.json` (validate with
|
`docs/superpowers/evidence/<slug>-<date>.json` (validate with
|
||||||
`python3 meta/scripts/validate_evidence.py <file>`), **plus a contract** in
|
`python3 meta/scripts/validate_evidence.py <file>`), **plus a contract** in
|
||||||
`docs/superpowers/contracts/` once **>=4 code files** are staged.
|
`docs/superpowers/contracts/` once **>=4 code files** are staged.
|
||||||
- **Put the MEASURED number in it**, never a rounded or hoped-for one.
|
- **Put the MEASURED number in it**, never a rounded or hoped-for one.
|
||||||
- **Stage narrowly.** A concurrent session had 8 unrelated files in the shared
|
- **Stage narrowly.** Another session may be working in this repo at the same
|
||||||
index this session; `git restore --staged` them.
|
time; `git restore --staged` anything you did not touch.
|
||||||
- **New test files need the exec bit** — `git add --chmod=+x` only changes the
|
- **New test files need the exec bit** — `git add --chmod=+x` only changes the
|
||||||
INDEX; `chmod +x` the working tree too or the shebang hook fails.
|
INDEX; `chmod +x` the working tree too or the shebang hook fails.
|
||||||
- **`CI_GREEN_SKIP=1`** is the documented escape hatch when THIS commit fixes a
|
|
||||||
red baseline. Export it for the pre-push mirror too.
|
|
||||||
- Work directly on `main`. `git stash` and branch creation are blocked.
|
- Work directly on `main`. `git stash` and branch creation are blocked.
|
||||||
- **Another Claude session may be working in this repo simultaneously.**
|
|
||||||
|
## When the allowlist reaches zero
|
||||||
|
|
||||||
|
Wire `check_shell_coverage.sh` into pre-commit, pre-push and CI. The gate is
|
||||||
|
already correct. Note it now runs each suite TWICE per lib, so an `--all`
|
||||||
|
sweep is roughly double what it was and belongs in CI, not a commit hook.
|
||||||
|
|
||||||
## Not caused by this campaign
|
## Not caused by this campaign
|
||||||
|
|
||||||
@ -165,9 +195,3 @@ writes provably land on disk.
|
|||||||
`error: resolution-too-deep` installing `meta/requirements.txt`. Needs
|
`error: resolution-too-deep` installing `meta/requirements.txt`. Needs
|
||||||
dependency pinning; deliberately excluded from `check_ci_green.sh`. Do not
|
dependency pinning; deliberately excluded from `check_ci_green.sh`. Do not
|
||||||
fold it into this work.
|
fold it into this work.
|
||||||
|
|
||||||
## When the allowlist reaches zero
|
|
||||||
|
|
||||||
Wire `check_shell_coverage.sh` into pre-commit, pre-push and CI. The gate is
|
|
||||||
already correct; it runs a full jailed suite per lib, so an `--all` sweep is
|
|
||||||
minutes and belongs in CI, not a commit hook.
|
|
||||||
|
|||||||
@ -1,5 +1,12 @@
|
|||||||
# kcov under-reports shell coverage: two distinct defects
|
# kcov under-reports shell coverage: two distinct defects
|
||||||
|
|
||||||
|
> **RESOLVED 2026-08-22.** Both defects are fixed; the instrument now
|
||||||
|
> corrects for them and the numbers below are the _historical_ readings that
|
||||||
|
> motivated the work. Kept because the disproven hypotheses are still worth
|
||||||
|
> not retrying, and because the two root causes are the kind that silently
|
||||||
|
> come back. What the fix does, and the three findings that make it work, is
|
||||||
|
> at the end of this file under "How it was fixed".
|
||||||
|
|
||||||
Split out of `docs/shell-split-verification.md` on 2026-08-22 to hold both
|
Split out of `docs/shell-split-verification.md` on 2026-08-22 to hold both
|
||||||
files under the repo's 250-line cap. This is the campaign's instrument
|
files under the repo's 250-line cap. This is the campaign's instrument
|
||||||
problem; read it before trusting any coverage percentage.
|
problem; read it before trusting any coverage percentage.
|
||||||
@ -97,3 +104,100 @@ surfaced by `--fail-on-case-error`. Temporarily ending the suite with
|
|||||||
`exit 42` at a chosen point turns "did execution reach here?" into a yes/no
|
`exit 42` at a chosen point turns "did execution reach here?" into a yes/no
|
||||||
the jail will answer. That is what proved the second pattern is a tracing
|
the jail will answer. That is what proved the second pattern is a tracing
|
||||||
failure and not an aborted suite.
|
failure and not an aborted suite.
|
||||||
|
|
||||||
|
## How it was fixed (2026-08-22)
|
||||||
|
|
||||||
|
The instrument now runs **two passes over the same cases, in two fresh
|
||||||
|
namespaces**, and combines them:
|
||||||
|
|
||||||
|
- **denominator** = kcov's instrumentable line set, minus continuation lines
|
||||||
|
of multi-line quoted arguments (defect (a), detected by tracking quote
|
||||||
|
state across the file in `meta/scripts/lib/shell_coverage_lines.py`);
|
||||||
|
- **numerator** = (PS4-traced lines ∪ kcov's own hits) ∩ denominator
|
||||||
|
(defect (b)).
|
||||||
|
|
||||||
|
The trace cannot supply the denominator. A trace only ever reports lines that
|
||||||
|
_ran_, so using it for both halves would make every subject 100.00% and gate
|
||||||
|
on nothing. kcov's line set is what keeps the gate meaningful; kcov's _hits_
|
||||||
|
are what could not be trusted.
|
||||||
|
|
||||||
|
### Three findings, each of which silently produces a WRONG trace
|
||||||
|
|
||||||
|
1. **kcov and xtrace cannot share a process.** Under `SHELLOPTS=xtrace`,
|
||||||
|
every line kcov had recorded as `hits="1"` comes back `hits="0"` —
|
||||||
|
reproduced minimally, A/B, on the same subject. Hence two passes.
|
||||||
|
2. **`SHELLOPTS` is a readonly variable inside bash.** `export
|
||||||
|
SHELLOPTS=xtrace` fails with "readonly variable" and tracing never turns
|
||||||
|
on. It only works placed in the environment _of_ the process.
|
||||||
|
3. **Decisive: bash under `unshare --user --map-root-user` runs in PRIVILEGED
|
||||||
|
mode and DISCARDS an inherited `PS4`**, falling back to the default `+ `,
|
||||||
|
while still honouring `SHELLOPTS=xtrace` and `BASH_XTRACEFD`. The trace
|
||||||
|
then carries no `file:line` prefix at all, so every subject reads as 0%
|
||||||
|
covered. This is why the trace is delivered through a **`BASH_ENV` file**
|
||||||
|
that assigns `PS4` and runs `set -x` from _inside_ each shell — which also
|
||||||
|
solves propagation into child processes, since `set -x` does not inherit.
|
||||||
|
|
||||||
|
A fourth trap, in the report rather than the jail: **kcov records
|
||||||
|
`filename="dwm_config.sh"`, a bare basename, not a path.** The source
|
||||||
|
location has to come from the trace (which carries `${BASH_SOURCE}`) or from
|
||||||
|
a repo search; an ambiguous basename yields no exclusion rather than a guess.
|
||||||
|
|
||||||
|
### Measured effect, all through `run_all.sh`
|
||||||
|
|
||||||
|
| lib | before | after |
|
||||||
|
| ------------------------- | --------------- | ---------------------------- |
|
||||||
|
| `dot_resolver_install.sh` | 39/39 = 100.00% | 39/39 = 100.00% (acceptance) |
|
||||||
|
| `rpi_nc_ca.sh` | 72/73 = 98.63% | **73/73 = 100.00%** |
|
||||||
|
| `dwm_config.sh` | 35/73 = 47.95% | **65/66 = 98.48%** |
|
||||||
|
| `rpi_nc_install.sh` | 10/88 = 11.36% | **85/88 = 96.59%** |
|
||||||
|
|
||||||
|
`rpi_nc_ca.sh` reaching 100.00% is the load-bearing check: its missing line
|
||||||
|
141 was the _cross-process contagion_ described above, and the trace pass has
|
||||||
|
no kcov in it to be contaminated. Nothing went down.
|
||||||
|
|
||||||
|
`dwm_config.sh`'s remaining uncovered line 39 is a `done < <(...)` process
|
||||||
|
substitution — the other half of defect (a). It is deliberately still in the
|
||||||
|
denominator: every line removed from a denominator inflates coverage, which
|
||||||
|
is the fail-open direction, so a second exclusion rule should be justified
|
||||||
|
per line rather than generalised from one lib.
|
||||||
|
|
||||||
|
## Defect (c): kcov's LINE SET is also incomplete — bounded, and fail-closed
|
||||||
|
|
||||||
|
The report prints, per subject, any line the trace saw execute that kcov never
|
||||||
|
listed as instrumentable at all:
|
||||||
|
|
||||||
|
```
|
||||||
|
outside kcov's line set (ran, but counted in neither half): 68, 70, 73, ...
|
||||||
|
```
|
||||||
|
|
||||||
|
Measured across every lib with a harness, these fall into two classes:
|
||||||
|
|
||||||
|
- **Not statements, correctly absent.** `dwm_config.sh:27` (`heal_config() {`,
|
||||||
|
a function declaration), `transcribe_deps.sh:9` (a one-line function
|
||||||
|
declaration), `clean_audio_filters.sh:197,200` (`((running++))`).
|
||||||
|
- **Ordinary statements, wrongly absent.** `aw_autostart.sh` lines 68, 70, 73,
|
||||||
|
79-81, 83-84, 87-88, 94 — plain `echo`, `local`, `if [[ ... ]]`, `sudo -u
|
||||||
|
... mkdir` and a `cat >` heredoc. The trigger is a `{ ... } >>"$file"`
|
||||||
|
command group with a redirection at lines 61-65: kcov lists nothing after it
|
||||||
|
in that function.
|
||||||
|
|
||||||
|
**This cannot inflate a percentage, and cannot hide an untested line.** A line
|
||||||
|
only reaches that list _because the trace saw it run_. Folding all 11 of
|
||||||
|
`aw_autostart.sh`'s into both halves moves it from 80/82 = 97.56% to
|
||||||
|
91/93 = 97.85% — up, not down. The direction is structural: an off-set line is
|
||||||
|
by construction an executed line, so it can only ever be a missing _covered_
|
||||||
|
line, never a missing _uncovered_ one.
|
||||||
|
|
||||||
|
What it does mean is that a subject with off-set lines is measured over a
|
||||||
|
SUBSET of its statements. The percentage is honest about the subset; it is not
|
||||||
|
a claim about the whole file. Read the list before clearing such a lib off the
|
||||||
|
allowlist.
|
||||||
|
|
||||||
|
## `nc_php.sh` does not measure at all, on either instrument
|
||||||
|
|
||||||
|
`nc_php.sh` reports "kcov instrumented no lines" — reproduced twice on the
|
||||||
|
current instrument and once on the pre-fix instrument at commit `078d3463`,
|
||||||
|
via a throwaway worktree. It is **not** a regression from the two-pass change.
|
||||||
|
The 84/85 = 98.82% in earlier notes does not reproduce; whatever produced it
|
||||||
|
is not what `run_all.sh` does today. `test_nc_php.sh` exists and runs. Treat
|
||||||
|
the old figure as unverified and re-derive it before relying on it.
|
||||||
|
|||||||
@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"title": "Fix both kcov defects: correct denominator, and replace its numerator with a PS4 trace",
|
||||||
|
"objective": "Make the shell-coverage instrument report the truth, so the allowlist campaign measures tests rather than tooling. kcov counted continuation lines of multi-line quoted arguments as statements (wrong denominator) and failed to record ordinary statements that provably execute (wrong numerator); the two together held dwm_config.sh at 47.95% and rpi_nc_install.sh at 11.36% regardless of how many tests were written.",
|
||||||
|
"acceptance_criteria": [
|
||||||
|
"dot_resolver_install.sh still measures 39/39 = 100.00% through run_all.sh, gating at --min 100.",
|
||||||
|
"rpi_nc_ca.sh measures 73/73 = 100.00% -- it was 72/73 = 98.63% only because of cross-process contagion from test_dwm_config.sh, which a kcov-free trace pass cannot suffer.",
|
||||||
|
"No lib's percentage goes DOWN. A drop means a lost trace, not a stricter instrument.",
|
||||||
|
"The denominator is never derived from the trace. A PS4 trace reports only lines that ran, so trace-as-denominator would make every subject 100% and gate on nothing; kcov's line set is what keeps the gate meaningful.",
|
||||||
|
"meta/scripts/lib/shell_coverage_lines.py and meta/scripts/shell_coverage_report.py both hold 100% branch coverage.",
|
||||||
|
"pre-commit passes on every touched file with no suppression added."
|
||||||
|
],
|
||||||
|
"out_of_scope": [
|
||||||
|
"Adding a second denominator-exclusion rule for `done < <(...)` process substitution. Every line removed from a denominator inflates coverage -- the fail-open direction -- so it must be justified per line, not generalised from one lib.",
|
||||||
|
"Wiring check_shell_coverage.sh into pre-commit/pre-push/CI, which waits for the allowlist to reach zero.",
|
||||||
|
"The unrelated red `Python tests` CI job (pip resolution-too-deep since 2026-08-17)."
|
||||||
|
],
|
||||||
|
"verifier": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/features/lib/tests/run_all.sh $(jail_args) --measure dot_resolver_install.sh --min 100 --fail-on-case-error -- \"\" and the same for rpi_nc_ca.sh (both must exit 0), plus python3 -m pytest python_pkg/tests/test_shell_coverage_lines.py python_pkg/tests/test_shell_coverage_report.py (expects 29 passed), plus pre-commit run --files on the touched files."
|
||||||
|
}
|
||||||
@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"title": "Land the token_audit standing-cost checkup: surfaces, probe, unused, checkup",
|
||||||
|
"objective": "Answer 'what is billed on every turn regardless of use' with measurement instead of recall. Earlier audits answered this from memory and got it wrong -- notably a seven-day dead list that included six surfaces used within thirty days -- so the module pairs a two-window liveness test with a weighted share estimate.",
|
||||||
|
"acceptance_criteria": [
|
||||||
|
"python3 -m python_pkg.token_audit.checkup runs and prints the standing-cost report.",
|
||||||
|
"The whole token_audit package holds 100% branch coverage (116 tests).",
|
||||||
|
"Every file stays under the repo's 250-line cap.",
|
||||||
|
"A surface is only reported dead when unused in BOTH the short and long window, never on a single window.",
|
||||||
|
"pre-commit passes on all eight files with no suppression added."
|
||||||
|
],
|
||||||
|
"out_of_scope": [
|
||||||
|
"Acting on the report -- unregistering any MCP server, skill or rule file. This lands the instrument, not its conclusions.",
|
||||||
|
"The shell-coverage instrument work committed separately in 81191f40 and 29b8c5a7."
|
||||||
|
],
|
||||||
|
"verifier": "timeout 120 python3 -m python_pkg.token_audit.checkup (expects a rendered report), plus python3 -m coverage run --branch --source=python_pkg/token_audit -m pytest python_pkg/token_audit/tests (expects 116 passed and 100% with zero partial branches), plus pre-commit run --files on the eight files."
|
||||||
|
}
|
||||||
39
docs/superpowers/evidence/fixes-lib-run-all-2026-08-22.json
Normal file
39
docs/superpowers/evidence/fixes-lib-run-all-2026-08-22.json
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"intent": "Give linux_configuration/scripts/single_use/fixes/lib a run_all.sh so its six already-tested libs become measurable by the coverage gate, which measures through a suite runner and not through single test files.",
|
||||||
|
"scope": [
|
||||||
|
"linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh - new suite runner",
|
||||||
|
"NEXT_SESSION_PROMPT.md - rewritten; the instrument is no longer the bottleneck",
|
||||||
|
"Non-goal: writing tests for the 16 fixes/lib libs that have none",
|
||||||
|
"Non-goal: clearing any lib off the allowlist"
|
||||||
|
],
|
||||||
|
"changes": [
|
||||||
|
"run_all.sh follows the transcribe suite's shape: iterate test_*.sh in one process tree, count failures, exit non-zero if any failed.",
|
||||||
|
"Deliberately no jail_args file beside it. The harness confines every write to its own `mktemp -d` and intercepts external commands with a PATH stub dir, and grep found no absolute writes to /etc, /var or /usr in any test, so the suite runs bare rather than inside the namespace jail.",
|
||||||
|
"Corrects the previous handoff, which recorded fixes/lib as having 'no harness at all'. It already had 8 test files and 2 harnesses; the missing piece was the runner that is_covered() builds as its subject."
|
||||||
|
],
|
||||||
|
"verification": [
|
||||||
|
{
|
||||||
|
"command": "timeout 300 bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "All 8 test files pass through the runner, ending 'All fixes lib test files passed.' -- e.g. pacman_hook_stall_usage 4 passed 0 failed, pacman_hook_stall_watch 5 passed 0 failed."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "shell_coverage_jail.sh --subject fixes/lib/tests/run_all.sh --measure pacman_hook_stall_usage.sh --min 1 --fail-on-case-error",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "1/1 lines = 100.00%. The lib is a single usage() whose body is one `cat <<EOF` heredoc plus `exit 0`; heredoc content is data, not statements, so a denominator of 1 is the honest reading. Its one off-set line is the `usage() {` declaration -- the benign class."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "grep -rn '>[[:space:]]*/etc|>[[:space:]]*/var|>[[:space:]]*/usr' fixes/lib/tests/*.sh",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "No matches, confirming the suite writes nothing outside its mktemp -d and so needs no jail_args."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"risks": [
|
||||||
|
"16 of the 22 libs in fixes/lib still have no tests, so the runner unblocks measurement for 6 libs rather than all 22.",
|
||||||
|
"This suite is noticeably slower under the jail than the features suite, because the watch_forever tests exercise timing loops; a future --all sweep should expect that."
|
||||||
|
],
|
||||||
|
"rollback": [
|
||||||
|
"git revert this commit, or delete tests/run_all.sh; the eight test files remain runnable individually and nothing else references the runner yet.",
|
||||||
|
"After rollback, confirm the individual test files still pass by running one directly."
|
||||||
|
]
|
||||||
|
}
|
||||||
@ -0,0 +1,70 @@
|
|||||||
|
{
|
||||||
|
"intent": "Make shell coverage measure the tests instead of the instrument: correct kcov's denominator (continuation lines of multi-line quoted arguments are not statements) and replace its unreliable numerator with a PS4 xtrace, so libs stop being capped at numbers no test can move.",
|
||||||
|
"scope": [
|
||||||
|
"meta/scripts/shell_coverage_jail.sh - runs two passes and reconciles their failures",
|
||||||
|
"meta/scripts/lib/shell_coverage_case_runner.sh - per-pass case execution; BASH_ENV trace delivery",
|
||||||
|
"meta/scripts/lib/shell_coverage_jail_setup.sh - trace dir, xtrace_env.sh, reconcile_pass_failures",
|
||||||
|
"meta/scripts/lib/shell_coverage_lines.py - new: statement/executed line classification",
|
||||||
|
"meta/scripts/shell_coverage_report.py - union arithmetic and source resolution",
|
||||||
|
"python_pkg/tests/test_shell_coverage_lines.py, python_pkg/tests/test_shell_coverage_report.py - new tests",
|
||||||
|
"docs/kcov-under-report.md - records the fix and the three root causes",
|
||||||
|
"Non-goal: wiring the gate into pre-commit/pre-push/CI (waits for the allowlist to reach zero)",
|
||||||
|
"Non-goal: excluding `done < <(...)` from the denominator (fail-open direction; needs per-line justification)"
|
||||||
|
],
|
||||||
|
"changes": [
|
||||||
|
"Two passes over the same cases in two fresh namespaces: kcov's ptrace and bash's xtrace are mutually exclusive, measured A/B -- under SHELLOPTS=xtrace every kcov hit collapses from 1 to 0. Pass one supplies the instrumentable line set, pass two the executed set.",
|
||||||
|
"Coverage = (PS4-traced lines UNION kcov hits) INTERSECT (kcov line set MINUS continuation lines). The trace deliberately does not supply the denominator: it can only report lines that ran, so trace-as-denominator would make every subject 100% and gate on nothing.",
|
||||||
|
"Trace delivered via a BASH_ENV file that assigns PS4 and runs `set -x` inside each shell. Required because bash under `unshare --map-root-user` runs privileged and DISCARDS an inherited PS4 (falling back to the default '+ ', losing the file:line prefix entirely), and because `set -x` does not propagate to child processes while SHELLOPTS is readonly inside bash.",
|
||||||
|
"Continuation lines detected by tracking single/double quote state across the source, honouring backslash escapes in double quotes only and treating an unquoted # as end-of-line.",
|
||||||
|
"Source path resolved from the trace's ${BASH_SOURCE} or a unique repo search, because kcov records only a bare basename; an ambiguous basename yields no exclusion rather than a wrong guess.",
|
||||||
|
"The trace pass failing more cases than the kcov pass is a hard error: a partially-traced case under-reports and looks exactly like the defect being fixed.",
|
||||||
|
"Traced lines absent from kcov's line set are counted and reported rather than silently dropped -- a non-zero count is a third defect the design cannot correct for."
|
||||||
|
],
|
||||||
|
"verification": [
|
||||||
|
{
|
||||||
|
"command": "shell_coverage_jail.sh --measure dot_resolver_install.sh --min 100 --fail-on-case-error (through run_all.sh)",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "dot_resolver_install.sh: 39/39 lines = 100.00%, exit 0. Acceptance baseline unchanged by the instrument change."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "shell_coverage_jail.sh --measure rpi_nc_ca.sh --min 100 --fail-on-case-error (through run_all.sh)",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "rpi_nc_ca.sh: 73/73 lines = 100.00%, exit 0 -- was 72/73 = 98.63%. Line 141 was lost to cross-process contagion from test_dwm_config.sh; the trace pass has no kcov in it to contaminate. This is the discriminating check that the numerator fix landed."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "shell_coverage_jail.sh --measure dwm_config.sh (through run_all.sh)",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "35/73 = 47.95% -> 65/66 = 98.48%. Denominator lost exactly the 7 continuation lines 64-66 and 98-101; numerator rose from 35 to 65. Remaining uncovered line 39 is a `done < <(...)`, left in the denominator deliberately."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "shell_coverage_jail.sh --measure rpi_nc_install.sh (through run_all.sh)",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "10/88 = 11.36% -> 85/88 = 96.59%. The lib was never test-limited; its 29 assertions already passed."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "python3 -m pytest python_pkg/tests/test_shell_coverage_lines.py python_pkg/tests/test_shell_coverage_report.py",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "29 passed."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "python3 -m coverage run --branch --source=meta/scripts -m pytest (the two new test modules); coverage report -m",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "meta/scripts/lib/shell_coverage_lines.py 53 stmts 38 branches 100%; meta/scripts/shell_coverage_report.py 61 stmts 28 branches 100%."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "pre-commit run --files (the seven touched code files)",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "All hooks pass. Three real lint findings were fixed at source, not suppressed: EXE001 (shebang without exec bit), PLR2004 (magic argv index named _ARGV_WITH_TRACE), E501 (long test signatures wrapped)."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"risks": [
|
||||||
|
"Every measurement now runs the suite twice, so an --all sweep takes roughly double the wall time. That is why the gate belongs in CI rather than a commit hook.",
|
||||||
|
"xtrace is slower than an untraced run, so a case near its --timeout under kcov can exceed it under trace. This fails loudly via the pass-failure reconciliation rather than silently under-reporting.",
|
||||||
|
"A subject that runs `set +x`, inspects $-, or opens fd 199 would corrupt its own trace. Neither construct exists in any current subject (grepped), and fd 199 was chosen over a low fd for this reason.",
|
||||||
|
"The continuation-line detector is a quote-state scanner, not a bash parser. Over-detection would inflate coverage; it was validated against dwm_config.sh, where it flags exactly the 7 known lines and nothing else."
|
||||||
|
],
|
||||||
|
"rollback": [
|
||||||
|
"git revert the commit; the previous instrument is self-contained in the same five files.",
|
||||||
|
"After rollback, re-measure dot_resolver_install.sh (expect 39/39) and rpi_nc_ca.sh (expect the old 72/73 = 98.63%) to confirm the old behaviour is back, and restore the allowlist entries for any lib cleared on the strength of the new numbers."
|
||||||
|
]
|
||||||
|
}
|
||||||
50
docs/superpowers/evidence/kcov-offset-lines-2026-08-22.json
Normal file
50
docs/superpowers/evidence/kcov-offset-lines-2026-08-22.json
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"intent": "Make the third kcov defect readable and bounded: list the individual lines the trace saw execute that kcov never listed as instrumentable, so a human can judge whether a subject's percentage covers its whole file, and record that this cannot inflate a number.",
|
||||||
|
"scope": [
|
||||||
|
"meta/scripts/shell_coverage_report.py - off_set becomes a list of line numbers, not a count",
|
||||||
|
"python_pkg/tests/test_shell_coverage_report.py - assertions follow the new return type",
|
||||||
|
"docs/kcov-under-report.md - documents defect (c) and the nc_php.sh finding",
|
||||||
|
"Non-goal: fixing defect (c). kcov's line set cannot be repaired from outside kcov."
|
||||||
|
],
|
||||||
|
"changes": [
|
||||||
|
"_measure returns the sorted off-set line numbers instead of len(); main prints them like the uncovered list, because deciding whether a line is a statement needs the number, not a count.",
|
||||||
|
"Documented that an off-set line is BY CONSTRUCTION an executed line, so folding them in can only raise a percentage -- aw_autostart.sh 80/82 = 97.56% becomes 91/93 = 97.85%. The list cannot hide an untested statement.",
|
||||||
|
"Documented that nc_php.sh fails to measure on the PRE-FIX instrument too, so it is not a regression from the two-pass change."
|
||||||
|
],
|
||||||
|
"verification": [
|
||||||
|
{
|
||||||
|
"command": "shell_coverage_jail.sh --measure aw_autostart.sh (through run_all.sh)",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "80/82 = 97.56%, and the report now names lines 68, 70, 73, 79, 80, 81, 83, 84, 87, 88, 94. Reading them showed ordinary echo/local/if/cat statements; the trigger is the `{ ... } >>\"$file\"` command group at lines 61-65, after which kcov lists nothing in that function."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "shell_coverage_jail.sh --measure dwm_config.sh / transcribe_deps.sh / clean_audio_filters.sh",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "Off-set lines are dwm_config.sh:27 (`heal_config() {`), transcribe_deps.sh:9 (one-line function declaration) and clean_audio_filters.sh:197,200 (`((running++))`). All correctly not statements -- the benign class."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "git worktree add --detach /tmp/claude-1000/wt_base 078d3463; shell_coverage_jail.sh --measure nc_php.sh",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "\"kcov instrumented no lines\" on the PRE-FIX instrument, identical to the current one. Confirms nc_php.sh is a pre-existing condition and the old 84/85 = 98.82% figure does not reproduce. Worktree removed afterwards."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "python3 -m pytest python_pkg/tests/test_shell_coverage_report.py python_pkg/tests/test_shell_coverage_lines.py",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "29 passed; both modules hold 100% branch coverage (shell_coverage_report.py 62 stmts / 28 branches)."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "pre-commit run --files (the four touched files)",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "All hooks pass, no suppressions added."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"risks": [
|
||||||
|
"A subject with off-set lines is measured over a SUBSET of its statements, so its percentage is honest about that subset rather than the whole file. Mitigated by printing the lines so the gap is visible before a lib is cleared.",
|
||||||
|
"Defect (c) is not fixed and cannot be fixed from outside kcov; it is only bounded and made visible.",
|
||||||
|
"nc_php.sh currently yields no measurement at all, so it cannot be assessed for the allowlist until that is diagnosed separately."
|
||||||
|
],
|
||||||
|
"rollback": [
|
||||||
|
"git revert this commit; the previous behaviour (a count rather than a list) returns with no change to any percentage.",
|
||||||
|
"After rollback, re-run the two acceptance measurements (dot_resolver_install.sh 39/39, rpi_nc_ca.sh 73/73) to confirm the arithmetic is untouched."
|
||||||
|
]
|
||||||
|
}
|
||||||
@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"intent": "Land the token_audit standing-cost checkup so the question 'what am I paying for on every turn' is answered by measurement rather than recall.",
|
||||||
|
"scope": [
|
||||||
|
"python_pkg/token_audit/surfaces.py - enumerates always-on surfaces and estimates their token cost",
|
||||||
|
"python_pkg/token_audit/unused.py - two-window liveness test for registered surfaces",
|
||||||
|
"python_pkg/token_audit/probe.py - weighted share arithmetic",
|
||||||
|
"python_pkg/token_audit/checkup.py - renders the report; entry point",
|
||||||
|
"Four matching test modules",
|
||||||
|
"Non-goal: acting on the report's conclusions"
|
||||||
|
],
|
||||||
|
"changes": [
|
||||||
|
"A surface qualifies as dead only when unused in the short window AND the long one. A single seven-day window is not enough evidence: one earlier audit's seven-day dead list included six servers used within thirty days.",
|
||||||
|
"Shares are weighted, with cache-read weight 0.1, so a cached surface is not billed as if it were re-read in full each turn.",
|
||||||
|
"checkup.py composes surfaces + unused + probe rather than re-deriving any of them, so the report and the spend report cannot disagree."
|
||||||
|
],
|
||||||
|
"verification": [
|
||||||
|
{
|
||||||
|
"command": "timeout 120 python3 -m python_pkg.token_audit.checkup",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "Rendered the standing-cost report over 44,311 turns: rules/ 4,907 tokens (1.77%), memories/ 3,758 (1.35%), MEMORY.md 4,312 (1.55%), CLAUDE.md 2,057 (0.74%), skill descriptions 3,279 (1.18%), plus per-MCP 7d/30d call counts with keep/park verdicts."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "python3 -m coverage run --branch --source=python_pkg/token_audit -m pytest python_pkg/token_audit/tests; coverage report -m",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "116 passed. All 11 modules at 100%: TOTAL 574 stmts, 130 branches, 0 missed, 0 partial."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "wc -l python_pkg/token_audit/*.py python_pkg/token_audit/tests/*.py",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "Largest files are report.py at 224 and parse.py at 223; every file is under the 250-line cap, so no split was needed."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "pre-commit run --files (the eight untracked files)",
|
||||||
|
"result": "pass",
|
||||||
|
"evidence": "All hooks pass, no suppressions added."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"risks": [
|
||||||
|
"Token counts are estimates from file sizes, not billed figures, so shares are directional rather than exact.",
|
||||||
|
"The two-window test reduces but does not eliminate false 'dead' verdicts: a surface used less often than the long window still reads as dead. The report says park, not remove, for this reason.",
|
||||||
|
"The files were found untracked in the working tree, ~2h old, from an earlier session; they are landed as-is after verifying they run and are fully covered."
|
||||||
|
],
|
||||||
|
"rollback": [
|
||||||
|
"git revert this commit; the package is self-contained and nothing else imports it.",
|
||||||
|
"After rollback, confirm python_pkg still collects cleanly with python3 -m pytest python_pkg -q."
|
||||||
|
]
|
||||||
|
}
|
||||||
32
linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh
Executable file
32
linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh
Executable file
@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# lib/tests/run_all.sh — run every fixes lib test in one process tree.
|
||||||
|
#
|
||||||
|
# Also the subject handed to shell_coverage_jail.sh when measuring coverage of
|
||||||
|
# a lib in this directory: coverage of a lib is only complete across the whole
|
||||||
|
# suite, and is_covered() builds exactly this subject. Never measure a single
|
||||||
|
# test file -- the runner's number is the one that counts, and it can be lower
|
||||||
|
# than a suite's own.
|
||||||
|
#
|
||||||
|
# No jail_args file sits beside this runner, and that is deliberate: the
|
||||||
|
# harness confines every write to its own `mktemp -d` and intercepts each
|
||||||
|
# external command with a PATH stub dir, so these suites touch nothing outside
|
||||||
|
# it. Both ci_mirror.sh and the shell-tests workflow therefore run this runner
|
||||||
|
# directly rather than wrapping it in the namespace jail.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
|
||||||
|
failed=0
|
||||||
|
for test_script in "${SCRIPT_DIR}"/test_*.sh; do
|
||||||
|
printf '\n### %s\n' "$(basename "$test_script")"
|
||||||
|
if ! "$test_script"; then
|
||||||
|
failed=$((failed + 1))
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ $failed -gt 0 ]]; then
|
||||||
|
printf '\n%d test file(s) FAILED\n' "$failed"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '\nAll fixes lib test files passed.\n'
|
||||||
@ -11,6 +11,41 @@
|
|||||||
# command because it executes in the child namespace: a quoted inline block
|
# command because it executes in the child namespace: a quoted inline block
|
||||||
# would have to defer every expansion to the child shell, which reads as a
|
# would have to defer every expansion to the child shell, which reads as a
|
||||||
# quoting bug and trips SC2016.
|
# quoting bug and trips SC2016.
|
||||||
|
#
|
||||||
|
# TWO PASSES, and they cannot be merged. kcov instruments via ptrace; bash's
|
||||||
|
# xtrace is a shell feature. Running both over one process was measured to
|
||||||
|
# destroy kcov's numerator outright -- with SHELLOPTS=xtrace set, every line
|
||||||
|
# kcov had recorded as hits="1" comes back hits="0". So:
|
||||||
|
#
|
||||||
|
# pass "kcov" -> the instrumentable LINE SET (the denominator) plus kcov's
|
||||||
|
# own hit counts, which are correct for some lines and
|
||||||
|
# missing for others (defect (b) in docs/kcov-under-report.md).
|
||||||
|
# pass "trace" -> the EXECUTED line set, from a PS4 xtrace. This is the
|
||||||
|
# authoritative numerator; kcov's hits are unioned in so a
|
||||||
|
# line either instrument saw counts as covered.
|
||||||
|
#
|
||||||
|
# Tracing is delivered via BASH_ENV, not SHELLOPTS/PS4, and the reason is
|
||||||
|
# measured, not stylistic. Three findings, each of which yields a silently
|
||||||
|
# WRONG trace rather than an error:
|
||||||
|
#
|
||||||
|
# 1. `set -x` does NOT reach child bash processes, and the suites drive
|
||||||
|
# their subjects several processes deep.
|
||||||
|
# 2. SHELLOPTS is a READONLY variable inside bash, so `export
|
||||||
|
# SHELLOPTS=xtrace` fails with "readonly variable" and tracing never
|
||||||
|
# turns on. It only works placed in the environment OF the process.
|
||||||
|
# 3. Decisive: bash started under `unshare --user --map-root-user` runs in
|
||||||
|
# PRIVILEGED mode (uid != euid) and DISCARDS an inherited PS4, falling
|
||||||
|
# back to the default "+ " -- while still honouring SHELLOPTS=xtrace.
|
||||||
|
# The trace then carries no file:line prefix at all and every subject
|
||||||
|
# reads as 0% covered.
|
||||||
|
#
|
||||||
|
# BASH_ENV survives all three: every non-interactive bash sources it at
|
||||||
|
# startup, so PS4 is ASSIGNED from inside the shell (where privileged mode
|
||||||
|
# cannot strip it) and `set -x` is re-applied per process, including children.
|
||||||
|
#
|
||||||
|
# BASH_XTRACEFD uses fd 199, not a low fd: subjects and harnesses open their
|
||||||
|
# own descriptors, and a subject doing `exec 9>...` would silently clobber the
|
||||||
|
# trace mid-run and truncate it.
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
write_case_runner() {
|
write_case_runner() {
|
||||||
@ -26,6 +61,7 @@ subject_dir="$2"
|
|||||||
subject_base="$3"
|
subject_base="$3"
|
||||||
measure_base="$4"
|
measure_base="$4"
|
||||||
case_timeout="$5"
|
case_timeout="$5"
|
||||||
|
pass="$6"
|
||||||
. "$jail/mounts.sh"
|
. "$jail/mounts.sh"
|
||||||
export PATH="$jail/bin:/usr/bin:/bin"
|
export PATH="$jail/bin:/usr/bin:/bin"
|
||||||
export HOME="$jail/home"
|
export HOME="$jail/home"
|
||||||
@ -33,22 +69,40 @@ USER="${USER:-root}"
|
|||||||
export USER
|
export USER
|
||||||
export SUDO_USER="$USER"
|
export SUDO_USER="$USER"
|
||||||
cd "$subject_dir" || exit 1
|
cd "$subject_dir" || exit 1
|
||||||
|
case_index=0
|
||||||
while IFS= read -r line; do
|
while IFS= read -r line; do
|
||||||
read -r -a case_args <<<"$line"
|
read -r -a case_args <<<"$line"
|
||||||
|
case_index=$((case_index + 1))
|
||||||
# Bounded, and with stdin closed. Both matter: a subject that reads stdin
|
# Bounded, and with stdin closed. Both matter: a subject that reads stdin
|
||||||
# blocks forever on the caller's terminal (a `crontab -` fallback did
|
# blocks forever on the caller's terminal (a `crontab -` fallback did
|
||||||
# exactly this and hung a run for the full two minutes with no output),
|
# exactly this and hung a run for the full two minutes with no output),
|
||||||
# and a subject that spins never yields at all. A timed-out case is
|
# and a subject that spins never yields at all. A timed-out case is
|
||||||
# reported rather than swallowed, because a silent timeout looks
|
# reported rather than swallowed, because a silent timeout looks
|
||||||
# identical to an unreachable line in the coverage report.
|
# identical to an unreachable line in the coverage report.
|
||||||
|
if [[ $pass == kcov ]]; then
|
||||||
timeout --kill-after=10s "$case_timeout" \
|
timeout --kill-after=10s "$case_timeout" \
|
||||||
kcov --include-pattern="$measure_base" "$jail/cov" \
|
kcov --include-pattern="$measure_base" "$jail/cov" \
|
||||||
"./$subject_base" ${case_args[@]+"${case_args[@]}"} \
|
"./$subject_base" ${case_args[@]+"${case_args[@]}"} \
|
||||||
>/dev/null 2>&1 </dev/null
|
>/dev/null 2>&1 </dev/null
|
||||||
rc=$?
|
rc=$?
|
||||||
|
else
|
||||||
|
# PS4 carries the full BASH_SOURCE, not ${BASH_SOURCE##*/}: two libs
|
||||||
|
# in different directories can share a basename, and the report
|
||||||
|
# filters by basename itself.
|
||||||
|
#
|
||||||
|
# The trace fd is opened HERE and inherited, so the subject's own
|
||||||
|
# stdout/stderr redirections (the jail sends both to /dev/null)
|
||||||
|
# cannot swallow the trace -- a 2>/dev/null once cost a bogus
|
||||||
|
# "0 lines traced" reading.
|
||||||
|
timeout --kill-after=10s "$case_timeout" \
|
||||||
|
env "BASH_XTRACEFD=199" "BASH_ENV=$jail/xtrace_env.sh" \
|
||||||
|
"./$subject_base" ${case_args[@]+"${case_args[@]}"} \
|
||||||
|
>/dev/null 2>&1 </dev/null 199>>"$jail/trace/case.$case_index"
|
||||||
|
rc=$?
|
||||||
|
fi
|
||||||
if [[ $rc -eq 124 || $rc -eq 137 ]]; then
|
if [[ $rc -eq 124 || $rc -eq 137 ]]; then
|
||||||
printf 'warn: case timed out after %s: %s\n' "$case_timeout" "$line" >&2
|
printf 'warn: case timed out after %s: %s\n' "$case_timeout" "$line" >&2
|
||||||
printf '%s\n' "$rc" >>"$jail/case_failures"
|
printf '%s\n' "$rc" >>"$jail/case_failures.$pass"
|
||||||
elif [[ $rc -ne 0 ]]; then
|
elif [[ $rc -ne 0 ]]; then
|
||||||
# A non-zero case is only noise when measuring (an installer that
|
# A non-zero case is only noise when measuring (an installer that
|
||||||
# exits 1 on a bogus arg still yields coverage), but it is the whole
|
# exits 1 on a bogus arg still yields coverage), but it is the whole
|
||||||
@ -56,7 +110,7 @@ while IFS= read -r line; do
|
|||||||
# caller decide; swallowing it made a deliberately-broken assertion
|
# caller decide; swallowing it made a deliberately-broken assertion
|
||||||
# exit 0 through the push gate.
|
# exit 0 through the push gate.
|
||||||
printf 'warn: case exited %d: %s\n' "$rc" "$line" >&2
|
printf 'warn: case exited %d: %s\n' "$rc" "$line" >&2
|
||||||
printf '%s\n' "$rc" >>"$jail/case_failures"
|
printf '%s\n' "$rc" >>"$jail/case_failures.$pass"
|
||||||
fi
|
fi
|
||||||
done <"$jail/cases"
|
done <"$jail/cases"
|
||||||
INNER
|
INNER
|
||||||
|
|||||||
@ -17,7 +17,23 @@ readonly DEFAULT_SHIMS=(
|
|||||||
|
|
||||||
build_jail() {
|
build_jail() {
|
||||||
JAIL="$(mktemp -d)"
|
JAIL="$(mktemp -d)"
|
||||||
mkdir -p "$JAIL/bin" "$JAIL/cov" "$JAIL/home" "$JAIL/etc"
|
# cov holds kcov's output (the line SET); trace holds the PS4 xtrace
|
||||||
|
# output (the executed-line set). They are two SEPARATE passes because
|
||||||
|
# kcov's ptrace and SHELLOPTS=xtrace cannot share a process -- measured:
|
||||||
|
# under xtrace every kcov hit count collapses to 0.
|
||||||
|
mkdir -p "$JAIL/bin" "$JAIL/cov" "$JAIL/trace" "$JAIL/home" "$JAIL/etc"
|
||||||
|
|
||||||
|
# Sourced by every non-interactive bash in the trace pass (via BASH_ENV).
|
||||||
|
# PS4 must be ASSIGNED here rather than inherited: bash under
|
||||||
|
# `unshare --map-root-user` runs privileged and drops an inherited PS4,
|
||||||
|
# which silently costs the trace its file:line prefix. `set -x` is
|
||||||
|
# likewise re-applied per process, which is what reaches child shells.
|
||||||
|
# Quoted heredoc: ${BASH_SOURCE}/${LINENO} must reach the traced shell
|
||||||
|
# unexpanded so they evaluate per traced line.
|
||||||
|
cat >"$JAIL/xtrace_env.sh" <<'XTRACE'
|
||||||
|
PS4='+PS4:${BASH_SOURCE}:${LINENO} '
|
||||||
|
set -x
|
||||||
|
XTRACE
|
||||||
|
|
||||||
local tool
|
local tool
|
||||||
for tool in "${DEFAULT_SHIMS[@]}" ${EXTRA_SHIMS[@]+"${EXTRA_SHIMS[@]}"}; do
|
for tool in "${DEFAULT_SHIMS[@]}" ${EXTRA_SHIMS[@]+"${EXTRA_SHIMS[@]}"}; do
|
||||||
@ -107,3 +123,29 @@ build_mount_script() {
|
|||||||
done
|
done
|
||||||
} >"$JAIL/mounts.sh"
|
} >"$JAIL/mounts.sh"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# A case that passes under kcov but fails under xtrace yields a PARTIAL trace,
|
||||||
|
# which under-reports and looks exactly like the defect the trace pass exists
|
||||||
|
# to fix. xtrace is slower, so a tight --timeout is the usual cause. Fail
|
||||||
|
# loudly rather than silently measuring less.
|
||||||
|
#
|
||||||
|
# Also collapses the two per-pass failure files into the one --fail-on-case-error
|
||||||
|
# reads, so that flag keeps its original meaning.
|
||||||
|
reconcile_pass_failures() {
|
||||||
|
local kcov_fail=0 trace_fail=0
|
||||||
|
if [[ -s "$JAIL/case_failures.kcov" ]]; then
|
||||||
|
kcov_fail="$(wc -l <"$JAIL/case_failures.kcov")"
|
||||||
|
fi
|
||||||
|
if [[ -s "$JAIL/case_failures.trace" ]]; then
|
||||||
|
trace_fail="$(wc -l <"$JAIL/case_failures.trace")"
|
||||||
|
fi
|
||||||
|
if [[ $trace_fail -gt $kcov_fail ]]; then
|
||||||
|
printf 'Error: trace pass had %d failing case(s) vs %d under kcov; the\n' \
|
||||||
|
"$trace_fail" "$kcov_fail" >&2
|
||||||
|
printf ' trace is partial. xtrace is slower -- raise --timeout.\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [[ -s "$JAIL/case_failures.kcov" ]]; then
|
||||||
|
cp "$JAIL/case_failures.kcov" "$JAIL/case_failures"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|||||||
109
meta/scripts/lib/shell_coverage_lines.py
Executable file
109
meta/scripts/lib/shell_coverage_lines.py
Executable file
@ -0,0 +1,109 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Line classification for shell coverage: what is a statement, and what ran.
|
||||||
|
|
||||||
|
Split out of ``shell_coverage_report.py`` to keep both files under the repo's
|
||||||
|
250-line cap.
|
||||||
|
|
||||||
|
Two independent instruments feed the report, because neither is correct alone
|
||||||
|
(see ``docs/kcov-under-report.md``):
|
||||||
|
|
||||||
|
* kcov supplies the *line set* -- which lines are instrumentable at all. Its
|
||||||
|
hit counts are unreliable: ordinary statements execute without being
|
||||||
|
recorded (defect (b)).
|
||||||
|
* a PS4 xtrace supplies the *executed* set. A trace can only ever report lines
|
||||||
|
that ran, so it cannot supply a denominator -- using it for both halves
|
||||||
|
would make every subject 100% and gate on nothing.
|
||||||
|
|
||||||
|
So: denominator = kcov's line set minus non-statements; numerator =
|
||||||
|
(traced lines | kcov's hits) & denominator.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
|
||||||
|
# A PS4 trace line looks like: "+PS4:/abs/path/to/lib.sh:42 some command"
|
||||||
|
# The leading '+' repeats with nesting depth, so it is matched loosely.
|
||||||
|
_TRACE_RE = re.compile(r"\+*PS4:(?P<path>[^:]*):(?P<line>\d+)")
|
||||||
|
|
||||||
|
|
||||||
|
def traced_lines(trace_dir: Path, subject: str) -> set[int]:
|
||||||
|
"""Return the line numbers of *subject* seen executing in a PS4 trace."""
|
||||||
|
seen: set[int] = set()
|
||||||
|
if not trace_dir.is_dir():
|
||||||
|
return seen
|
||||||
|
for trace_file in sorted(trace_dir.iterdir()):
|
||||||
|
if not trace_file.is_file():
|
||||||
|
continue
|
||||||
|
# errors="replace": a trace interleaves writes from concurrent
|
||||||
|
# processes and can split a UTF-8 sequence. A decode error must not
|
||||||
|
# discard the whole file, which would read as zero coverage.
|
||||||
|
text = trace_file.read_text(encoding="utf-8", errors="replace")
|
||||||
|
for match in _TRACE_RE.finditer(text):
|
||||||
|
if Path(match.group("path")).name == subject:
|
||||||
|
seen.add(int(match.group("line")))
|
||||||
|
return seen
|
||||||
|
|
||||||
|
|
||||||
|
def traced_paths(trace_dir: Path, subject: str) -> list[Path]:
|
||||||
|
"""Return the distinct source paths a PS4 trace recorded for *subject*.
|
||||||
|
|
||||||
|
kcov's XML carries only a basename, so the trace is the one place the
|
||||||
|
subject's real location is written down.
|
||||||
|
"""
|
||||||
|
found: list[Path] = []
|
||||||
|
if not trace_dir.is_dir():
|
||||||
|
return found
|
||||||
|
for trace_file in sorted(trace_dir.iterdir()):
|
||||||
|
if not trace_file.is_file():
|
||||||
|
continue
|
||||||
|
text = trace_file.read_text(encoding="utf-8", errors="replace")
|
||||||
|
for match in _TRACE_RE.finditer(text):
|
||||||
|
path = Path(match.group("path"))
|
||||||
|
if path.name == subject and path not in found:
|
||||||
|
found.append(path)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def continuation_lines(source: Path) -> set[int]:
|
||||||
|
"""Return lines that are *inside* a multi-line quoted argument.
|
||||||
|
|
||||||
|
kcov counts these as instrumentable statements that never run, which
|
||||||
|
inflates the denominator and caps a subject's coverage below 100% no
|
||||||
|
matter what the tests do (defect (a)). A `bash -x` tracer never reports
|
||||||
|
them as executable at all, which is the correct reading: they are data
|
||||||
|
inside an argument, not statements.
|
||||||
|
|
||||||
|
Detected by tracking quote state across the file: any line that *begins*
|
||||||
|
while a quote opened on an earlier line is still open is a continuation.
|
||||||
|
Only the opening line of such a construct is a statement.
|
||||||
|
"""
|
||||||
|
inside: set[int] = set()
|
||||||
|
quote: str | None = None
|
||||||
|
for number, raw in enumerate(
|
||||||
|
source.read_text(encoding="utf-8", errors="replace").splitlines(), start=1
|
||||||
|
):
|
||||||
|
if quote is not None:
|
||||||
|
inside.add(number)
|
||||||
|
index = 0
|
||||||
|
while index < len(raw):
|
||||||
|
char = raw[index]
|
||||||
|
if quote is None:
|
||||||
|
if char == "#":
|
||||||
|
# A comment outside quotes ends the line's significance.
|
||||||
|
break
|
||||||
|
if char == "\\":
|
||||||
|
index += 2
|
||||||
|
continue
|
||||||
|
if char in ("'", '"'):
|
||||||
|
quote = char
|
||||||
|
elif char == quote:
|
||||||
|
quote = None
|
||||||
|
elif quote == '"' and char == "\\":
|
||||||
|
# Only double quotes honour backslash escapes; inside single
|
||||||
|
# quotes a backslash is a literal character.
|
||||||
|
index += 2
|
||||||
|
continue
|
||||||
|
index += 1
|
||||||
|
return inside
|
||||||
@ -23,13 +23,11 @@
|
|||||||
# subject under `set -e` long before the interesting code.
|
# subject under `set -e` long before the interesting code.
|
||||||
# 3. Mount only what the subject WRITES; preserve what it READS. A blanket
|
# 3. Mount only what the subject WRITES; preserve what it READS. A blanket
|
||||||
# jail that masked /usr/local/bin cut pacman_wrapper.sh from 75.00% to
|
# jail that masked /usr/local/bin cut pacman_wrapper.sh from 75.00% to
|
||||||
# 28.95%, because the wrapper sources its sibling libs from there and
|
# 28.95%: the wrapper sources its siblings from there and took its
|
||||||
# took its "libraries missing" escape hatch. An over-aggressive mount
|
# "libraries missing" escape hatch. Over-mounting looks like dead code.
|
||||||
# looks exactly like unreachable code.
|
|
||||||
#
|
#
|
||||||
# Entry scripts must be executed in place: they resolve their libs via
|
# Entry scripts must be executed in place: they resolve libs via BASH_SOURCE
|
||||||
# BASH_SOURCE and common.sh via `readlink -f "$0"`, so staging a copy into a
|
# and common.sh via `readlink -f "$0"`, so staging a copy breaks them.
|
||||||
# temp dir (which works fine for a sourced lib) breaks them.
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@ -213,9 +211,18 @@ main() {
|
|||||||
done
|
done
|
||||||
} >>"$JAIL/mounts.sh"
|
} >>"$JAIL/mounts.sh"
|
||||||
|
|
||||||
|
# Two passes, two fresh namespaces; they cannot be merged (kcov's ptrace
|
||||||
|
# and xtrace are mutually exclusive -- measured: under xtrace every kcov
|
||||||
|
# hit collapses to 0). "kcov" gives the line set, "trace" gives the truth
|
||||||
|
# about which of those lines ran. See lib/shell_coverage_case_runner.sh.
|
||||||
|
local pass
|
||||||
|
for pass in kcov trace; do
|
||||||
unshare --user --map-root-user --mount --fork \
|
unshare --user --map-root-user --mount --fork \
|
||||||
"$JAIL/run_cases.sh" "$JAIL" "$subject_dir" "$subject_base" "$measure_base" \
|
"$JAIL/run_cases.sh" "$JAIL" "$subject_dir" "$subject_base" \
|
||||||
"$CASE_TIMEOUT"
|
"$measure_base" "$CASE_TIMEOUT" "$pass"
|
||||||
|
done
|
||||||
|
|
||||||
|
reconcile_pass_failures
|
||||||
|
|
||||||
local tree_after
|
local tree_after
|
||||||
tree_after="$(cd "$REPO_ROOT" && git status --porcelain)"
|
tree_after="$(cd "$REPO_ROOT" && git status --porcelain)"
|
||||||
@ -229,7 +236,7 @@ main() {
|
|||||||
# and suppressing it would hide the diagnosis behind the symptom.
|
# and suppressing it would hide the diagnosis behind the symptom.
|
||||||
local report_rc=0
|
local report_rc=0
|
||||||
python3 "$REPO_ROOT/meta/scripts/shell_coverage_report.py" \
|
python3 "$REPO_ROOT/meta/scripts/shell_coverage_report.py" \
|
||||||
"$JAIL/cov" "$measure_base" "$MIN_PERCENT" || report_rc=$?
|
"$JAIL/cov" "$measure_base" "$MIN_PERCENT" "$JAIL/trace" || report_rc=$?
|
||||||
|
|
||||||
if [[ $FAIL_ON_CASE_ERROR -eq 1 && -s "$JAIL/case_failures" ]]; then
|
if [[ $FAIL_ON_CASE_ERROR -eq 1 && -s "$JAIL/case_failures" ]]; then
|
||||||
printf 'Error: %d case(s) exited non-zero; see the warn: lines above\n' \
|
printf 'Error: %d case(s) exited non-zero; see the warn: lines above\n' \
|
||||||
|
|||||||
@ -5,46 +5,125 @@ Reads kcov's cobertura-style ``cov.xml`` rather than its ``coverage.json``:
|
|||||||
the JSON summary carries only a percentage, so it cannot say which lines are
|
the JSON summary carries only a percentage, so it cannot say which lines are
|
||||||
missing, which is the only part that helps close a gap.
|
missing, which is the only part that helps close a gap.
|
||||||
|
|
||||||
|
kcov alone is not trustworthy (``docs/kcov-under-report.md``): it counts
|
||||||
|
continuation lines of multi-line quoted arguments as statements that never run
|
||||||
|
(wrong denominator), and it fails to record ordinary statements that provably
|
||||||
|
execute (wrong numerator). Both are corrected here -- the denominator by
|
||||||
|
excluding non-statements, the numerator by unioning in a PS4 xtrace captured
|
||||||
|
in a second pass.
|
||||||
|
|
||||||
Exits 1 when coverage is below the requested minimum, so the caller can use
|
Exits 1 when coverage is below the requested minimum, so the caller can use
|
||||||
it as a gate.
|
it as a gate.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from importlib.util import module_from_spec, spec_from_file_location
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
from defusedxml import ElementTree
|
from defusedxml import ElementTree
|
||||||
|
|
||||||
|
# Loaded by path rather than imported: meta/scripts/lib is not a package on
|
||||||
|
# sys.path, and a sys.path.insert would need the import to sit below it,
|
||||||
|
# which is an E402 the repo will not suppress.
|
||||||
|
_LINES_PATH = Path(__file__).resolve().parent / "lib" / "shell_coverage_lines.py"
|
||||||
|
_SPEC = spec_from_file_location("shell_coverage_lines", _LINES_PATH)
|
||||||
|
if _SPEC is None or _SPEC.loader is None: # pragma: no cover - unreachable
|
||||||
|
raise ImportError(_LINES_PATH)
|
||||||
|
_LINES = module_from_spec(_SPEC)
|
||||||
|
_SPEC.loader.exec_module(_LINES)
|
||||||
|
continuation_lines = _LINES.continuation_lines
|
||||||
|
traced_lines = _LINES.traced_lines
|
||||||
|
|
||||||
def _measure(out_dir: Path, subject: str) -> tuple[int, int, list[str]]:
|
|
||||||
"""Return (covered, total, uncovered line numbers) for *subject*.
|
def _kcov_lines(out_dir: Path, subject: str) -> dict[int, int]:
|
||||||
|
"""Return kcov's {line: hits} for *subject*.
|
||||||
|
|
||||||
kcov writes one report per instrumented process. A harness that stages
|
kcov writes one report per instrumented process. A harness that stages
|
||||||
the subject into a temp dir produces several, so the entries are merged:
|
the subject into a temp dir produces several, so the entries are merged:
|
||||||
a line counts as covered if any process hit it.
|
a line counts as covered if any process hit it.
|
||||||
"""
|
"""
|
||||||
hits: dict[str, int] = {}
|
hits: dict[int, int] = {}
|
||||||
for xml_path in out_dir.rglob("cov.xml"):
|
for xml_path in out_dir.rglob("cov.xml"):
|
||||||
for cls in ElementTree.parse(xml_path).iter("class"):
|
for cls in ElementTree.parse(xml_path).iter("class"):
|
||||||
filename = cls.get("filename", "")
|
if Path(cls.get("filename", "")).name != subject:
|
||||||
if Path(filename).name != subject:
|
|
||||||
continue
|
continue
|
||||||
for line in cls.iter("line"):
|
for line in cls.iter("line"):
|
||||||
number = line.get("number")
|
number = line.get("number")
|
||||||
if number is None:
|
if number is None:
|
||||||
continue
|
continue
|
||||||
hits[number] = hits.get(number, 0) + int(line.get("hits", "0"))
|
key = int(number)
|
||||||
|
hits[key] = hits.get(key, 0) + int(line.get("hits", "0"))
|
||||||
|
return hits
|
||||||
|
|
||||||
uncovered = sorted((n for n, h in hits.items() if h == 0), key=int)
|
|
||||||
return len(hits) - len(uncovered), len(hits), uncovered
|
def _find_source(subject: str, trace_dir: Path | None) -> Path | None:
|
||||||
|
"""Locate *subject*'s source file so its non-statements can be excluded.
|
||||||
|
|
||||||
|
kcov records `filename="dwm_config.sh"` -- a bare BASENAME, not a path --
|
||||||
|
so the XML cannot supply the source location. The PS4 trace can: it
|
||||||
|
carries ${BASH_SOURCE}, an absolute path, for every line it reports.
|
||||||
|
Falling back to a repo search keeps the exclusion working for a subject
|
||||||
|
whose trace is empty.
|
||||||
|
"""
|
||||||
|
if trace_dir is not None:
|
||||||
|
for candidate in _LINES.traced_paths(trace_dir, subject):
|
||||||
|
if candidate.is_file():
|
||||||
|
return candidate
|
||||||
|
matches = sorted(Path(__file__).resolve().parents[2].rglob(subject))
|
||||||
|
real = [m for m in matches if m.is_file() and ".git" not in m.parts]
|
||||||
|
# Exactly one match, or the exclusion would be applied from the wrong
|
||||||
|
# file. Ambiguity is reported by the caller as "no exclusions" rather
|
||||||
|
# than silently guessing, which could only inflate coverage.
|
||||||
|
return real[0] if len(real) == 1 else None
|
||||||
|
|
||||||
|
|
||||||
|
def _measure(
|
||||||
|
out_dir: Path, subject: str, trace_dir: Path | None
|
||||||
|
) -> tuple[int, int, list[str], list[str]]:
|
||||||
|
"""Return (covered, total, uncovered lines, lines outside kcov's line set)."""
|
||||||
|
hits = _kcov_lines(out_dir, subject)
|
||||||
|
if not hits:
|
||||||
|
return 0, 0, [], []
|
||||||
|
|
||||||
|
source = _find_source(subject, trace_dir)
|
||||||
|
excluded = continuation_lines(source) if source is not None else set()
|
||||||
|
denominator = set(hits) - excluded
|
||||||
|
|
||||||
|
executed = {line for line, count in hits.items() if count > 0}
|
||||||
|
traced: set[int] = set()
|
||||||
|
if trace_dir is not None:
|
||||||
|
traced = traced_lines(trace_dir, subject)
|
||||||
|
|
||||||
|
# Lines the trace saw executing that kcov never listed as instrumentable.
|
||||||
|
# Dropped from BOTH numerator and denominator, so if any of them is a real
|
||||||
|
# statement the percentage is an OVER-estimate -- the fail-open direction.
|
||||||
|
# They are listed individually, not counted, because deciding whether they
|
||||||
|
# are statements or non-statements needs the actual line numbers.
|
||||||
|
off_set = sorted(traced - set(hits) - excluded)
|
||||||
|
|
||||||
|
covered_set = (executed | traced) & denominator
|
||||||
|
uncovered = sorted(denominator - covered_set)
|
||||||
|
return (
|
||||||
|
len(covered_set),
|
||||||
|
len(denominator),
|
||||||
|
[str(n) for n in uncovered],
|
||||||
|
[str(n) for n in off_set],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# argv: <cov-dir> <subject> <minimum> [<trace-dir>]. The trace dir is optional
|
||||||
|
# so the report still runs against a kcov-only output directory.
|
||||||
|
_ARGV_WITH_TRACE = 5
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
"""Print the coverage summary and gate on the minimum percentage."""
|
"""Print the coverage summary and gate on the minimum percentage."""
|
||||||
out_dir, subject, minimum = Path(sys.argv[1]), sys.argv[2], float(sys.argv[3])
|
out_dir, subject, minimum = Path(sys.argv[1]), sys.argv[2], float(sys.argv[3])
|
||||||
|
trace_dir = Path(sys.argv[4]) if len(sys.argv) >= _ARGV_WITH_TRACE else None
|
||||||
|
|
||||||
covered, total, uncovered = _measure(out_dir, subject)
|
covered, total, uncovered, off_set = _measure(out_dir, subject, trace_dir)
|
||||||
if total == 0:
|
if total == 0:
|
||||||
sys.exit(
|
sys.exit(
|
||||||
f"{subject}: kcov instrumented no lines. It was probably invoked as "
|
f"{subject}: kcov instrumented no lines. It was probably invoked as "
|
||||||
@ -58,6 +137,11 @@ def main() -> None:
|
|||||||
sys.stdout.write(f"{subject}: {covered}/{total} lines = {percent:.2f}%\n")
|
sys.stdout.write(f"{subject}: {covered}/{total} lines = {percent:.2f}%\n")
|
||||||
if uncovered:
|
if uncovered:
|
||||||
sys.stdout.write(f" uncovered: {', '.join(uncovered)}\n")
|
sys.stdout.write(f" uncovered: {', '.join(uncovered)}\n")
|
||||||
|
if off_set:
|
||||||
|
sys.stdout.write(
|
||||||
|
f" outside kcov's line set (ran, but counted in neither half): "
|
||||||
|
f"{', '.join(off_set)}\n"
|
||||||
|
)
|
||||||
|
|
||||||
if percent < minimum:
|
if percent < minimum:
|
||||||
sys.exit(f"coverage {percent:.2f}% is below the required {minimum:.2f}%")
|
sys.exit(f"coverage {percent:.2f}% is below the required {minimum:.2f}%")
|
||||||
|
|||||||
172
python_pkg/tests/test_shell_coverage_lines.py
Normal file
172
python_pkg/tests/test_shell_coverage_lines.py
Normal file
@ -0,0 +1,172 @@
|
|||||||
|
"""Tests for meta/scripts/lib/shell_coverage_lines.py.
|
||||||
|
|
||||||
|
This module decides what counts as a statement and what counts as executed,
|
||||||
|
so both of its failure modes are silent and one-directional:
|
||||||
|
|
||||||
|
* over-detecting continuation lines shrinks the denominator and INFLATES
|
||||||
|
coverage, which is the fail-open direction -- it could promote an untested
|
||||||
|
lib off the allowlist;
|
||||||
|
* losing trace lines shrinks the numerator, which merely keeps a lib on the
|
||||||
|
allowlist that deserves to come off.
|
||||||
|
|
||||||
|
The first is the one worth pinning down hardest, so the quote-state cases
|
||||||
|
below assert exact line sets rather than counts.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from types import ModuleType
|
||||||
|
|
||||||
|
_ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
_SCRIPT = _ROOT / "meta" / "scripts" / "lib" / "shell_coverage_lines.py"
|
||||||
|
|
||||||
|
|
||||||
|
def _load() -> ModuleType:
|
||||||
|
"""Import the module by path; it lives outside any importable package."""
|
||||||
|
spec = importlib.util.spec_from_file_location("shell_coverage_lines", _SCRIPT)
|
||||||
|
assert spec is not None
|
||||||
|
assert spec.loader is not None
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(name="mod")
|
||||||
|
def _mod() -> ModuleType:
|
||||||
|
return _load()
|
||||||
|
|
||||||
|
|
||||||
|
def _write(tmp_path: Path, name: str, text: str) -> Path:
|
||||||
|
path = tmp_path / name
|
||||||
|
path.write_text(text, encoding="utf-8")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# continuation_lines
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_single_line_quotes_are_not_continuations(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""A quote opened and closed on one line leaves no continuation."""
|
||||||
|
src = _write(tmp_path, "a.sh", "echo 'hello'\necho \"world\"\n")
|
||||||
|
assert mod.continuation_lines(src) == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiline_single_quote_marks_inner_lines(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""This is the real dwm_config.sh perl-block shape: only the inner lines."""
|
||||||
|
src = _write(tmp_path, "a.sh", "perl -pe '\ns/a/b/;\ns/c/d/;\n' file\necho after\n")
|
||||||
|
# Line 1 opens the quote and IS a statement; 2-4 are inside it; 5 is after.
|
||||||
|
assert mod.continuation_lines(src) == {2, 3, 4}
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiline_double_quote_marks_inner_lines(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""Double quotes span lines the same way single quotes do."""
|
||||||
|
src = _write(tmp_path, "a.sh", 'x="\nline two\n"\necho after\n')
|
||||||
|
assert mod.continuation_lines(src) == {2, 3}
|
||||||
|
|
||||||
|
|
||||||
|
def test_comment_outside_quotes_ends_the_line(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""An apostrophe inside a comment must not open a quote state."""
|
||||||
|
src = _write(tmp_path, "a.sh", "# don't be fooled\necho after\n")
|
||||||
|
assert mod.continuation_lines(src) == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_backslash_escape_outside_quotes_is_skipped(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""An escaped quote outside quotes does not open a quote state."""
|
||||||
|
src = _write(tmp_path, "a.sh", "echo \\'\necho after\n")
|
||||||
|
assert mod.continuation_lines(src) == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_backslash_escape_inside_double_quotes(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""An escaped double quote inside double quotes does not close them."""
|
||||||
|
src = _write(tmp_path, "a.sh", 'x="a\\"b\nstill inside\n"\n')
|
||||||
|
assert mod.continuation_lines(src) == {2, 3}
|
||||||
|
|
||||||
|
|
||||||
|
def test_backslash_inside_single_quotes_is_literal(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""Single quotes honour no escapes, so a trailing backslash closes nothing."""
|
||||||
|
src = _write(tmp_path, "a.sh", "x='a\\'\necho after\n")
|
||||||
|
assert mod.continuation_lines(src) == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_hash_inside_quotes_is_not_a_comment(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""A # inside an open quote must not be treated as a comment."""
|
||||||
|
src = _write(tmp_path, "a.sh", "x='# not a comment\nstill inside\n'\n")
|
||||||
|
assert mod.continuation_lines(src) == {2, 3}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# traced_lines / traced_paths
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_traced_lines_missing_dir_is_empty(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""A missing trace dir yields nothing rather than raising."""
|
||||||
|
assert mod.traced_lines(tmp_path / "absent", "x.sh") == set()
|
||||||
|
assert mod.traced_paths(tmp_path / "absent", "x.sh") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_traced_lines_filters_by_basename(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""Only the subject's own lines are collected."""
|
||||||
|
trace = tmp_path / "trace"
|
||||||
|
trace.mkdir()
|
||||||
|
(trace / "case.1").write_text(
|
||||||
|
"+PS4:/a/b/subject.sh:12 cmd\n"
|
||||||
|
"++PS4:/a/b/subject.sh:15 cmd\n"
|
||||||
|
"+PS4:/a/b/other.sh:99 cmd\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
assert mod.traced_lines(trace, "subject.sh") == {12, 15}
|
||||||
|
|
||||||
|
|
||||||
|
def test_traced_lines_skips_subdirectories(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""A directory inside the trace dir is not read as a trace file."""
|
||||||
|
trace = tmp_path / "trace"
|
||||||
|
(trace / "nested").mkdir(parents=True)
|
||||||
|
(trace / "case.1").write_text("+PS4:/a/subject.sh:3 cmd\n", encoding="utf-8")
|
||||||
|
assert mod.traced_lines(trace, "subject.sh") == {3}
|
||||||
|
|
||||||
|
|
||||||
|
def test_traced_lines_survives_invalid_utf8(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""A split multi-byte sequence must not discard the whole trace."""
|
||||||
|
trace = tmp_path / "trace"
|
||||||
|
trace.mkdir()
|
||||||
|
(trace / "case.1").write_bytes(b"+PS4:/a/subject.sh:7 cmd\n\xff\xfe\n")
|
||||||
|
assert mod.traced_lines(trace, "subject.sh") == {7}
|
||||||
|
|
||||||
|
|
||||||
|
def test_traced_paths_skips_subdirectories(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""A directory inside the trace dir is not read when resolving paths."""
|
||||||
|
trace = tmp_path / "trace"
|
||||||
|
(trace / "nested").mkdir(parents=True)
|
||||||
|
(trace / "case.1").write_text("+PS4:/a/subject.sh:3 cmd\n", encoding="utf-8")
|
||||||
|
assert mod.traced_paths(trace, "subject.sh") == [Path("/a/subject.sh")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_traced_paths_deduplicates(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""The same source path reported many times yields one entry."""
|
||||||
|
trace = tmp_path / "trace"
|
||||||
|
trace.mkdir()
|
||||||
|
(trace / "case.1").write_text(
|
||||||
|
"+PS4:/a/subject.sh:1 c\n+PS4:/a/subject.sh:2 c\n+PS4:/b/other.sh:2 c\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
assert mod.traced_paths(trace, "subject.sh") == [Path("/a/subject.sh")]
|
||||||
235
python_pkg/tests/test_shell_coverage_report.py
Normal file
235
python_pkg/tests/test_shell_coverage_report.py
Normal file
@ -0,0 +1,235 @@
|
|||||||
|
"""Tests for meta/scripts/shell_coverage_report.py.
|
||||||
|
|
||||||
|
The report combines two instruments that are each wrong on their own
|
||||||
|
(``docs/kcov-under-report.md``): kcov supplies the line SET but under-reports
|
||||||
|
hits, and a PS4 trace supplies the executed set but cannot see a line that
|
||||||
|
never ran. The arithmetic here is what makes the shell-coverage gate mean
|
||||||
|
something, so the tests below pin the fail-open direction hardest: a trace
|
||||||
|
must never be able to add a line that is not in the denominator.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from types import ModuleType
|
||||||
|
|
||||||
|
_ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
_SCRIPT = _ROOT / "meta" / "scripts" / "shell_coverage_report.py"
|
||||||
|
|
||||||
|
_XML = """<?xml version="1.0" ?>
|
||||||
|
<coverage><packages><package><classes>
|
||||||
|
<class name="s" filename="{name}">
|
||||||
|
<lines>{lines}</lines>
|
||||||
|
</class>
|
||||||
|
</classes></package></packages></coverage>
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _load() -> ModuleType:
|
||||||
|
"""Import the script by path; it lives outside any importable package."""
|
||||||
|
spec = importlib.util.spec_from_file_location("shell_coverage_report", _SCRIPT)
|
||||||
|
assert spec is not None
|
||||||
|
assert spec.loader is not None
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(name="mod")
|
||||||
|
def _mod() -> ModuleType:
|
||||||
|
return _load()
|
||||||
|
|
||||||
|
|
||||||
|
def _cov(tmp_path: Path, name: str, hits: dict[int, int]) -> Path:
|
||||||
|
"""Write a minimal kcov cov.xml tree for *name*."""
|
||||||
|
out = tmp_path / "cov" / "proc"
|
||||||
|
out.mkdir(parents=True)
|
||||||
|
lines = "".join(f'<line number="{n}" hits="{h}"/>' for n, h in sorted(hits.items()))
|
||||||
|
(out / "cov.xml").write_text(_XML.format(name=name, lines=lines), encoding="utf-8")
|
||||||
|
return tmp_path / "cov"
|
||||||
|
|
||||||
|
|
||||||
|
def _trace(tmp_path: Path, source: Path, numbers: list[int]) -> Path:
|
||||||
|
trace = tmp_path / "trace"
|
||||||
|
trace.mkdir()
|
||||||
|
(trace / "case.1").write_text(
|
||||||
|
"".join(f"+PS4:{source}:{n} cmd\n" for n in numbers), encoding="utf-8"
|
||||||
|
)
|
||||||
|
return trace
|
||||||
|
|
||||||
|
|
||||||
|
def test_kcov_hits_alone_are_used_without_a_trace(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""With no trace dir the result is kcov's own reading."""
|
||||||
|
cov = _cov(tmp_path, "s.sh", {1: 1, 2: 0})
|
||||||
|
covered, total, uncovered, off_set = mod._measure(cov, "s.sh", None)
|
||||||
|
assert (covered, total, uncovered, off_set) == (1, 2, ["2"], [])
|
||||||
|
|
||||||
|
|
||||||
|
def test_trace_rescues_a_line_kcov_missed(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""Defect (b): a line kcov reports as 0 hits but that provably ran."""
|
||||||
|
source = tmp_path / "s.sh"
|
||||||
|
source.write_text("echo one\necho two\n", encoding="utf-8")
|
||||||
|
cov = _cov(tmp_path, "s.sh", {1: 1, 2: 0})
|
||||||
|
trace = _trace(tmp_path, source, [2])
|
||||||
|
covered, total, uncovered, _ = mod._measure(cov, "s.sh", trace)
|
||||||
|
assert (covered, total, uncovered) == (2, 2, [])
|
||||||
|
|
||||||
|
|
||||||
|
def test_continuation_lines_leave_the_denominator(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""Defect (a): inner lines of a multi-line quoted argument are not statements."""
|
||||||
|
source = tmp_path / "s.sh"
|
||||||
|
# The real dwm_config.sh shape: the closing quote shares a line with the
|
||||||
|
# rest of the command, so only the middle line is a continuation.
|
||||||
|
source.write_text("perl -pe '\ns/a/b/;\n' f\necho after\n", encoding="utf-8")
|
||||||
|
cov = _cov(tmp_path, "s.sh", {1: 1, 2: 0, 4: 1})
|
||||||
|
# The trace must be non-empty: it is what tells the report where the
|
||||||
|
# source lives, since kcov's XML carries only a basename.
|
||||||
|
trace = _trace(tmp_path, source, [1, 4])
|
||||||
|
covered, total, uncovered, _ = mod._measure(cov, "s.sh", trace)
|
||||||
|
# Line 2 is inside the quote, so the denominator is 1 and 4 only.
|
||||||
|
assert (covered, total, uncovered) == (2, 2, [])
|
||||||
|
|
||||||
|
|
||||||
|
def test_traced_line_outside_the_line_set_is_counted_not_credited(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""A traced line kcov never listed cannot inflate coverage, but is reported."""
|
||||||
|
source = tmp_path / "s.sh"
|
||||||
|
source.write_text("echo one\necho two\necho three\n", encoding="utf-8")
|
||||||
|
cov = _cov(tmp_path, "s.sh", {1: 1})
|
||||||
|
trace = _trace(tmp_path, source, [1, 3])
|
||||||
|
covered, total, _, off_set = mod._measure(cov, "s.sh", trace)
|
||||||
|
# Line 3 ran but kcov never listed it: excluded from both halves, and
|
||||||
|
# named so a human can judge whether it is a statement.
|
||||||
|
assert (covered, total, off_set) == (1, 1, ["3"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_kcov_output_reports_zero_total(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""No instrumented lines is a distinct, reportable state."""
|
||||||
|
cov = _cov(tmp_path, "other.sh", {1: 1})
|
||||||
|
assert mod._measure(cov, "s.sh", None) == (0, 0, [], [])
|
||||||
|
|
||||||
|
|
||||||
|
def test_line_without_a_number_is_skipped(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""A malformed <line> entry must not abort the report."""
|
||||||
|
out = tmp_path / "cov" / "proc"
|
||||||
|
out.mkdir(parents=True)
|
||||||
|
(out / "cov.xml").write_text(
|
||||||
|
_XML.format(name="s.sh", lines='<line hits="1"/><line number="4" hits="1"/>'),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
covered, total, _, _ = mod._measure(tmp_path / "cov", "s.sh", None)
|
||||||
|
assert (covered, total) == (1, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_source_prefers_the_trace_path(mod: ModuleType, tmp_path: Path) -> None:
|
||||||
|
"""kcov records only a basename, so the trace is the source of the path."""
|
||||||
|
source = tmp_path / "s.sh"
|
||||||
|
source.write_text("echo one\n", encoding="utf-8")
|
||||||
|
assert mod._find_source("s.sh", _trace(tmp_path, source, [1])) == source
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_source_ignores_a_trace_path_that_is_gone(
|
||||||
|
mod: ModuleType, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""A traced path that no longer exists falls through to the repo search."""
|
||||||
|
missing = tmp_path / "absent.sh"
|
||||||
|
trace = _trace(tmp_path, missing, [1])
|
||||||
|
# Nothing in the repo is called absent.sh, so the fallback finds nothing.
|
||||||
|
assert mod._find_source("absent.sh", trace) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_source_without_a_trace_searches_the_repo(mod: ModuleType) -> None:
|
||||||
|
"""The fallback resolves a uniquely-named file in the repo."""
|
||||||
|
found = mod._find_source("shell_coverage_jail.sh", None)
|
||||||
|
assert found is not None
|
||||||
|
assert found.name == "shell_coverage_jail.sh"
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_source_refuses_an_ambiguous_name(mod: ModuleType) -> None:
|
||||||
|
"""Two files with one name yields no exclusion rather than a wrong guess."""
|
||||||
|
assert mod._find_source("run_all.sh", None) is None
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# main(): the gate itself
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _run_main(
|
||||||
|
mod: ModuleType,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
argv: list[str],
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setattr("sys.argv", ["shell_coverage_report.py", *argv])
|
||||||
|
mod.main()
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_prints_the_summary(
|
||||||
|
mod: ModuleType,
|
||||||
|
tmp_path: Path,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
capsys: pytest.CaptureFixture[str],
|
||||||
|
) -> None:
|
||||||
|
"""A fully covered subject prints its percentage and passes the gate."""
|
||||||
|
cov = _cov(tmp_path, "s.sh", {1: 1, 2: 1})
|
||||||
|
_run_main(mod, monkeypatch, [str(cov), "s.sh", "100"])
|
||||||
|
assert "s.sh: 2/2 lines = 100.00%" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_lists_uncovered_lines(
|
||||||
|
mod: ModuleType,
|
||||||
|
tmp_path: Path,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
capsys: pytest.CaptureFixture[str],
|
||||||
|
) -> None:
|
||||||
|
"""A gap is named, because the numbers alone do not help close it."""
|
||||||
|
cov = _cov(tmp_path, "s.sh", {1: 1, 2: 0})
|
||||||
|
with pytest.raises(SystemExit):
|
||||||
|
_run_main(mod, monkeypatch, [str(cov), "s.sh", "100"])
|
||||||
|
assert "uncovered: 2" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_notes_lines_outside_the_line_set(
|
||||||
|
mod: ModuleType,
|
||||||
|
tmp_path: Path,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
capsys: pytest.CaptureFixture[str],
|
||||||
|
) -> None:
|
||||||
|
"""A traced line kcov never listed is surfaced as a third-defect signal."""
|
||||||
|
source = tmp_path / "s.sh"
|
||||||
|
source.write_text("echo one\necho two\n", encoding="utf-8")
|
||||||
|
cov = _cov(tmp_path, "s.sh", {1: 1})
|
||||||
|
trace = _trace(tmp_path, source, [1, 2])
|
||||||
|
_run_main(mod, monkeypatch, [str(cov), "s.sh", "100", str(trace)])
|
||||||
|
assert "outside kcov's line set" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_exits_when_below_the_minimum(
|
||||||
|
mod: ModuleType, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
"""Below the bar is a non-zero exit, which is what makes this a gate."""
|
||||||
|
cov = _cov(tmp_path, "s.sh", {1: 1, 2: 0})
|
||||||
|
with pytest.raises(SystemExit) as excinfo:
|
||||||
|
_run_main(mod, monkeypatch, [str(cov), "s.sh", "100"])
|
||||||
|
assert "below the required" in str(excinfo.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_exits_when_nothing_was_instrumented(
|
||||||
|
mod: ModuleType, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
"""Zero instrumented lines is an error, never a vacuous 100%."""
|
||||||
|
cov = _cov(tmp_path, "other.sh", {1: 1})
|
||||||
|
with pytest.raises(SystemExit) as excinfo:
|
||||||
|
_run_main(mod, monkeypatch, [str(cov), "s.sh", "100"])
|
||||||
|
assert "instrumented no lines" in str(excinfo.value)
|
||||||
71
python_pkg/token_audit/checkup.py
Normal file
71
python_pkg/token_audit/checkup.py
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
"""The weekly standing-cost checkup.
|
||||||
|
|
||||||
|
Complements the spend report. That report answers "where did the tokens go";
|
||||||
|
this answers "what is still being paid for every turn regardless of use", which
|
||||||
|
is the question earlier audits kept answering by memory and kept getting wrong.
|
||||||
|
|
||||||
|
Run as ``python3 -m python_pkg.token_audit.checkup``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from python_pkg.token_audit import surfaces, unused
|
||||||
|
from python_pkg.token_audit.probe import weighted_pct
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_usage(rows: list[unused.Usage]) -> list[str]:
|
||||||
|
"""Render call counts, marking only rows dead in BOTH windows."""
|
||||||
|
header = (
|
||||||
|
f"| name | {unused.SHORT_WINDOW_DAYS}d | {unused.LONG_WINDOW_DAYS}d | verdict |"
|
||||||
|
)
|
||||||
|
lines = [header, "|---|---|---|---|"]
|
||||||
|
for row in rows:
|
||||||
|
verdict = "**park**" if row.dead else "keep"
|
||||||
|
lines.append(
|
||||||
|
f"| {row.name} | {row.short_calls} | {row.long_calls} | {verdict} |"
|
||||||
|
)
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
def build(turns: int, weighted_total: int) -> str:
|
||||||
|
"""Render the checkup as markdown."""
|
||||||
|
out = ["# Standing-cost checkup", ""]
|
||||||
|
out.append(
|
||||||
|
"Every row below is billed on each of "
|
||||||
|
f"{turns:,} turns. Shares are weighted (cache-read weight 0.1)."
|
||||||
|
)
|
||||||
|
out.append("")
|
||||||
|
out.append("## Surfaces")
|
||||||
|
out.append("| surface | est tokens | share | detail |")
|
||||||
|
out.append("|---|---|---|---|")
|
||||||
|
for surface in surfaces.collect():
|
||||||
|
share = weighted_pct(surface.est_tokens, turns, weighted_total)
|
||||||
|
est = f"{surface.est_tokens:,}" if surface.est_tokens else "A/B only"
|
||||||
|
out.append(f"| {surface.name} | {est} | {share:.2f}% | {surface.detail} |")
|
||||||
|
out += ["", "## MCP servers", ""]
|
||||||
|
out += _fmt_usage(unused.mcp_usage())
|
||||||
|
out += ["", "## Skills", ""]
|
||||||
|
out += _fmt_usage(unused.skill_usage())
|
||||||
|
out += [
|
||||||
|
"",
|
||||||
|
"_A surface marked `A/B only` cannot be sized from disk; measure it",
|
||||||
|
"with `probe.measure()`, which runs non-strict so project `.mcp.json`",
|
||||||
|
"files are included._",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
return "\n".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
"""Print the checkup, taking turns and weighted total from the last report."""
|
||||||
|
argv = sys.argv[1:] if argv is None else argv
|
||||||
|
turns = int(argv[0]) if argv else 44311
|
||||||
|
total = int(argv[1]) if len(argv) > 1 else 1230346533
|
||||||
|
sys.stdout.write(build(turns, total))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
117
python_pkg/token_audit/probe.py
Normal file
117
python_pkg/token_audit/probe.py
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
"""Measure the real per-turn prefix by starting Claude Code and reading usage.
|
||||||
|
|
||||||
|
Disk sizes do not predict billed cost: deferred MCP schemas are absent while
|
||||||
|
their tool *names* are not, and skill bodies are summarised. The only honest
|
||||||
|
number comes from a real process start.
|
||||||
|
|
||||||
|
Two lessons are encoded as defaults here, both learned by getting them wrong:
|
||||||
|
|
||||||
|
* ``--strict-mcp-config`` suppresses project-scoped ``.mcp.json`` files, so an
|
||||||
|
A/B run with it understates the baseline (~2,000 tokens/turn in one audit).
|
||||||
|
Probes therefore run **non-strict** unless explicitly asked otherwise.
|
||||||
|
* A saving predicted from a synthetic config must be re-measured after the
|
||||||
|
change actually lands. :func:`check_prediction` exists to fail loudly when the
|
||||||
|
two disagree, because one audit predicted 6,122 and delivered 4,465.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
CLAUDE_BIN = Path.home() / ".local" / "bin" / "claude"
|
||||||
|
PROBE_PROMPT = "say ok"
|
||||||
|
PROBE_TIMEOUT = 300
|
||||||
|
# Fraction by which a predicted saving may miss the measured one before the
|
||||||
|
# prediction is treated as unreliable rather than merely imprecise.
|
||||||
|
PREDICTION_TOLERANCE = 0.2
|
||||||
|
PREFIX_KINDS = (
|
||||||
|
"input_tokens",
|
||||||
|
"cache_creation_input_tokens",
|
||||||
|
"cache_read_input_tokens",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Probe:
|
||||||
|
"""One measured process start."""
|
||||||
|
|
||||||
|
label: str
|
||||||
|
prefix_tokens: int
|
||||||
|
|
||||||
|
|
||||||
|
def _prefix_from_usage(usage: dict) -> int:
|
||||||
|
"""Sum the token classes that make up the request prefix.
|
||||||
|
|
||||||
|
Cache creation and cache read are alternatives — a cold start reports the
|
||||||
|
prefix as creation, a warm one as read — so summing both is correct and
|
||||||
|
stable across repeat runs.
|
||||||
|
"""
|
||||||
|
return sum(usage.get(kind) or 0 for kind in PREFIX_KINDS)
|
||||||
|
|
||||||
|
|
||||||
|
def measure(
|
||||||
|
label: str,
|
||||||
|
*,
|
||||||
|
cwd: Path | None = None,
|
||||||
|
mcp_config: Path | None = None,
|
||||||
|
strict: bool = False,
|
||||||
|
) -> Probe:
|
||||||
|
"""Start Claude Code once and report the prefix it billed.
|
||||||
|
|
||||||
|
``strict`` defaults to False on purpose; see the module docstring.
|
||||||
|
"""
|
||||||
|
cmd = [str(CLAUDE_BIN), "-p", PROBE_PROMPT, "--output-format", "json"]
|
||||||
|
if mcp_config is not None:
|
||||||
|
cmd += ["--mcp-config", str(mcp_config)]
|
||||||
|
if strict:
|
||||||
|
cmd.append("--strict-mcp-config")
|
||||||
|
result = subprocess.run(
|
||||||
|
cmd,
|
||||||
|
cwd=str(cwd or Path.home()),
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=PROBE_TIMEOUT,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
usage = json.loads(result.stdout).get("usage") or {}
|
||||||
|
return Probe(label, _prefix_from_usage(usage))
|
||||||
|
|
||||||
|
|
||||||
|
def check_prediction(
|
||||||
|
predicted_saving: int, measured_saving: int, tolerance: float = PREDICTION_TOLERANCE
|
||||||
|
) -> str | None:
|
||||||
|
"""Return a warning when a predicted saving missed the measured one.
|
||||||
|
|
||||||
|
Returns ``None`` when the prediction held, so callers can treat a truthy
|
||||||
|
result as a gate failure.
|
||||||
|
"""
|
||||||
|
if predicted_saving <= 0:
|
||||||
|
return None
|
||||||
|
drift = abs(measured_saving - predicted_saving) / predicted_saving
|
||||||
|
if drift <= tolerance:
|
||||||
|
return None
|
||||||
|
return (
|
||||||
|
f"prediction off by {drift:.0%}: predicted {predicted_saving:,} "
|
||||||
|
f"tokens/turn, measured {measured_saving:,}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def weighted_pct(
|
||||||
|
tokens_per_turn: int,
|
||||||
|
turns: int,
|
||||||
|
weighted_total: int,
|
||||||
|
cache_read_weight: float = 0.1,
|
||||||
|
) -> float:
|
||||||
|
"""Convert a per-turn prefix saving into a share of weighted spend.
|
||||||
|
|
||||||
|
Every lever must be quoted through this function. Prefix tokens are billed
|
||||||
|
as cache reads, which carry a 0.1 weight, so a raw per-turn figure compared
|
||||||
|
against a weighted headline overstates the saving by roughly 10x — a
|
||||||
|
mistake made, and caught, in an earlier audit.
|
||||||
|
"""
|
||||||
|
if weighted_total <= 0:
|
||||||
|
return 0.0
|
||||||
|
return 100.0 * tokens_per_turn * turns * cache_read_weight / weighted_total
|
||||||
157
python_pkg/token_audit/surfaces.py
Normal file
157
python_pkg/token_audit/surfaces.py
Normal file
@ -0,0 +1,157 @@
|
|||||||
|
"""Enumerate every context surface that is billed on every turn.
|
||||||
|
|
||||||
|
The weekly audit kept missing surfaces — plugins and ``autoMode.environment``
|
||||||
|
were both found only because the user asked "nothing else?". The fix is that
|
||||||
|
the list of surfaces lives in code: a surface that is not measured shows up as
|
||||||
|
an explicit row with ``measured=False`` instead of silently not existing.
|
||||||
|
|
||||||
|
Sizes here are *estimates from disk*. Anything that can be A/B'd against a real
|
||||||
|
process start should be, via :mod:`python_pkg.token_audit.probe`; disk size and
|
||||||
|
measured prefix cost disagree (skill descriptions are summarised, MCP servers
|
||||||
|
contribute only tool names), and the measured number is the one to trust.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
CLAUDE_DIR = Path.home() / ".claude"
|
||||||
|
GLOBAL_CONFIG = Path.home() / ".claude.json"
|
||||||
|
SETTINGS = CLAUDE_DIR / "settings.json"
|
||||||
|
# Anthropic's rough byte-to-token ratio for English prose.
|
||||||
|
BYTES_PER_TOKEN = 4
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Surface:
|
||||||
|
"""One always-loaded context component."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
detail: str
|
||||||
|
bytes_on_disk: int
|
||||||
|
measurable: bool = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def est_tokens(self) -> int:
|
||||||
|
"""Disk size converted to an approximate token count."""
|
||||||
|
return self.bytes_on_disk // BYTES_PER_TOKEN
|
||||||
|
|
||||||
|
|
||||||
|
def _tree_bytes(root: Path, pattern: str = "*.md") -> int:
|
||||||
|
"""Total size of every file under *root* matching *pattern*."""
|
||||||
|
if not root.is_dir():
|
||||||
|
return 0
|
||||||
|
return sum(p.stat().st_size for p in root.rglob(pattern) if p.is_file())
|
||||||
|
|
||||||
|
|
||||||
|
def _json_field_bytes(path: Path, field: str) -> int:
|
||||||
|
"""Serialized size of one top-level field, or 0 when absent."""
|
||||||
|
if not path.exists():
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
data = json.loads(path.read_text())
|
||||||
|
except (json.JSONDecodeError, OSError):
|
||||||
|
return 0
|
||||||
|
if field not in data:
|
||||||
|
return 0
|
||||||
|
return len(json.dumps(data[field]))
|
||||||
|
|
||||||
|
|
||||||
|
def _skill_description_bytes() -> int:
|
||||||
|
"""Approximate the frontmatter that every skill contributes."""
|
||||||
|
total = 0
|
||||||
|
for skill in (CLAUDE_DIR / "skills").glob("*/SKILL.md"):
|
||||||
|
head = skill.read_text(errors="replace")[:4000]
|
||||||
|
_, _, rest = head.partition("description:")
|
||||||
|
total += len(rest.split("\n---", 1)[0]) if rest else 0
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
def _mcp_names(path: Path, field: str = "mcpServers") -> list[str]:
|
||||||
|
"""Server names registered in a config file."""
|
||||||
|
if not path.exists():
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
return sorted(json.loads(path.read_text()).get(field, {}))
|
||||||
|
except (json.JSONDecodeError, OSError):
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def _enabled_plugins() -> list[str]:
|
||||||
|
"""Plugins switched on in settings.json."""
|
||||||
|
if not SETTINGS.exists():
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
plugins = json.loads(SETTINGS.read_text()).get("enabledPlugins", {})
|
||||||
|
except (json.JSONDecodeError, OSError):
|
||||||
|
return []
|
||||||
|
return sorted(name for name, on in plugins.items() if on)
|
||||||
|
|
||||||
|
|
||||||
|
def _project_mcp_files() -> list[Path]:
|
||||||
|
"""Project-scoped .mcp.json files under the home directory.
|
||||||
|
|
||||||
|
These are invisible to ``--strict-mcp-config``, which is exactly how an
|
||||||
|
earlier audit under-measured the real baseline by ~2,000 tokens/turn.
|
||||||
|
"""
|
||||||
|
return sorted(p for p in Path.home().glob("*/.mcp.json") if p.is_file())
|
||||||
|
|
||||||
|
|
||||||
|
def collect() -> list[Surface]:
|
||||||
|
"""Enumerate every known billed surface.
|
||||||
|
|
||||||
|
Adding a surface here is what makes it appear in the report; the weekly
|
||||||
|
check walks this list rather than a human's memory of it.
|
||||||
|
"""
|
||||||
|
memory_dir = CLAUDE_DIR / "projects" / "-home-kuhy" / "memory"
|
||||||
|
plugins = _enabled_plugins()
|
||||||
|
project_mcp = _project_mcp_files()
|
||||||
|
global_mcp = _mcp_names(GLOBAL_CONFIG)
|
||||||
|
parked = _mcp_names(CLAUDE_DIR / "mcp-parked.json")
|
||||||
|
return [
|
||||||
|
Surface(
|
||||||
|
"rules/",
|
||||||
|
"always-on, loaded recursively",
|
||||||
|
_tree_bytes(CLAUDE_DIR / "rules"),
|
||||||
|
),
|
||||||
|
Surface("memories/", "always-on", _tree_bytes(CLAUDE_DIR / "memories")),
|
||||||
|
Surface(
|
||||||
|
"CLAUDE.md",
|
||||||
|
"global instructions",
|
||||||
|
(CLAUDE_DIR / "CLAUDE.md").stat().st_size
|
||||||
|
if (CLAUDE_DIR / "CLAUDE.md").exists()
|
||||||
|
else 0,
|
||||||
|
),
|
||||||
|
Surface(
|
||||||
|
"MEMORY.md",
|
||||||
|
"auto-memory index",
|
||||||
|
(memory_dir / "MEMORY.md").stat().st_size
|
||||||
|
if (memory_dir / "MEMORY.md").exists()
|
||||||
|
else 0,
|
||||||
|
),
|
||||||
|
Surface(
|
||||||
|
"skill descriptions",
|
||||||
|
f"{len(list((CLAUDE_DIR / 'skills').glob('*/SKILL.md')))} personal skills",
|
||||||
|
_skill_description_bytes(),
|
||||||
|
),
|
||||||
|
Surface("plugins", ", ".join(plugins) or "none", 0, measurable=True),
|
||||||
|
Surface(
|
||||||
|
"global MCP",
|
||||||
|
f"{len(global_mcp)} active, {len(parked)} parked",
|
||||||
|
0,
|
||||||
|
measurable=True,
|
||||||
|
),
|
||||||
|
Surface(
|
||||||
|
"project .mcp.json",
|
||||||
|
f"{len(project_mcp)} repos (per-project only)",
|
||||||
|
0,
|
||||||
|
measurable=True,
|
||||||
|
),
|
||||||
|
Surface(
|
||||||
|
"autoMode.environment",
|
||||||
|
"injected in auto mode",
|
||||||
|
_json_field_bytes(SETTINGS, "autoMode"),
|
||||||
|
),
|
||||||
|
]
|
||||||
64
python_pkg/token_audit/tests/test_checkup.py
Normal file
64
python_pkg/token_audit/tests/test_checkup.py
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
"""Tests for the standing-cost checkup report."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from python_pkg.token_audit import checkup, surfaces, unused
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def stub_sources(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
"""Replace disk scans with fixed rows so the render is deterministic."""
|
||||||
|
monkeypatch.setattr(
|
||||||
|
surfaces,
|
||||||
|
"collect",
|
||||||
|
lambda: [
|
||||||
|
surfaces.Surface("rules/", "always-on", 4000),
|
||||||
|
surfaces.Surface("global MCP", "13 active", 0, measurable=True),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
unused,
|
||||||
|
"mcp_usage",
|
||||||
|
lambda: [unused.Usage("reaper", 0, 0), unused.Usage("ck3", 0, 9)],
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(unused, "skill_usage", lambda: [unused.Usage("grilling", 0, 0)])
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_lists_every_surface() -> None:
|
||||||
|
"""A surface present in the enumeration reaches the report."""
|
||||||
|
text = checkup.build(44311, 1230346533)
|
||||||
|
assert "rules/" in text
|
||||||
|
assert "global MCP" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_disk_sized_surface_shows_weighted_share() -> None:
|
||||||
|
"""Shares are weighted, not raw — the unit error an audit made."""
|
||||||
|
text = checkup.build(44311, 1230346533)
|
||||||
|
assert "| 1,000 | 0.36% |" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_unmeasurable_surface_is_labelled() -> None:
|
||||||
|
"""A surface that needs an A/B says so rather than reporting zero bytes."""
|
||||||
|
assert "A/B only" in checkup.build(1000, 1000000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_both_window_zero_is_parked() -> None:
|
||||||
|
"""ck3 (unused 7d, used 30d) must not be recommended for parking."""
|
||||||
|
text = checkup.build(44311, 1230346533)
|
||||||
|
assert "| reaper | 0 | 0 | **park** |" in text
|
||||||
|
assert "| ck3 | 0 | 9 | keep |" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_skills_section_present() -> None:
|
||||||
|
"""Skills are audited alongside MCP servers."""
|
||||||
|
assert "## Skills" in checkup.build(1000, 1000000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_defaults_and_args(capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
"""The CLI accepts turns and total, and defaults when omitted."""
|
||||||
|
assert checkup.main([]) == 0
|
||||||
|
assert "Standing-cost checkup" in capsys.readouterr().out
|
||||||
|
assert checkup.main(["100", "1000000"]) == 0
|
||||||
|
assert "100 turns" in capsys.readouterr().out
|
||||||
111
python_pkg/token_audit/tests/test_probe.py
Normal file
111
python_pkg/token_audit/tests/test_probe.py
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
"""Tests for the prefix probe and its prediction gate."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from python_pkg.token_audit import probe
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def test_prefix_sums_cold_start() -> None:
|
||||||
|
"""A cold start reports the prefix as cache creation."""
|
||||||
|
usage = {
|
||||||
|
"input_tokens": 2,
|
||||||
|
"cache_creation_input_tokens": 46434,
|
||||||
|
"cache_read_input_tokens": 0,
|
||||||
|
}
|
||||||
|
assert probe._prefix_from_usage(usage) == 46436
|
||||||
|
|
||||||
|
|
||||||
|
def test_prefix_sums_warm_start() -> None:
|
||||||
|
"""A warm start reports the same prefix as cache read."""
|
||||||
|
usage = {"input_tokens": 2, "cache_read_input_tokens": 46434}
|
||||||
|
assert probe._prefix_from_usage(usage) == 46436
|
||||||
|
|
||||||
|
|
||||||
|
def test_prefix_handles_missing_and_null() -> None:
|
||||||
|
"""Absent or null token classes count as zero."""
|
||||||
|
assert probe._prefix_from_usage({}) == 0
|
||||||
|
assert probe._prefix_from_usage({"input_tokens": None}) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_prediction_within_tolerance_passes() -> None:
|
||||||
|
"""A prediction close to the measurement is not flagged."""
|
||||||
|
assert probe.check_prediction(1000, 900) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_prediction_beyond_tolerance_is_flagged() -> None:
|
||||||
|
"""The 6,122-vs-4,465 miss from a real audit must fail the gate."""
|
||||||
|
warning = probe.check_prediction(6122, 4465)
|
||||||
|
assert warning is not None
|
||||||
|
assert "27%" in warning
|
||||||
|
|
||||||
|
|
||||||
|
def test_prediction_ignores_nonpositive() -> None:
|
||||||
|
"""No prediction means nothing to check."""
|
||||||
|
assert probe.check_prediction(0, 500) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_weighted_pct_applies_cache_read_weight() -> None:
|
||||||
|
"""Prefix savings are billed as cache reads, at weight 0.1."""
|
||||||
|
assert probe.weighted_pct(4465, 44311, 1230346533) == pytest.approx(1.608, abs=0.01)
|
||||||
|
|
||||||
|
|
||||||
|
def test_weighted_pct_guards_zero_total() -> None:
|
||||||
|
"""An empty week cannot divide by zero."""
|
||||||
|
assert probe.weighted_pct(100, 10, 0) == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_measure_runs_non_strict_by_default(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""Strict mode hides project .mcp.json, so it must be opt-in."""
|
||||||
|
seen: dict[str, list[str]] = {}
|
||||||
|
|
||||||
|
def fake_run(cmd: list[str], **_: object) -> subprocess.CompletedProcess[str]:
|
||||||
|
seen["cmd"] = cmd
|
||||||
|
return subprocess.CompletedProcess(
|
||||||
|
cmd, 0, json.dumps({"usage": {"input_tokens": 5}}), ""
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(subprocess, "run", fake_run)
|
||||||
|
result = probe.measure("base", mcp_config=tmp_path / "x.json")
|
||||||
|
assert "--strict-mcp-config" not in seen["cmd"]
|
||||||
|
assert result.prefix_tokens == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_measure_can_opt_into_strict(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""Strict mode is still reachable when deliberately requested."""
|
||||||
|
seen: dict[str, list[str]] = {}
|
||||||
|
|
||||||
|
def fake_run(cmd: list[str], **_: object) -> subprocess.CompletedProcess[str]:
|
||||||
|
seen["cmd"] = cmd
|
||||||
|
return subprocess.CompletedProcess(cmd, 0, json.dumps({"usage": {}}), "")
|
||||||
|
|
||||||
|
monkeypatch.setattr(subprocess, "run", fake_run)
|
||||||
|
probe.measure("strict", mcp_config=tmp_path / "x.json", strict=True)
|
||||||
|
assert "--strict-mcp-config" in seen["cmd"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_measure_without_mcp_config_omits_flags(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
"""The plain probe passes no MCP flags at all."""
|
||||||
|
seen: dict[str, list[str]] = {}
|
||||||
|
|
||||||
|
def fake_run(cmd: list[str], **_: object) -> subprocess.CompletedProcess[str]:
|
||||||
|
seen["cmd"] = cmd
|
||||||
|
return subprocess.CompletedProcess(cmd, 0, json.dumps({"usage": {}}), "")
|
||||||
|
|
||||||
|
monkeypatch.setattr(subprocess, "run", fake_run)
|
||||||
|
probe.measure("plain")
|
||||||
|
assert "--mcp-config" not in seen["cmd"]
|
||||||
143
python_pkg/token_audit/tests/test_surfaces.py
Normal file
143
python_pkg/token_audit/tests/test_surfaces.py
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
"""Tests for the billed-surface enumerator."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from python_pkg.token_audit import surfaces
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||||
|
"""Build a minimal ~/.claude tree and point the module at it."""
|
||||||
|
claude = tmp_path / ".claude"
|
||||||
|
(claude / "rules").mkdir(parents=True)
|
||||||
|
(claude / "rules" / "a.instructions.md").write_text("x" * 400)
|
||||||
|
(claude / "memories").mkdir()
|
||||||
|
(claude / "memories" / "m.md").write_text("y" * 200)
|
||||||
|
(claude / "CLAUDE.md").write_text("z" * 100)
|
||||||
|
memory = claude / "projects" / "-home-kuhy" / "memory"
|
||||||
|
memory.mkdir(parents=True)
|
||||||
|
(memory / "MEMORY.md").write_text("w" * 80)
|
||||||
|
skill = claude / "skills" / "demo"
|
||||||
|
skill.mkdir(parents=True)
|
||||||
|
(skill / "SKILL.md").write_text("---\nname: demo\ndescription: hello there\n---\n")
|
||||||
|
(claude / "settings.json").write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"enabledPlugins": {"on@x": True, "off@y": False},
|
||||||
|
"autoMode": {"environment": ["a", "b"]},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
(tmp_path / ".claude.json").write_text(json.dumps({"mcpServers": {"aseprite": {}}}))
|
||||||
|
(claude / "mcp-parked.json").write_text(json.dumps({"mcpServers": {"reaper": {}}}))
|
||||||
|
repo = tmp_path / "repo"
|
||||||
|
repo.mkdir()
|
||||||
|
(repo / ".mcp.json").write_text(json.dumps({"mcpServers": {"local": {}}}))
|
||||||
|
monkeypatch.setattr(Path, "home", staticmethod(lambda: tmp_path))
|
||||||
|
for name, value in [
|
||||||
|
("CLAUDE_DIR", claude),
|
||||||
|
("GLOBAL_CONFIG", tmp_path / ".claude.json"),
|
||||||
|
("SETTINGS", claude / "settings.json"),
|
||||||
|
]:
|
||||||
|
monkeypatch.setattr(surfaces, name, value)
|
||||||
|
return tmp_path
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_surface_is_reported(fake_home: Path) -> None:
|
||||||
|
"""The enumeration is the contract: a missing row means a missed surface."""
|
||||||
|
names = [s.name for s in surfaces.collect()]
|
||||||
|
assert names == [
|
||||||
|
"rules/",
|
||||||
|
"memories/",
|
||||||
|
"CLAUDE.md",
|
||||||
|
"MEMORY.md",
|
||||||
|
"skill descriptions",
|
||||||
|
"plugins",
|
||||||
|
"global MCP",
|
||||||
|
"project .mcp.json",
|
||||||
|
"autoMode.environment",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_sizes_come_from_disk(fake_home: Path) -> None:
|
||||||
|
"""Byte counts reflect real files."""
|
||||||
|
found = {s.name: s for s in surfaces.collect()}
|
||||||
|
assert found["rules/"].bytes_on_disk == 400
|
||||||
|
assert found["rules/"].est_tokens == 100
|
||||||
|
assert found["CLAUDE.md"].bytes_on_disk == 100
|
||||||
|
assert found["MEMORY.md"].bytes_on_disk == 80
|
||||||
|
|
||||||
|
|
||||||
|
def test_enabled_plugins_only(fake_home: Path) -> None:
|
||||||
|
"""Disabled plugins cost nothing and must not be listed."""
|
||||||
|
found = {s.name: s for s in surfaces.collect()}
|
||||||
|
assert found["plugins"].detail == "on@x"
|
||||||
|
assert found["plugins"].measurable
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_split_between_active_and_parked(fake_home: Path) -> None:
|
||||||
|
"""Parked servers are reported separately from active ones."""
|
||||||
|
found = {s.name: s for s in surfaces.collect()}
|
||||||
|
assert found["global MCP"].detail == "1 active, 1 parked"
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_mcp_files_counted(fake_home: Path) -> None:
|
||||||
|
"""Project-scoped configs are surfaced, not hidden."""
|
||||||
|
found = {s.name: s for s in surfaces.collect()}
|
||||||
|
assert "1 repos" in found["project .mcp.json"].detail
|
||||||
|
|
||||||
|
|
||||||
|
def test_skill_description_measured(fake_home: Path) -> None:
|
||||||
|
"""Skill frontmatter contributes bytes."""
|
||||||
|
found = {s.name: s for s in surfaces.collect()}
|
||||||
|
assert found["skill descriptions"].bytes_on_disk > 0
|
||||||
|
assert "1 personal skills" in found["skill descriptions"].detail
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_files_are_zero(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
"""An absent tree or config contributes zero rather than raising."""
|
||||||
|
monkeypatch.setattr(Path, "home", staticmethod(lambda: tmp_path))
|
||||||
|
for name in ("CLAUDE_DIR", "GLOBAL_CONFIG", "SETTINGS"):
|
||||||
|
monkeypatch.setattr(surfaces, name, tmp_path / "nope")
|
||||||
|
result = surfaces.collect()
|
||||||
|
assert all(s.bytes_on_disk == 0 for s in result)
|
||||||
|
assert surfaces._mcp_names(tmp_path / "nope.json") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_corrupt_json_is_tolerated(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
"""Malformed config files degrade to zero, never to a crash."""
|
||||||
|
bad = tmp_path / "bad.json"
|
||||||
|
bad.write_text("{oops")
|
||||||
|
assert surfaces._json_field_bytes(bad, "autoMode") == 0
|
||||||
|
assert surfaces._mcp_names(bad) == []
|
||||||
|
monkeypatch.setattr(surfaces, "SETTINGS", bad)
|
||||||
|
assert surfaces._enabled_plugins() == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_absent_field_is_zero(tmp_path: Path) -> None:
|
||||||
|
"""A config without the field contributes nothing."""
|
||||||
|
cfg = tmp_path / "s.json"
|
||||||
|
cfg.write_text(json.dumps({"other": 1}))
|
||||||
|
assert surfaces._json_field_bytes(cfg, "autoMode") == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_enabled_plugins_without_settings(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
"""No settings file means no plugins."""
|
||||||
|
monkeypatch.setattr(surfaces, "SETTINGS", tmp_path / "gone.json")
|
||||||
|
assert surfaces._enabled_plugins() == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_tree_bytes_ignores_missing(tmp_path: Path) -> None:
|
||||||
|
"""A non-directory root totals zero."""
|
||||||
|
assert surfaces._tree_bytes(tmp_path / "absent") == 0
|
||||||
100
python_pkg/token_audit/tests/test_unused.py
Normal file
100
python_pkg/token_audit/tests/test_unused.py
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
"""Tests for the dual-window unused-surface detector."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from python_pkg.token_audit import unused
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def transcripts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||||
|
"""Redirect the transcript scan at a temporary tree."""
|
||||||
|
root = tmp_path / "projects"
|
||||||
|
(root / "proj").mkdir(parents=True)
|
||||||
|
monkeypatch.setattr(unused, "TRANSCRIPT_ROOT", root)
|
||||||
|
return root / "proj"
|
||||||
|
|
||||||
|
|
||||||
|
def test_dead_requires_both_windows_empty() -> None:
|
||||||
|
"""Used at 30 days but not 7 is not dead — the rule that prevents overreach."""
|
||||||
|
assert unused.Usage("reaper", 0, 0).dead
|
||||||
|
assert not unused.Usage("ck3", 0, 9).dead
|
||||||
|
assert not unused.Usage("aseprite", 232, 748).dead
|
||||||
|
|
||||||
|
|
||||||
|
def test_usage_counts_across_windows(transcripts: Path) -> None:
|
||||||
|
"""A recent call lands in both windows; an old one only in the long window."""
|
||||||
|
now = 1_000_000_000.0
|
||||||
|
recent = transcripts / "recent.jsonl"
|
||||||
|
recent.write_text('{"name":"mcp__aseprite__draw_line"}\n')
|
||||||
|
import os
|
||||||
|
|
||||||
|
os.utime(recent, (now - 3 * 86400, now - 3 * 86400))
|
||||||
|
old = transcripts / "old.jsonl"
|
||||||
|
old.write_text('{"name":"mcp__ck3__ck3_search"}\n')
|
||||||
|
os.utime(old, (now - 20 * 86400, now - 20 * 86400))
|
||||||
|
|
||||||
|
result = {
|
||||||
|
u.name: u
|
||||||
|
for u in unused.usage_for(
|
||||||
|
["aseprite", "ck3", "reaper"], unused._MCP_CALL, now=now
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assert result["aseprite"].short_calls == 1
|
||||||
|
assert result["aseprite"].long_calls == 1
|
||||||
|
assert result["ck3"].short_calls == 0
|
||||||
|
assert result["ck3"].long_calls == 1
|
||||||
|
assert result["reaper"].dead
|
||||||
|
|
||||||
|
|
||||||
|
def test_scan_skips_unreadable(
|
||||||
|
transcripts: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
"""An unreadable transcript is skipped rather than aborting the audit."""
|
||||||
|
bad = transcripts / "bad.jsonl"
|
||||||
|
bad.write_text("{}")
|
||||||
|
|
||||||
|
def boom(*_: object, **__: object) -> str:
|
||||||
|
msg = "nope"
|
||||||
|
raise OSError(msg)
|
||||||
|
|
||||||
|
monkeypatch.setattr(Path, "read_text", boom)
|
||||||
|
assert unused._scan(unused._MCP_CALL, 0) == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_usage_reads_config(tmp_path: Path, transcripts: Path) -> None:
|
||||||
|
"""Server names come from the global config."""
|
||||||
|
cfg = tmp_path / "claude.json"
|
||||||
|
cfg.write_text(json.dumps({"mcpServers": {"reaper": {}, "aseprite": {}}}))
|
||||||
|
names = {u.name for u in unused.mcp_usage(cfg)}
|
||||||
|
assert names == {"reaper", "aseprite"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_usage_survives_bad_config(tmp_path: Path) -> None:
|
||||||
|
"""A corrupt config yields no rows instead of raising."""
|
||||||
|
cfg = tmp_path / "broken.json"
|
||||||
|
cfg.write_text("{not json")
|
||||||
|
assert unused.mcp_usage(cfg) == []
|
||||||
|
assert unused.mcp_usage(tmp_path / "missing.json") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_skill_usage_lists_installed(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, transcripts: Path
|
||||||
|
) -> None:
|
||||||
|
"""Skill names come from the skills directory."""
|
||||||
|
home = tmp_path / "home"
|
||||||
|
skill = home / ".claude" / "skills" / "grilling"
|
||||||
|
skill.mkdir(parents=True)
|
||||||
|
(skill / "SKILL.md").write_text("---\nname: grilling\n---\n")
|
||||||
|
monkeypatch.setattr(Path, "home", staticmethod(lambda: home))
|
||||||
|
result = unused.skill_usage()
|
||||||
|
assert [u.name for u in result] == ["grilling"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_skill_pattern_matches_invocation() -> None:
|
||||||
|
"""The skill regex matches the transcript form."""
|
||||||
|
assert unused._SKILL_CALL.findall('{"skill":"phone-deploy"}') == ["phone-deploy"]
|
||||||
78
python_pkg/token_audit/unused.py
Normal file
78
python_pkg/token_audit/unused.py
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
"""Find registered surfaces that nothing has called, using two time windows.
|
||||||
|
|
||||||
|
A single seven-day window is not enough evidence to unregister anything: one
|
||||||
|
audit's seven-day "dead" list included six servers that had been used within
|
||||||
|
thirty days. A surface therefore qualifies as dead only when it is unused in
|
||||||
|
the short window *and* the long one.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
TRANSCRIPT_ROOT = Path.home() / ".claude" / "projects"
|
||||||
|
SECONDS_PER_DAY = 86400
|
||||||
|
SHORT_WINDOW_DAYS = 7
|
||||||
|
LONG_WINDOW_DAYS = 30
|
||||||
|
_MCP_CALL = re.compile(r'"name":"mcp__([a-zA-Z0-9_-]+)__')
|
||||||
|
_SKILL_CALL = re.compile(r'"skill":"([^"]+)"')
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Usage:
|
||||||
|
"""Call counts for one surface across both windows."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
short_calls: int
|
||||||
|
long_calls: int
|
||||||
|
|
||||||
|
@property
|
||||||
|
def dead(self) -> bool:
|
||||||
|
"""True when unused in both windows, so it is safe to park."""
|
||||||
|
return self.short_calls == 0 and self.long_calls == 0
|
||||||
|
|
||||||
|
|
||||||
|
def _scan(pattern: re.Pattern[str], since: float) -> Counter[str]:
|
||||||
|
"""Count regex matches across transcripts modified after *since*."""
|
||||||
|
found: Counter[str] = Counter()
|
||||||
|
for path in TRANSCRIPT_ROOT.glob("*/*.jsonl"):
|
||||||
|
try:
|
||||||
|
if path.stat().st_mtime < since:
|
||||||
|
continue
|
||||||
|
text = path.read_text(errors="replace")
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
found.update(pattern.findall(text))
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def usage_for(
|
||||||
|
names: list[str], pattern: re.Pattern[str], now: float | None = None
|
||||||
|
) -> list[Usage]:
|
||||||
|
"""Report short- and long-window call counts for each of *names*."""
|
||||||
|
now = time.time() if now is None else now
|
||||||
|
short = _scan(pattern, now - SHORT_WINDOW_DAYS * SECONDS_PER_DAY)
|
||||||
|
long_ = _scan(pattern, now - LONG_WINDOW_DAYS * SECONDS_PER_DAY)
|
||||||
|
return [Usage(n, short.get(n, 0), long_.get(n, 0)) for n in sorted(names)]
|
||||||
|
|
||||||
|
|
||||||
|
def mcp_usage(config: Path | None = None) -> list[Usage]:
|
||||||
|
"""Call counts for every globally registered MCP server."""
|
||||||
|
config = config or Path.home() / ".claude.json"
|
||||||
|
try:
|
||||||
|
names = list(json.loads(config.read_text()).get("mcpServers", {}))
|
||||||
|
except (json.JSONDecodeError, OSError):
|
||||||
|
return []
|
||||||
|
return usage_for(names, _MCP_CALL)
|
||||||
|
|
||||||
|
|
||||||
|
def skill_usage() -> list[Usage]:
|
||||||
|
"""Invocation counts for every personal skill."""
|
||||||
|
root = Path.home() / ".claude" / "skills"
|
||||||
|
names = [p.parent.name for p in root.glob("*/SKILL.md")]
|
||||||
|
return usage_for(names, _SKILL_CALL)
|
||||||
Loading…
Reference in New Issue
Block a user