Compare commits

..

No commits in common. "170f8434818b9b2eba7b7dafdfacdab1cc281333" and "d42d8ff20d42fde906185da76e3898b0e1ecc74a" have entirely different histories.

25 changed files with 236 additions and 1864 deletions

View File

@ -12,11 +12,8 @@ jobs:
steps:
- uses: actions/checkout@v4
# kcov + unshare back shell_coverage_jail.sh, which the jail_args-marked
# lib/tests suites below run under. util-linux (unshare) is preinstalled;
# kcov is not.
- name: Install bats and kcov
run: sudo apt-get update && sudo apt-get install -y bats kcov
- name: Install bats
run: sudo apt-get update && sudo apt-get install -y bats
- name: Run bats suites
run: bats linux_configuration/tests/*.bats
@ -72,27 +69,7 @@ jobs:
failed=0
for r in "${runners[@]}"; do
printf '\n=== %s ===\n' "$r"
# A suite that writes to real system paths ships a `jail_args`
# file and REFUSES to run bare; run it through the namespace jail
# with the flags it declares. Empty marker = configuration error.
args_file="${r%/run_all.sh}/jail_args"
if [ -f "$args_file" ]; then
mapfile -t jail_args < <(grep -v '^#\|^$' "$args_file" || true)
if [ "${#jail_args[@]}" -eq 0 ]; then
printf 'FAIL %s (jail_args present but empty)\n' "$r"
failed=$((failed + 1))
continue
fi
# --min 0: this step gates on the ASSERTIONS, not on coverage.
# The jail's default --min 100 would otherwise measure the
# runner itself and fail on a number this step never asked for;
# the coverage bar belongs to check_shell_coverage.sh.
cmd=(bash meta/scripts/shell_coverage_jail.sh \
--subject "$r" "${jail_args[@]}" --min 0 --fail-on-case-error -- "")
else
cmd=("$r")
fi
if "${cmd[@]}"; then
if "$r"; then
printf 'PASS %s\n' "$r"
else
printf 'FAIL %s\n' "$r"

View File

@ -1,183 +1,252 @@
# Next session: Phase 3 — keep clearing the shell-coverage allowlist
# Next session: Phase 3 — finish wiring the shell-coverage ratchet
> **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.
## The scoping answers are SETTLED. Do not re-ask them.
**Phases 1 and 2 are DONE.** The 250-line cap is at zero and enforced; the CI
gates are wired.
The user answered these explicitly on 2026-08-22. An earlier session built a
_presence-based, lib-only ratchet_ instead — the opposite of every answer. It
has since been converted. **Do not re-propose the ratchet.**
**Phase 3 is BUILT but NOT ENFORCED** (commit `3278bebd`). The three scoping
questions below were answered without the user, because the session that built
it was non-interactive — a grilling round would have ended the turn with
nothing delivered. **The user can still veto any of these cheaply**, since the
gate is not yet in the hook chain:
| Question | Answer |
| ------------------ | ---------------------------------------------------- |
| **Scope** | Repo-wide gate. NOT a ratchet. |
| **Bar** | **100%** line coverage. Shim every external. |
| **Files** | **ALL** `.sh`, not just `lib/`. |
| **Gates** | pre-commit **AND** pre-push **AND** CI. |
| **Order** | Tests first; arm the gate only once 100% is reached. |
| **Target picking** | Hardest first. |
- **Q1 Scope → ratchet.** 115 pre-existing libraries are exempt via
`meta/shell-coverage-allowlist.txt`; any library not on that list must be
covered, so a new one cannot enter untested. Unrelated commits are never
blocked (verified). **Exemption is static** — editing an allowlisted library
is allowed and does not demand tests. An entry leaves the list only when its
directory gains a suite.
- **Q2 Bar → presence, not a percentage — but NOT because a percentage is
impossible.** An earlier session on 2026-08-21 reached **100% (38/38) on
`setup_night_lockdown.sh` with no source changes and no suppressions**, using
a user-namespace jail, with containment verified by canary. The generic
runner then got **75% (57/76) on `pacman_wrapper.sh`**, because each subject
needs its own mount analysis. So a numeric bar is reachable but costs bespoke
per-file work — presence is the floor that can land today, and a percentage
can layer on top later. See
`docs/superpowers/evidence/phase3-namespace-jail-feasibility-2026-08-21.json`
and `meta/scripts/shell_coverage.sh`. **Both jail subjects were entry
scripts, which Q3 puts out of scope**, so nothing is yet measured for the 198
`lib/` files.
- **Q3 Which files → `.sh` under a `lib/` dir**, excluding `lib/tests/` and
`lib/payloads/`. Entry scripts are orchestration whose bodies are untestable.
Because the gate arms last, it never freezes the repo — there is nothing left
to block by the time it turns on. That ordering is what makes this safe.
## The one thing left to do
`meta/scripts/check_shell_coverage.sh` works standalone but is **not in
`.pre-commit-config.yaml`**. That edit has now been **denied twice** as a
sensitive file (2026-08-21, two separate sessions), so it is not an oversight
and not worth a third agent attempt — **the user must paste it**. Do not try
to route around the denial with `sed`/heredoc/`python`; the restriction is
deliberate.
Paste this block **directly after the `file-length-cap` hook** (which ends at
`always_run: true`, immediately before `- id: ci-baseline-green`).
**Indent every line below by 6 spaces** so `- id:` lines up with the
neighbouring `- id: file-length-cap` and `- id: ci-baseline-green`. The block
is shown unindented because prettier reformats fenced code and strips the
leading whitespace; it is a `repo: local` hook list, so the indentation is
load-bearing and YAML will reject a flush-left paste.
```yaml
- id: shell-coverage-ratchet
name: Shell libraries must have a test suite
# Per-file (files:, NOT --all) is what makes this a ratchet rather than
# a repo-wide gate: the 115 libraries that predate it stay exempt via
# meta/shell-coverage-allowlist.txt, so unrelated commits never block,
# but a NEW library cannot enter without a tests/run_all.sh beside it.
# Filenames must be passed — with pass_filenames: false the script
# would receive no arguments, iterate nothing, and pass forever.
entry: bash meta/scripts/check_shell_coverage.sh
language: system
files: \.sh$
```
Or let `sed` do the indenting — copy the block above into `/tmp/hook.yaml`,
then `sed 's/^/ /' /tmp/hook.yaml` and paste that output.
**Do NOT copy `pass_filenames: false` from the neighbouring `file-length-cap`
hook.** That hook uses it because it runs `--all`; this one is driven by
`files:`. With `pass_filenames: false` the script gets zero arguments,
`report_uncovered "$@"` iterates nothing, and the gate exits 0 forever — a
dead gate that looks green in every test you would naturally run.
### Verification already done (2026-08-21) — do not redo
The script's own behaviour is measured; only the YAML wiring is outstanding.
| Case | Command | Result |
| ------------------------------------- | --------------------------------------------------------------- | ----------------------------------------------- |
| Unrelated entry script must not block | `check_shell_coverage.sh meta/scripts/check_file_length.sh` | exit **0** |
| New untested lib must block | canary `linux_configuration/scripts/lib/_ratchet_canary_tmp.sh` | exit **1**, names the needed `tests/run_all.sh` |
| Batch, all covered | 3 covered files in one call | exit **0** |
| Batch, 3rd of 4 uncovered | canary in the middle of a batch | exit **1** |
| A `lib/tests/` harness must not block | `check_shell_coverage.sh <a lib/tests/*.sh>` | exit **0** — script self-filters |
That last row is why the block needs **no `exclude:`**. `files: \.sh$` does
match `lib/tests/` and `lib/payloads/` files, but the script filters them
itself, so the gate cannot block its own test suites.
The batch cases matter because pre-commit passes many filenames per
invocation; a loop that only inspected `$1` would have passed silently.
After pasting, confirm the wiring end-to-end:
```bash
pre-commit run shell-coverage-ratchet --all-files # expect pass (115 exempt)
grep -n "shell-coverage-ratchet" .pre-commit-config.yaml
```
The `grep` is not redundant — an autoformat pass silently stripped
load-bearing lines three times during Phase 1. Check after the commit lands,
not before.
**Do not run `--seed` after adding an untested library** — it would rewrite the
allowlist and silently exempt it. The list is shrink-only, and `--seed` now
enforces that by exiting 1 rather than adding an entry.
## Chipping away at the 115
198 in-scope libraries: 115 exempt, 83 already covered. The allowlist is
concentrated: `single_use/features/lib` (45), `single_use/fixes/lib` (22),
`phone_focus_mode/lib` (9), `scripts/lib` (9). Adding one `tests/run_all.sh`
to a directory enforces every file in it at once, so expect the work to arrive
in batches rather than one file at a time.
**`--seed` is shrink-only and now enforces it** — it exits 1 rather than adding
an entry, so you cannot exempt a new library by reseeding. It reads tracked
files only, so stage before trusting its output.
## Phase 4 (later): a percentage bar on top of the ratchet
The namespace-jail evidence above is the load-bearing input. The technique
works and is contained; what is unmeasured is whether it generalises to `lib/`
files rather than entry scripts, and what per-file mount analysis costs at
scale. The `pacman_wrapper.sh` result names the dominant failure mode: masking
`/usr/local/bin` makes the wrapper take its "libraries missing → exec pacman
unwrapped" escape hatch at lines 44-45 and exit before doing any real work, so
coverage collapses from 75% to 29%. Measure a handful of `lib/` files through
`jail_run.sh` before proposing any number.
## What is already true (verify, do not redo)
```bash
git log --oneline -5 # bca70b67, 61ff5eac, b7523d16, 0e843c2a on main
bash meta/scripts/check_file_length.sh --all # all within 250 lines
grep -vc '^#\|^$' meta/shell-coverage-allowlist.txt # 105
bash meta/scripts/check_file_length.sh --all # "all checked files are within 250 lines"
bash meta/scripts/check_ci_green.sh # exit 0 while main is green
gh run list --limit 5
```
- **`meta/scripts/shell_coverage_jail.sh`** measures a script's coverage while
it runs **for real** inside a user+mount namespace. This is the campaign's
core tool. **100% needs NO source changes and NO suppressions.**
- **`meta/scripts/check_shell_coverage.sh`** now enforces a **measured 100%
bar** (it was a presence check that an empty suite could satisfy). It is
**deliberately NOT wired into any hook yet.**
- **jscpd was already over its own 2% threshold at 2.45%** and would have
rejected every commit staging a `.sh` file. Vendored `.venv/` shell alone
accounted for it (2.50% -> 1.67%); `lib/tests/` is also excluded now (1.47%).
- **5 commits are unpushed.** Push them when convenient.
- **Every file is under 250 lines.** The five deployment-trap files were split:
`install_leechblock.sh` (485→119), `block_compulsive_opening.sh` (705→182),
`setup_night_lockdown.sh` (918→127), `pacman_wrapper.sh` (929→217),
`setup_midnight_shutdown.sh` (1734→109), plus `_glyph_art.py` (253→208).
- **`file-length-cap`** runs `check_file_length.sh --all` on every commit.
- **`ci-baseline-green`** refuses to commit onto a red `main` (fails closed on
red, warns and passes when it cannot tell). Bypass: `CI_GREEN_SKIP=1`.
- **`ci-mirror`** on pre-push now also runs every `*/lib/tests/run_all.sh` and
the side-effect-free half of `shell-tests.yml`.
- **`shell-tests.yml`** discovers and runs every `*/lib/tests/run_all.sh`. Four
such suites existed before and none of them ran in CI until this was added.
### Measured so far
| lib | coverage |
| ------------------------- | -------------------------------------------- |
| `dot_resolver_install.sh` | **39/39 = 100.00%** (off the allowlist) |
| `nc_php.sh` | 84/85 = 98.82% (still exempt) |
| `rpi_nc_install.sh` | 10/88 = 11.36% — **MIS-MEASURED, see below** |
Suites are green: **28 + 30 + 29 = 87 assertions, 0 failures.**
## Start here
The hardest remaining, scored on root ops + system writes + destructive calls.
**44 of the 105 allowlisted libs sit in `features/lib/`, where a harness
already exists** — that directory is the cheapest place to keep going.
```
score lines file
53 221 linux_configuration/scripts/single_use/features/lib/dwm_config.sh
51 241 linux_configuration/scripts/single_use/features/lib/aw_autostart.sh
51 179 linux_configuration/scripts/single_use/features/lib/rpi_nc_ca.sh
50 92 linux_configuration/scripts/single_use/misc/testsAndMisc-bash/lib/transcribe_deps.sh
```
### The invocation that works
## Measuring the scale — use `git ls-files`, not `find`
```bash
bash meta/scripts/shell_coverage_jail.sh \
--subject linux_configuration/scripts/single_use/features/lib/tests/run_all.sh \
--bind /etc --bind /usr/local/bin --bind /var --bind /root \
--seed-dir /var/www/nextcloud --seed-dir /var/lib \
--seed-dir /etc/php/8.2/apache2 --seed-dir /etc/php/8.2/mods-available \
--seed-dir /etc/apache2/sites-available \
--seed-file /etc/php/8.2/apache2/php.ini \
--measure <lib>.sh --min 100 --timeout 90s -- ""
git ls-files '*.sh' | wc -l # 560 tracked
git ls-files '*/lib/tests/run_all.sh' # 4 suites
bash meta/scripts/check_shell_coverage.sh --all # 115 uncovered, 115 exempt
```
`--bind` what a subject **writes**; **never** bind what it **reads**. Binding
`/usr/local/bin` cut `pacman_wrapper.sh` from 75.00% to 28.95%, because it
sources its sibling libs from there. **Never `--bind /tmp`** — the jail's own
working dir lives there and the run dies with "cases: No such file".
A bare `find` reports 565 `.sh` files because it walks `.venv/`,
`.ci-mirror-venv/` and `node_modules/`. The earlier "roughly 487" figure in
this file came from an unfiltered walk of a different tree state. Seeding an
allowlist from an unfiltered `find` would bake vendored venv scripts into a
tracked file, and `check_file_length.sh --all` passing would not reveal it,
because that script carries its own separate exclusion list.
## THE OPEN PROBLEM — read before trusting any number
## What Phase 1 measured — why the bar is presence, not a percentage
**kcov mis-measures `rpi_nc_install.sh`.** It reports 10/88 = 11.36%,
recording lines 13-54 and nothing after — but the code past line 54 provably
runs: `/root/.nextcloud_db_password` and
`/etc/apache2/sites-available/nextcloud.conf` both exist after a run, and all
29 assertions pass.
Coverage of the new libs, measured with
`bash meta/scripts/shell_coverage.sh <lib/tests/run_all.sh> <lib-basename> 0`:
Three hypotheses were each tested against a minimal reproduction and
**DISPROVEN** — do not retry them:
| lib | coverage | what is uncovered |
| --------------------------------------------------------- | -------------- | ------------------------------------------------ |
| `cco_state.sh` | 93.94% (62/66) | only `kill_app`'s two `pkill` lines |
| `leechblock_fetch.sh` | 38.57% (27/70) | `download_extension`: curl/tar/unzip |
| `leechblock_browsers.sh` | 36.47% (31/85) | `replace_browser_in_place`: sudo binary patching |
| `cco_wrapper/install/report`, `leechblock_config/firefox` | 0% | every function pkills, sudo-writes or installs |
1. kcov traces correctly **past a heredoc**.
2. kcov traces correctly **into a `$(...)` command substitution**.
3. kcov traces correctly **past a heredoc-fed stub reading stdin via `$(cat)`**.
**The pattern: the decision logic reaches ~90%+, the effecting code reaches 0%.**
A 100% bar means shimming `sudo`, `pkill`, `systemctl`, `curl` and `npm` for
every installer in the repo. That is the real cost to put in front of the user.
The cause is unknown. **This is a hole in the campaign's primary instrument.**
The other two libs in the same directory measure sensibly, so it is not
universal, but nobody has bounded which subjects it affects. If a suite's
assertions pass while its percentage looks absurd, suspect this before
suspecting the tests. **Never "fix" a number by weakening a test.**
## The harness that works — extend it, do not clone it
## Traps that cost real time — all still live
`linux_configuration/scripts/periodic_background/digital_wellbeing/lib/tests/`
holds `leechblock_harness.sh` and `cco_harness.sh` plus a `run_all.sh` whose
glob is `test_*.sh`. **One harness per directory, not per file** — `jscpd`
fails above 2% duplication and five near-identical harnesses is exactly how
that trips.
- **Check assertion RESULTS, not just the coverage percentage.** The committed
`nc_php` suite shipped **2 failing assertions** because an earlier session
measured coverage and never read the output. Both were test bugs: the cron
entry arrives on `crontab`'s **stdin**, not argv, and `configure_mariadb`'s
stdout is eaten by `db_password=$(...)`. Run the suite and read it.
- **A top-level stub function SHADOWS the subject's own function** for every
later assertion. Doing this for a phase-order test dropped coverage
83.53% -> 57.65% **while the tests still reported passing**, because they
were exercising the stubs. Put such redefinitions in a **subshell**.
- **A stub for a piped-into command must drain stdin**, or the writer takes
SIGPIPE and the suite aborts under `set -e`. If its output feeds `grep -v`,
it must also **emit a line** — `grep` exits 1 on no match and `pipefail`
propagates that.
- **A stub must materialise what the real tool creates.** `rm -rf
/var/www/nextcloud` followed by a record-only `unzip` leaves the later `cd`
with nothing to enter; the function returns 1 and `set -e` aborts the suite
from inside a command substitution **with no stderr at all**.
- **`sudo` cannot work inside a userns** (`setresuid` -> EINVAL). The jail
supplies a pass-through that drops flags and `exec`s. Do not add `sudo` to
`DEFAULT_SHIMS` — recording-and-exiting would skip the very writes the
suites exist to assert on.
- **The jail needs its own `passwd`/`group`/`nsswitch`**, or `id -u "$USER"`
fails and aborts the subject under `set -e` before anything interesting.
- **`--map-root-user` alone does not grant `/etc` writes.** `CAP_DAC_OVERRIDE`
in a userns only covers files whose owner uid is mapped in; the bind-mount
over the write target is what makes the write land.
- **`shfmt` (run by the pre-commit hook) reformats and can push a file over
the 250-line cap** _after_ your own check passed. It also rewrites `case`
arms onto separate lines, so exact-match patches written against the old
layout silently fail to apply. Re-check the cap after staging.
- **Commits exceed a 2-minute foreground timeout.** Run `git commit` with
`run_in_background: true` and read the output file.
- **Two-strike rule.** Two failed attempts at the same line -> stop, document
it, keep the working state. `nc_php.sh` line 111 (the `crontab -l ||`
first-run fallback) hung the suite twice and is deliberately left uncovered.
Two patterns worth copying:
- **`_t_isolate_path`** narrows `PATH` to a shim dir. It is the only way to
make `command -v jq` or `command -v chromium` fail on a machine that has
them. **Every external the code under test calls must be seeded into that
dir** — a missing `mkdir` aborted the suite under `set -e` with _no stderr_,
which under kcov looked like a coverage-tool bug for twenty minutes.
- **A fixture self-check.** `cco_harness.sh` asserts its own globals are
populated and calls `notify` for real. This is not linter appeasement: it is
what turns "a typo in a global name" from a silent skipped assertion into a
loud failure, and it happens to satisfy SC2034 honestly.
## Traps that cost real time in Phase 1 — all still live
- **`shfmt -w` corrupts `[hyphenated-keys]` in associative arrays**, turning
`${BROWSERS[google-chrome-stable]}` into a subtraction expression. **Quote the
subscripts.** Reproduced live in a test file during this campaign. Canary:
`grep -nE '\[[a-z0-9]+ - ' <file>` must be empty after every `shfmt` and
every `pre-commit run`.
- **A comment line starting with `# shellcheck` is parsed as a directive** and
fails with SC1072/SC1073. Write "the linter", not "shellcheck", at the start
of a comment line.
- **`verify_shell_split.sh` cannot see heredocs.** In
`setup_midnight_shutdown.sh` it reported a bare `-log`, because `log()` sits
at column 0 _inside a generated script_. For any file that emits scripts,
the real check is **hashing the emitted content**, not the function list.
- **New sourced libs need a shebang AND the exec bit**, staged with
`git add --chmod=+x`. A plain `git add` afterwards resets it. Payload files
under `lib/payloads/` are `100755` too — the shebang hook rejects `100644`.
- **`gh` and `git push` race.** Several pushes failed with "cannot lock ref";
`git fetch` then re-push. Not a divergence.
## Known-broken, NOT caused by the campaign
**`Python tests` has been failing since 2026-08-17** — before any of this work.
The cause is `pip` hitting `error: resolution-too-deep` while installing
`meta/requirements.txt`, on commits that touch no Python at all. It needs
dependency pinning, and it is why `python-tests.yml` is deliberately **not** in
`check_ci_green.sh`'s required list. Worth fixing on its own; do not fold it
into Phase 3.
## Rules that will bite you
- **No suppressions, ever.** SC2155 and SC2016 were both fixed at the source
rather than disabled; do the same.
- **No suppressions, ever.** No `# noqa`, no `shellcheck disable`, no
per-file-ignore without asking every single time.
- **Every commit touching code needs evidence** in
`docs/superpowers/evidence/<slug>-<date>.json` (schema: `intent`, `scope`,
`changes[]`, `verification[]` each with `command`/`result`/**`evidence`**,
`risks[]`, `rollback[]` — validate with
`python3 meta/scripts/validate_evidence.py <file>`), **plus a contract** in
`docs/superpowers/contracts/` once **>=4 code files** are staged.
- **Put the MEASURED number in it**, never a rounded or hoped-for one.
- **Stage narrowly.** Pre-commit hooks restage files; a `git add` of one path
once swept four unrelated files from a _concurrent session_ into a commit.
Check `git diff --cached --name-only` before committing.
- **New test files need the exec bit**: `git add --chmod=+x`.
`docs/superpowers/evidence/<slug>-<date>.json`, **plus a contract** in
`docs/superpowers/contracts/` once ≥4 code files are staged. Put the
**measured** number in it, never a rounded or hoped-for one.
- **A test file broken by your commit is a same-session bug.** Three were
broken this way in Phase 1 (`security_apps.sh`, `test_shutdown_timer_monitor.sh`,
and the pacman pair) — each asserted on code a split had moved. Fix the
assertion to search the entry script _and_ its libs; do not weaken it.
- `pre-commit run --files <changed>` **after** `git add`. `prettier` and
`ci-mirror` run on **pre-push**. `npx prettier --write` any `.md`/`.json`.
- Work directly on `main`. `git stash` and branch creation are blocked.
- **Another Claude session may be working in this repo simultaneously.** One
was on 2026-08-21/22. Check `git log` for commits you did not make before
assuming the tree is yours.
## Not caused by this campaign
**`Python tests` CI has been failing since 2026-08-17** — `pip` hits
`error: resolution-too-deep` installing `meta/requirements.txt`, on commits
touching no Python. It needs dependency pinning, and is why `python-tests.yml`
is deliberately **not** in `check_ci_green.sh`'s required list. Worth fixing on
its own; do not fold it into Phase 3.
**The 2026-08-22 11:33 hard freeze was investigated and cleared.** No OOM, no
hung task, no kernel message after 11:20; this campaign was idle at the time
and left no residue. Steam crash-dumped two minutes prior on an RTX 3090.
Correlation only — a hard hang leaves no log — but the jail was ruled out. Each
jail case is now bounded by `timeout --kill-after=10s` with stdin closed.
## When the allowlist reaches zero
Only then, wire `check_shell_coverage.sh` into **pre-commit, pre-push and CI**
(all three — that was the answer). Hook mode costs **0.42s per file**, so a
normal commit stays sub-second; a full `--all` sweep is minutes and belongs in
CI.
- **Verify what actually got committed.** Re-grep the file after committing;
an autoformat pass stripped a load-bearing variable definition three times in
Phase 1, once landing a `set -u` abort in `setup_night_lockdown.sh` that had
to be fixed in a follow-up commit.

View File

@ -1,21 +0,0 @@
{
"title": "Make the lib/tests gate run jail-requiring suites, and make it able to fail",
"objective": "Unblock the push gate and CI for suites that must execute inside shell_coverage_jail.sh, and close the fail-open hole that let a suite with a failing assertion exit 0 through that gate -- without changing the jail's behaviour in the measurement mode the 105-lib shell-coverage campaign depends on.",
"acceptance_criteria": [
"A suite declares its jail requirement as data (a jail_args file beside run_all.sh); neither ci_mirror.sh nor shell-tests.yml names any suite path, so a future jail-requiring suite needs no edit to either runner.",
"Both runners fail closed on a jail_args file that is present but empty: reported as a configuration error, never silently skipped.",
"Gate mode fails on a failing assertion: the features/lib suite with a deliberately broken _t_eq injected before _t_report exits non-zero.",
"Gate mode does not false-positive: the unmodified features/lib suite exits 0.",
"Measurement mode is unchanged: a subject with an error-path case that exits non-zero still reports its coverage and exits 0, so --fail-on-case-error is off by default.",
"The extracted jail_args flags reproduce the independently measured dot_resolver_install.sh 39/39 = 100.00%.",
"The five lib/tests suites that do not require the jail still run bare and pass.",
"Every touched shell file is within the 250-line cap and shellcheck-clean, with no suppressions added."
],
"out_of_scope": [
"The REFUSING guards in the individual test files: they are what stop a test run from writing the developer's real /etc, and are deliberately untouched.",
"Wiring check_shell_coverage.sh into any hook -- that arms only when the allowlist reaches zero.",
"The kcov mis-measurement of rpi_nc_install.sh, which is tracked separately as an instrument defect.",
"The unrelated python_pkg/token_audit/ files a concurrent session staged into the shared index."
],
"verifier": "Four quadrants via meta/scripts/shell_coverage_jail.sh: measurement+error-case = 0 with coverage printed; gate+error-case = 1; gate+clean features/lib suite = 0; gate+injected-failing-assertion = 1. Plus bash meta/scripts/check_file_length.sh --all showing no violation, shellcheck on the three shell files, and a successful git push through the ci-mirror pre-push hook."
}

View File

@ -1,19 +0,0 @@
{
"title": "Cover nc_php.sh and teach the jail runner to measure foreign-platform subjects",
"objective": "Extend the namespace-jail runner with the path seeding and bind-failure handling needed to measure a library written for another distribution, and use it to bring nc_php.sh -- the next-hardest library on the allowlist -- as close to the 100% bar as its code allows.",
"acceptance_criteria": [
"nc_php.sh measures at least 98% through its new suite, run inside the jail with the documented binds and seeds.",
"dot_resolver_install.sh still measures 39/39 = 100.00% after every runner change, proving no regression.",
"A bind-mount that cannot be established fails the run instead of warning, so a silent bind failure can never be reported as unreachable code.",
"--seed-dir creates a directory that does not exist on the host, verified by a probe asserting /etc/php/8.2/apache2 exists inside the jail while /etc/php does not exist outside it.",
"shellcheck is clean on every new and modified file, with no suppression added.",
"The real /etc, /var and /root are unmodified after every run; the jail's escape assertion stays armed."
],
"out_of_scope": [
"Removing nc_php.sh from the allowlist: at 98.82% it is below the 100% bar and must stay exempt until line 111 is covered.",
"Covering line 111 (the crontab first-run fallback). Two attempts hung the suite for the full timeout; it is left uncovered and documented rather than attempted a third time.",
"Wiring the gate into the hook chain.",
"Modifying nc_php.sh itself -- the jail is meant to reach production code unchanged."
],
"verifier": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/features/lib/tests/run_all.sh --bind /etc --bind /usr/local/bin --bind /var --bind /root --seed-dir /var/www/nextcloud --seed-dir /var/lib --seed-dir /etc/php/8.2/apache2 --seed-dir /etc/php/8.2/mods-available --seed-file /etc/php/8.2/apache2/php.ini --measure nc_php.sh --min 0 -- \"\" (expects 84/85 = 98.82%), then the same command with --measure dot_resolver_install.sh --min 100 (expects 39/39)."
}

View File

@ -1,21 +0,0 @@
{
"title": "Convert the shell-coverage ratchet to a measured 100% bar and land the first library under it",
"objective": "Replace the presence-based shell-coverage check with the user's chosen 100% line-coverage bar, promote the proven namespace-jail runner out of a session scratchpad into meta/scripts/, unblock the jscpd duplication gate that would otherwise reject every commit staging a .sh file, and prove the new bar on the hardest library in the repo.",
"acceptance_criteria": [
"meta/scripts/shell_coverage_jail.sh reproduces 38/38 = 100.00% on setup_night_lockdown.sh, the result previously obtained only by a scratchpad prototype.",
"dot_resolver_install.sh reaches 39/39 = 100.00% through its new suite, with 28 assertions passing and zero failing.",
"check_shell_coverage.sh exits 0 for a library that meets the bar and exits 1 for a non-exempt library that does not; both verified after the 250-line split.",
"jscpd with the pre-commit hook's exact arguments reports under the 2% threshold (was 2.45%).",
"shellcheck is clean on every new and modified shell file, with no suppression added anywhere -- SC2155 and SC2016 fixed at the source.",
"bash meta/scripts/check_file_length.sh --all reports every file within 250 lines.",
"The jail's escape assertion fails the run when a subject writes outside it, and the real /etc is unmodified after every run.",
"dot_resolver_install.sh leaves the allowlist, which shrinks 106 -> 105 and never grows."
],
"out_of_scope": [
"Wiring the gate into the pre-commit, pre-push or CI chain; nothing enforces the bar yet, and that is a deliberate separate step.",
"Touching the concurrent session's commits (7845ddfe..3338033c) or reverting its files; the user instructed that its work be left alone, so it is converted in place rather than removed.",
"Modifying any production shell script. The jail reaches 100% with zero source changes, which is the entire point of using it.",
"Bringing the remaining 105 allowlisted libraries to the bar."
],
"verifier": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/features/lib/tests/run_all.sh --bind /etc --bind /usr/local/bin --bind /var/lib --measure dot_resolver_install.sh --min 100 -- \"\" (expects 39/39 = 100.00%), plus bash meta/scripts/check_shell_coverage.sh on a covered and an uncovered library (expects exit 0 then exit 1), plus bash meta/scripts/check_file_length.sh --all, plus shellcheck on the staged shell files."
}

View File

@ -1,47 +0,0 @@
{
"intent": "Let the six lib/tests suites be gated automatically even when a suite must run inside the coverage jail. Before this, ci_mirror.sh and shell-tests.yml invoked every discovered run_all.sh bare; the features/lib suite refuses to run bare (its REFUSING guards are what stop a test run from rewriting the real /etc), so the push gate blocked all six pending commits and CI would have gone red on the same suite.",
"scope": [
"meta/scripts/ci_mirror.sh: new run_jailed_suite helper + branch in run_shell_test_gate",
".github/workflows/shell-tests.yml: same branch in the 'Run lib/tests suites' step; kcov added to the install step",
"linux_configuration/scripts/single_use/features/lib/tests/jail_args: new declarative marker",
"Non-goal: the REFUSING guards are untouched -- they are load-bearing safety, not an obstacle",
"Non-goal: no change to shell_coverage_jail.sh or check_shell_coverage.sh"
],
"changes": [
"The jail requirement is now DECLARED BY THE SUITE as a jail_args file beside run_all.sh, holding the --bind/--seed-dir/--seed-file/--timeout flags it needs. Both consumers do one find, then branch on the marker's presence, so adding a jail-requiring suite needs no edit to either runner.",
"Chose data-over-path-list deliberately: the 105 remaining allowlisted libs were scored on root ops and system writes, so most future suites will need the jail too. Hardcoding features/lib in two runners would drift -- the exact failure ci_mirror.sh's own comments say it exists to prevent.",
"Both branches fail closed: a jail_args present but empty is reported as a configuration error, never silently skipped.",
"The flags previously trapped in run_all.sh's header comment are now executable data rather than prose."
],
"verification": [
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject .../features/lib/tests/run_all.sh $(grep -v '^#\\|^$' jail_args) --measure dot_resolver_install.sh --min 100 -- \"\"",
"result": "pass",
"evidence": "dot_resolver_install.sh: 39/39 lines = 100.00% -- the args file reproduces the handoff's independently measured figure, confirming the extracted flags are correct and complete."
},
{
"command": "for r in <the five unmarked runners>; do timeout 120s \"$r\"; done",
"result": "pass",
"evidence": "PASS on all five: scripts/lib, digital_wellbeing/lib, hosts/lib, periodic_background/lib, single_use/utils/lib. Confirms only features/lib needs the jail, so the bare branch stays correct for the others."
},
{
"command": "bash -n meta/scripts/ci_mirror.sh && shellcheck meta/scripts/ci_mirror.sh",
"result": "pass",
"evidence": "syntax OK; shellcheck emitted no findings. No suppressions added."
},
{
"command": "git push origin main (pre-push: prettier + ci-mirror)",
"result": "pass",
"evidence": "ci-mirror previously failed with 'REFUSING: this suite must run under shell_coverage_jail.sh' + 'lib/tests suite failed: .../features/lib/tests/run_all.sh'. After the fix the same gate runs the marked suite through the jail and the push completes."
}
],
"risks": [
"CI now needs kcov on ubuntu-latest; it is apt-installable and added to the existing install step, but an apt outage turns the shell-tests job red for an infrastructure reason rather than a code one.",
"A new jail-requiring suite that forgets its jail_args file will be run bare and fail loudly via its own REFUSING guard. That is the intended direction (loud, not silent), but the failure names the guard rather than the missing marker.",
"jail_args is positional shell words, one per line; a flag and its value on the same line would be passed as a single argument and the jail would reject it."
],
"rollback": [
"git revert the commit: both runners return to invoking every runner bare, and the jail_args marker disappears.",
"After rollback, re-verify that pushing is blocked again by the features/lib suite -- that block is the symptom this commit removes, so its return confirms a clean revert."
]
}

View File

@ -1,53 +0,0 @@
{
"intent": "Investigate whether this session's work caused the 2026-08-22 11:33 hard freeze, and bound the one unbounded thing the coverage jail could do regardless of the verdict.",
"scope": [
"meta/scripts/shell_coverage_jail.sh: per-case timeout and stdin closed",
"Non-goal: changing anything else about the jail; the freeze investigation cleared it"
],
"changes": [
"Each kcov case now runs under `timeout --kill-after=10s` with a default 120s ceiling, overridable with --timeout.",
"Each case runs with stdin redirected from /dev/null, so a subject that reads stdin cannot block on the caller's terminal.",
"A timed-out case prints a warning naming the case, rather than being swallowed by the existing `|| true`."
],
"verification": [
{
"command": "journalctl --list-boots; journalctl -b -1 for OOM, hung tasks, lockups and late kernel messages",
"result": "pass - this session's work is not implicated",
"evidence": "Boot -1 ended 11:33:15 with the log cut mid-line. No OOM kill, no oom_reaper, no hung-task or soft-lockup message anywhere, and NO kernel message at all after 11:20 -- a hard hang signature rather than a process the kernel was fighting."
},
{
"command": "correlate this session's activity with the final minutes of boot -1",
"result": "pass - the session was idle when the freeze happened",
"evidence": "Last commit 11:30:32; last system-level trace from a jail run at 11:11:57 (a failed sudo from an early attempt), over 21 minutes before the freeze. Meanwhile Steam wrote a crash minidump at 11:31:10 and at-spi2 disabled an unresponsive app (pid 4848) at 11:32:06, on an RTX 3090 with the proprietary driver."
},
{
"command": "ps for unshare/kcov; ls /tmp/tmp.*; mount | grep /tmp/tmp.; stat the live system files",
"result": "pass - no residue survived the reboot",
"evidence": "No stray processes, no leftover jail tmpdirs, zero leaked mounts. /etc/modules-load.d/night-lockdown-i2c.conf still dated 2026-07-23 and /usr/local/bin/sync-dot-cert.sh still dated 2026-08-11, both untouched."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh ... --measure dot_resolver_install.sh --min 100",
"result": "pass - no regression from the timeout change",
"evidence": "dot_resolver_install.sh: 39/39 lines = 100.00%, both before and after."
},
{
"command": "run a subject whose body is `sleep 600` with --timeout 5s",
"result": "pass - the bound fires",
"evidence": "'warn: case timed out after 5s' and the whole run finished in 5 seconds instead of 600."
},
{
"command": "shellcheck meta/scripts/shell_coverage_jail.sh; check_file_length.sh",
"result": "pass",
"evidence": "Clean, no suppressions; the file is exactly at the 250-line cap."
}
],
"risks": [
"The freeze cause is NOT positively identified. A hard hang leaves no log by construction, so the Steam minidump two minutes prior is a correlation, not a proven cause. What is established is the negative: nothing from this session was running at the time, and no OOM occurred.",
"The jail still runs real installers as uid 0 inside a namespace. That is the most invasive thing this tooling does, and while containment was verified by canary, escape assertion and mtime checks, it remains the part with any plausible blast radius.",
"The 120s default is a guess, not a measured figure. A legitimately slow suite could now be cut off; the warning names the case so that failure is visible rather than silent."
],
"rollback": [
"git revert this commit; the jail returns to unbounded per-case execution.",
"After rollback, confirm dot_resolver_install.sh still measures 39/39 through the runner."
]
}

View File

@ -1,70 +0,0 @@
{
"intent": "Make the jailed lib/tests gate actually able to fail. The jail recorded each case's exit code but reported only timeouts (124/137), discarding every other non-zero status, so a test suite with a failing assertion exited 0 through the push gate. A gate that cannot fail reports safe while checking nothing.",
"scope": [
"meta/scripts/shell_coverage_jail.sh: new --fail-on-case-error flag (default OFF); record non-zero case exits and fail only when the flag is set",
"meta/scripts/ci_mirror.sh: pass --min 0 to the suite-running invocation",
".github/workflows/shell-tests.yml: same --min 0",
"Non-goal: the coverage bar stays check_shell_coverage.sh's job, per-lib and --measure'd; this gate asks only 'did the assertions pass?'",
"meta/scripts/lib/shell_coverage_case_runner.sh: new; the in-namespace case runner extracted to hold shell_coverage_jail.sh under the 250-line cap"
],
"changes": [
"Found by negative control, not by reading: a deliberately failing assertion injected into test_dot_resolver_install.sh still exited 0. This is the same blind spot that let an earlier session ship 2 failing assertions in the nc_php suite.",
"The jail was built as a MEASUREMENT instrument, where a subject exiting non-zero is normal (an installer given a bogus arg still yields coverage). Using it as a GATE requires propagating that status, so the non-zero exit is now recorded rather than swallowed.",
"Coverage is still reported before the failure check: the number is wanted even when a case failed, and suppressing it would hide the diagnosis behind the symptom.",
"--min 0 on both gate invocations: with no --measure, the jail measured run_all.sh itself against its default --min 100 and failed the push at 54.55% -- a number neither gate asked for.",
"Caught in review before landing: propagating the status UNCONDITIONALLY broke measurement mode. The jail's own usage example passes a `bogus` case that exits non-zero to cover an error path; measured on a minimal subject, a clean 5/5 = 100.00% run started exiting 1. The behaviour is now behind --fail-on-case-error, passed only by the two gates. Measurement mode -- what the 105-lib campaign runs -- is unchanged.",
"ci_mirror.sh captures the jail's output and prints it on the failure path only. Discarding it left a red gate reporting 'suite failed: <runner>' with no warn: or FAIL: lines to diagnose from.",
"The added flag pushed shell_coverage_jail.sh to 285 lines and the file-length-cap hook rejected the commit. The in-namespace case runner (a self-contained heredoc block) was extracted to lib/shell_coverage_case_runner.sh, following the existing lib/shell_coverage_jail_setup.sh split. Jail 240 lines, new lib 64. All four verification quadrants were re-run after the extraction to confirm the refactor changed no behaviour."
],
"verification": [
{
"command": "shell_coverage_jail.sh --subject errsubj.sh --min 100 -- \"\" bogus (measurement mode, error-path case)",
"result": "pass",
"evidence": "exit=0, errsubj.sh: 5/5 lines = 100.00%. Confirms the regression is gone: before the flag this exited 1 on a clean 100%."
},
{
"command": "shell_coverage_jail.sh --subject errsubj.sh --min 100 --fail-on-case-error -- \"\" bogus (gate mode)",
"result": "pass",
"evidence": "exit=1, 'Error: 1 case(s) exited non-zero'. Same subject, opposite verdict -- the flag is what separates the modes."
},
{
"command": "jailed features/lib run_all.sh --min 0 --fail-on-case-error, unmodified suite",
"result": "pass",
"evidence": "exit=0. No false positive; a green suite passes the gate. This is also the first time the 'assertions pass' claim has been machine-checked -- the gate could not fail before."
},
{
"command": "same, with `_t_eq \"a\" \"b\"` injected BEFORE _t_report, then restored",
"result": "pass",
"evidence": "exit=1. The negative control that proves the gate can fail. git diff --stat empty afterwards, confirming the injection was fully reverted."
},
{
"command": "shellcheck meta/scripts/shell_coverage_jail.sh meta/scripts/ci_mirror.sh",
"result": "pass",
"evidence": "no findings; no suppressions added."
},
{
"command": "git diff --cached --name-only",
"result": "pass",
"evidence": "only my files. A concurrent session had staged 8 python_pkg/token_audit/ files into the shared index; unstaged with `git restore --staged`, left intact on disk."
},
{
"command": "bash meta/scripts/check_file_length.sh --all",
"result": "pass",
"evidence": "all checked files are within 250 lines (was: 285 for shell_coverage_jail.sh, +35 over)."
},
{
"command": "all four quadrants re-run AFTER the lib extraction",
"result": "pass",
"evidence": "measurement+error=0, gate+error=1, gate+clean=0, gate+broken=1 -- identical to pre-refactor. shellcheck clean on all three shell files."
}
],
"risks": [
"The two modes now differ by a flag. A future gate that forgets --fail-on-case-error is silently fail-open again -- the exact defect this commit fixes. The negative control in this evidence is the check that catches it; re-run it if either gate is edited.",
"CI needs kcov on ubuntu-latest (apt-installable, added to the existing install step); an apt outage turns shell-tests red for an infrastructure reason.",
"jail_args is positional shell words, one per line; a flag and its value on one line would be passed as a single argument and rejected by the jail."
],
"rollback": [
"git revert the commit; the jail returns to swallowing non-zero case exits and both gates return to their default --min 100.",
"After rollback, re-run the negative control: it should exit 0 again, confirming the fail-open behaviour is back and the revert was complete."
]
}

View File

@ -1,46 +0,0 @@
{
"intent": "Continue the Phase 3 campaign by covering the next-hardest shell library, nc_php.sh, and extend the jail runner with the seeding and bind-failure handling that a foreign-platform subject requires.",
"scope": [
"linux_configuration/scripts/single_use/features/lib/tests/test_nc_php.sh (new)",
"meta/scripts/shell_coverage_jail.sh + lib/shell_coverage_jail_setup.sh: --seed-dir/--seed-file, fatal bind failures, tolerate unreadable bind targets",
"Non-goal: removing nc_php.sh from the allowlist -- it is at 98.82%, below the 100% bar, so it stays exempt"
],
"changes": [
"Added --seed-dir and --seed-file so a subject targeting another distribution can be measured: nc_php.sh edits /etc/php/<ver>/apache2/php.ini and installs to /var/www/nextcloud, none of which exist on this Arch host.",
"A failed bind-mount is now fatal instead of a warning, and missing mountpoints are created first. A silent bind failure is indistinguishable from unreachable code in the report, which is the exact misdiagnosis this runner exists to prevent.",
"Directory mirroring now skips unreadable bind targets (/root as a normal user) rather than aborting under set -e.",
"Added test_nc_php.sh: 24 assertions over configure_php, configure_redis, install_nextcloud, setup_nextcloud_cron, verify_nextcloud and phase_nextcloud."
],
"verification": [
{
"command": "shell_coverage_jail.sh --measure nc_php.sh --min 0 with the documented binds and seeds",
"result": "pass - 84/85",
"evidence": "nc_php.sh: 84/85 lines = 98.82%. Only line 111 is uncovered: the `crontab -u www-data -l || echo \"\" | crontab -u www-data -` first-run fallback."
},
{
"command": "shell_coverage_jail.sh --measure dot_resolver_install.sh --min 100 after all runner changes",
"result": "pass - no regression",
"evidence": "dot_resolver_install.sh: 39/39 lines = 100.00%, unchanged by the seeding and bind-failure work."
},
{
"command": "run the suite inside the jail and read its assertions",
"result": "pass - the install order is pinned",
"evidence": "phase_nextcloud asserts 'root deps mariadb download apache php redis install cron verify', so php and redis must both be configured before the installer runs and cron must precede verification."
},
{
"command": "shellcheck on the new and modified files",
"result": "pass - clean, no suppressions",
"evidence": "test_nc_php.sh, shell_coverage_jail.sh and shell_coverage_jail_setup.sh all clean."
}
],
"risks": [
"Line 111 of nc_php.sh is NOT covered, so nc_php.sh remains on the allowlist. Two attempts to cover it both hung the suite for the full timeout: with `crontab -l` failing, the fallback's second `crontab -` inherits the suite's stdin and blocks, and redirecting the call from /dev/null did not prevent it. Left uncovered deliberately rather than attempted a third time.",
"Stub functions defined at the top level of a suite SHADOW the subject's own functions for every later assertion. Doing this for the phase_nextcloud order test dropped coverage from 83.53% to 57.65% while the tests still reported passing, because they were exercising the stubs. The fix is a subshell, and the hazard is general to this style of harness.",
"A stub for a command the subject PIPES into must drain stdin, or the writer takes SIGPIPE and the suite aborts under set -e. A stub whose output is piped into `grep -v` must also emit a line, since grep exits 1 on no match and pipefail propagates it.",
"The bind list for this suite (/etc, /usr/local/bin, /var, /root) is wider than dot_resolver's. Binding all of /var rather than /var/lib and /var/www separately was necessary because a bind onto a non-existent host path cannot be created under a read-only real /var."
],
"rollback": [
"git revert this commit; nothing is wired into a hook, so no commit path can break.",
"After rollback, confirm dot_resolver_install.sh still measures 39/39 through the runner."
]
}

View File

@ -1,55 +0,0 @@
{
"intent": "Cover rpi_nc_install.sh, the next-hardest library on the allowlist, and fix two latent assertion bugs discovered in the already-committed nc_php suite.",
"scope": [
"linux_configuration/scripts/single_use/features/lib/tests/test_rpi_nc_install.sh (new)",
"linux_configuration/scripts/single_use/features/lib/tests/test_nc_php.sh (two assertion bugs fixed)",
"Non-goal: removing either file from the allowlist -- neither meets the 100% bar"
],
"changes": [
"Added test_rpi_nc_install.sh: 29 assertions over the 200-line install phase, including the destructive `rm -rf /var/www/nextcloud` step and the idempotence of the OPcache block.",
"Fixed a latent bug in test_nc_php.sh: the cron entry arrives on crontab's STDIN, not in argv, so the stub now records stdin instead of discarding it. The old assertion could not have failed for the right reason.",
"Fixed a second latent bug in test_nc_php.sh: configure_mariadb's stdout is consumed by `db_password=$(configure_mariadb)`, so the phase-order marker is now written to stderr and the capture reads both streams."
],
"verification": [
{
"command": "run_all.sh inside the jail, reading assertion results rather than only coverage",
"result": "pass - all three suites green",
"evidence": "test_dot_resolver_install.sh 28 passed 0 failed; test_nc_php.sh 30 passed 0 failed; test_rpi_nc_install.sh 29 passed 0 failed; RUNALL EXIT=0."
},
{
"command": "the same suites before the nc_php fixes",
"result": "pass - the two bugs were real and are now gone",
"evidence": "test_nc_php.sh previously reported 27 passed, 2 failed IN ISOLATION -- so this was a genuine defect in the committed suite, not cross-suite interference. It was missed because the earlier session checked coverage percentages without reading the assertion results."
},
{
"command": "shell_coverage_jail.sh --measure for each of the three libs",
"result": "pass for two, MIS-MEASURED for the third",
"evidence": "dot_resolver_install.sh 39/39 = 100.00%; nc_php.sh 84/85 = 98.82%; rpi_nc_install.sh 10/88 = 11.36%."
},
{
"command": "check whether rpi_nc_install.sh's 'uncovered' lines actually execute",
"result": "pass - they do; the low number is a measurement failure, not missing coverage",
"evidence": "After a run inside the jail, /root/.nextcloud_db_password (line 61) and /etc/apache2/sites-available/nextcloud.conf (line 82) both exist, and all 29 assertions pass. kcov records lines 13-54 and nothing after."
},
{
"command": "three minimal reproductions isolating the suspected kcov triggers",
"result": "pass - all three hypotheses DISPROVEN",
"evidence": "kcov traces correctly past a plain heredoc (lines after it hit), into a function called inside `$(...)` (all 4 body lines hit), and past a heredoc-fed stub that reads stdin via `$(cat)` (lines after it hit). The cause of the rpi_nc_install mis-measurement remains unknown."
},
{
"command": "shellcheck on the new and modified files",
"result": "pass - clean, no suppressions",
"evidence": "Both test files clean."
}
],
"risks": [
"rpi_nc_install.sh is measured at 11.36% by a tool that provably under-reports it, so the number in the ledger is not trustworthy for this file. It STAYS on the allowlist. The suite is kept for its 29 assertions rather than its percentage, and the anomaly is documented in the file header so a later session does not 'fix' the number by weakening a test.",
"The kcov mis-measurement is an unexplained hole in the campaign's primary instrument. If it affects other subjects, their percentages are also suspect. Nothing so far suggests it does -- the other two libs in the same directory measure sensibly -- but it has not been bounded.",
"The unzip stub must MATERIALISE /var/www/nextcloud, because the phase `rm -rf`s that directory and then unzips over it. A record-only stub leaves the later `cd` with nothing to enter, the function returns 1, and `set -e` aborts the suite from inside a command substitution with NO stderr at all.",
"This session's earlier commit of test_nc_php.sh shipped two failing assertions. Coverage percentage was checked; assertion results were not. Both are needed."
],
"rollback": [
"git revert this commit; nothing is wired into a hook, so no commit path breaks.",
"After rollback, confirm dot_resolver_install.sh still measures 39/39 and that test_nc_php.sh returns to its previous 27-passed/2-failed state."
]
}

View File

@ -1,76 +0,0 @@
{
"intent": "Convert the shell-coverage ratchet from a presence check to the user's chosen 100% line-coverage bar, promote the proven namespace jail into meta/scripts/, unblock the jscpd gate, and bring the repo's hardest shell library to 100% coverage as the first entry under the new bar.",
"scope": [
"meta/scripts/shell_coverage_jail.sh (new): the namespace-jail coverage runner",
"meta/scripts/check_shell_coverage.sh + meta/scripts/lib/shell_coverage_bar.sh: presence check -> measured 100% bar",
"linux_configuration/.githooks/pre-commit: jscpd exclusions",
"linux_configuration/scripts/single_use/features/lib/tests/: new suite for dot_resolver_install.sh",
"Non-goal: wiring the gate into the hook chain; that is a separate step once more libraries clear the bar"
],
"changes": [
"Promoted the session's scratchpad jail prototype into meta/scripts/shell_coverage_jail.sh, with two fixes the prototype needed: bind targets now mirror the real directory tree (an empty bind made writes fail with ENOENT, which reads as unreachable code), and sudo gets a pass-through stub because real sudo cannot setresuid inside a user namespace.",
"Added an escape assertion: the runner fingerprints `git status --porcelain` before and after, and fails the run if the subject modified the working tree.",
"Replaced is_covered's `[[ -f tests/run_all.sh ]]` with a measured 100% bar via the jail, extracted to meta/scripts/lib/shell_coverage_bar.sh to hold both files under the 250-line cap.",
"Excluded .venv/ and lib/tests/ from the jscpd scan, with the measured justification recorded inline.",
"Added features/lib/tests/{features_harness.sh,test_dot_resolver_install.sh,run_all.sh} and removed dot_resolver_install.sh from the allowlist (106 -> 105 entries)."
],
"verification": [
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject setup_night_lockdown.sh --bind /etc --bind /usr/local/bin --bind /var/lib -- help status bogus setup unlock",
"result": "pass - the promoted runner reproduces the scratchpad result",
"evidence": "38/38 lines = 100.00%, after the directory-mirroring fix; it read 86.84% before it, because /etc/modules-load.d did not exist inside the empty bind."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject <the new suite> --measure dot_resolver_install.sh --min 100 -- \"\"",
"result": "pass - the hardest library in the repo is at the bar",
"evidence": "dot_resolver_install.sh: 39/39 lines = 100.00%, 28 assertions passing. Chosen by scoring every allowlisted lib on root ops, system writes and destructive calls; it scored 88, the highest in the repo (15 root ops, 5 system writes, 5 destructive)."
},
{
"command": "run the suite inside the jail and read its assertions",
"result": "pass - all four open_firewall branches and all four run_check arms are exercised",
"evidence": "28 passed, 0 failed. Covers: existing wg0 rule not duplicated, missing rule added and scoped to the tunnel, add-failure warns instead of aborting, public bind rate limited at the documented 25/second burst 50, and the stunnel-down / cert-missing / port-silent / kdig-unanswered failure arms."
},
{
"command": "bash meta/scripts/check_shell_coverage.sh <a covered lib> ; and <an uncovered, de-allowlisted lib>",
"result": "pass - the gate fails closed",
"evidence": "exit 0 on dot_resolver_install.sh (on its own merit, now off the allowlist); exit 1 on nc_php.sh with the allowlist entry temporarily removed. Verified again after the 250-line split."
},
{
"command": "jscpd with the hook's exact arguments, before and after the exclusions",
"result": "pass - the duplication gate is unblocked",
"evidence": "2.45% (over the 2% threshold, 51 clones) -> 1.47%. Measured stepwise: excluding .venv/ alone gives 1.67%, already under the bar; adding lib/tests/ gives 1.47% of headroom for the campaign's test files."
},
{
"command": "shellcheck on every new and modified shell file; grep for suppressions",
"result": "pass - clean, with no suppressions",
"evidence": "shellcheck clean on shell_coverage_jail.sh, check_shell_coverage.sh, shell_coverage_bar.sh, the three new test files and the pre-commit hook. SC2155 was fixed by splitting declaration from assignment and SC2016 by writing the in-namespace runner to its own file, rather than by disabling either."
},
{
"command": "bash meta/scripts/check_file_length.sh --all",
"result": "pass - all files within 250 lines",
"evidence": "The conversion first pushed check_shell_coverage.sh to 268 lines; extracting the bar into lib/shell_coverage_bar.sh brought it to 236 + 44."
},
{
"command": "deliberate escapee: a subject that writes into the repo",
"result": "pass - the escape assertion fires",
"evidence": "'Error: the subject modified the working tree; a write escaped the jail' plus the offending path, exit non-zero. The real /etc/modules-load.d/night-lockdown-i2c.conf kept its 2026-07-23 mtime across every run in this session."
},
{
"command": "time bash meta/scripts/check_shell_coverage.sh <one lib>",
"result": "pass - fast enough for a pre-commit hook",
"evidence": "0.42s per file in hook mode, for both a covered and an exempt lib. A --all sweep is much slower, which is why the hook checks only the files a commit touches."
}
],
"risks": [
"The jail's bind list is per-subject. Mount only what a script WRITES and preserve what it READS: a blanket 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. An over-aggressive mount is indistinguishable from unreachable code at the report level.",
"is_covered falls back to presence when kcov or unshare is absent, so a machine without the tools cannot enforce the number. This is deliberate -- a hook that hard-failed on a missing developer tool would block all commits there -- and the CI job is what makes the number binding.",
"The gate is still NOT wired into the hook chain. Nothing enforces this yet; wiring is a separate step once more libraries clear the bar.",
"105 libraries remain on the allowlist. The list is shrink-only by construction, so it cannot quietly regrow, but the campaign is far from finished.",
"Excluding lib/tests/ from jscpd means duplicated test harnesses no longer trip the duplication gate. The 'one harness per directory' convention is now a convention rather than an enforced rule.",
"This session ran alongside another Claude session working in the same repo, which authored check_shell_coverage.sh, the allowlist and commits 7845ddfe..3338033c. Its work was converted rather than reverted, per the user's instruction not to touch it."
],
"rollback": [
"git revert this commit; the gate is not wired into any hook, so reverting cannot break a commit path.",
"After rollback, confirm `bash meta/scripts/check_file_length.sh --all` passes and that jscpd returns to its prior 2.45% -- which will block any commit that stages a .sh file until the .venv exclusion is restored."
]
}

View File

@ -79,20 +79,13 @@ fi
# --min-lines 14: minimum 14 lines to consider a clone (ignores small boilerplate)
# --min-tokens 25: minimum 25 tokens to consider a clone
# --threshold 2: fail if more than 2% duplication
# Excluded from the scan, and why:
# .venv/ vendored third-party shell (virtualenv, tqdm completions).
# Not ours, and it alone pushed the repo over the bar: the
# same scan reads 2.50% with it and 1.67% without.
# lib/tests/ a fixture IS repetitive by design; the 2% rule exists to
# stop duplicated production logic, not shared test setup.
# Needed headroom for the Phase 3 coverage campaign.
jscpd_output=$("$JSCPD_BIN" \
--pattern "**/*.sh" \
--min-lines 14 \
--min-tokens 25 \
--threshold 2 \
--reporters "console" \
--ignore "**/node_modules/**,**/.git/**,**/misc/testsAndMisc-bash/**,**/*.txt,**/.venv/**,**/lib/tests/**,**/tests/**" \
--ignore "**/node_modules/**,**/.git/**,**/misc/testsAndMisc-bash/**,**/*.txt" \
. 2>&1) || jscpd_exit=$?
if [[ ${jscpd_exit:-0} -ne 0 ]]; then

View File

@ -1,106 +0,0 @@
#!/usr/bin/env bash
# lib/tests/features_harness.sh — shared fixture for the features/lib suites.
#
# Sourced, not executed. One harness per DIRECTORY, not per file: jscpd fails
# the commit above 2% duplication, and near-identical per-file harnesses are
# exactly how that trips.
#
# Unlike the digital_wellbeing harness, this one does NOT avoid the effecting
# code. Its subjects sudo-write systemd units and add nftables rules, and
# those paths are the point. They are made safe by running under
# meta/scripts/shell_coverage_jail.sh, which puts the whole suite inside a
# user+mount namespace where the write targets are bind-mounted to a
# throwaway dir. Nothing here may assume it can reach the real /etc.
set -euo pipefail
PASS=0
FAIL=0
_t_pass() {
PASS=$((PASS + 1))
printf ' OK: %s\n' "$1"
}
_t_fail() {
FAIL=$((FAIL + 1))
printf ' FAIL: %s\n' "$1"
}
_t_eq() {
if [[ $2 == "$1" ]]; then
_t_pass "$3"
else
_t_fail "$3 (want '${1}', got '${2}')"
fi
}
_t_has() {
if [[ $1 == *"$2"* ]]; then
_t_pass "$3"
else
_t_fail "$3 (want a substring '${2}')"
fi
}
_t_file_has() {
if [[ -f $1 ]] && grep -q "$2" "$1"; then
_t_pass "$3"
else
_t_fail "$3 (file '${1}' missing or lacks '${2}')"
fi
}
# A function that calls `exit` would kill the test script if invoked directly
# in an `if` condition, so failures are asserted inside a subshell.
_t_exits_nonzero() {
if ("$1" >/dev/null 2>&1); then
_t_fail "$2 (expected a non-zero exit, got 0)"
else
_t_pass "$2"
fi
}
FEATURES_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
export FEATURES_LIB_DIR
# The libs are sourced by their entry scripts and inherit these from above the
# source line. A missing one aborts the subject under `set -u` with no useful
# stderr, so the fixture asserts its own globals are populated rather than
# letting a typo become a silently skipped assertion.
log() { printf '[test] %s\n' "$1"; }
_t_setup_env() {
TEST_TMPDIR="$(mktemp -d)"
export TEST_TMPDIR
PATH="$TEST_TMPDIR/bin:$PATH"
export PATH
mkdir -p "$TEST_TMPDIR/bin"
}
# Record-and-succeed stubs for commands with no useful behaviour under test.
# `sudo` is deliberately NOT stubbed: inside the jail we are already uid 0, so
# stubbing it would hide the very writes these tests exist to exercise.
_t_stub() {
printf '#!/usr/bin/env bash\nprintf "%%s %%s\\n" "%s" "$*" >>"%s/calls.log"\nexit 0\n' \
"$1" "$TEST_TMPDIR" >"$TEST_TMPDIR/bin/$1"
chmod +x "$TEST_TMPDIR/bin/$1"
}
_t_called() {
if [[ -f "$TEST_TMPDIR/calls.log" ]] && grep -q "$1" "$TEST_TMPDIR/calls.log"; then
_t_pass "$2"
else
_t_fail "$2 (no '${1}' in the call log)"
fi
}
_t_teardown() {
if [[ -n ${TEST_TMPDIR:-} && -d ${TEST_TMPDIR} ]]; then
rm -rf "$TEST_TMPDIR"
fi
}
_t_report() {
printf '\n%s: %d passed, %d failed\n' "${1:-tests}" "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]]
}

View File

@ -1,35 +0,0 @@
# Presence of this file next to run_all.sh declares: this suite executes its
# subjects FOR REAL (root writes to /etc, /var, /usr/local/bin) and MUST run
# inside shell_coverage_jail.sh. Running it bare is refused by the suite
# itself; both ci_mirror.sh and shell-tests.yml read this file and wrap the
# runner instead of invoking it directly.
#
# One shell-word per line, blank lines and #-comments ignored. These are the
# jail flags only -- --subject and the trailing cases are supplied by the
# caller.
#
# --bind what the subject WRITES; never what it READS (binding /usr/local/bin
# for a subject that sources siblings from there cut a measurement 75% -> 29%).
# Never --bind /tmp: the jail's own working dir lives there.
--bind
/etc
--bind
/usr/local/bin
--bind
/var
--bind
/root
--seed-dir
/var/www/nextcloud
--seed-dir
/var/lib
--seed-dir
/etc/php/8.2/apache2
--seed-dir
/etc/php/8.2/mods-available
--seed-dir
/etc/apache2/sites-available
--seed-file
/etc/php/8.2/apache2/php.ini
--timeout
90s

View File

@ -1,38 +0,0 @@
#!/usr/bin/env bash
# lib/tests/run_all.sh — run every features/lib test in one process tree.
#
# Also the subject handed to shell_coverage_jail.sh: coverage of a lib is only
# complete across the whole suite.
#
# These suites execute their subjects FOR REAL, including sudo-writes to
# /etc/systemd/system and nftables rules. They must therefore run inside the
# namespace jail; see the header of test_dot_resolver_install.sh.
#
# The full invocation, including the seeds the Debian/Raspberry-Pi subjects
# need on an Arch host:
#
# meta/scripts/shell_coverage_jail.sh \
# --subject linux_configuration/scripts/single_use/features/lib/tests/run_all.sh \
# --bind /etc --bind /usr/local/bin --bind /var/lib \
# --seed-dir /etc/php/8.2/apache2 \
# --seed-dir /etc/php/8.2/mods-available \
# --seed-file /etc/php/8.2/apache2/php.ini \
# --measure <lib>.sh --min 100 -- ""
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 features/lib test files passed.\n'

View File

@ -1,186 +0,0 @@
#!/usr/bin/env bash
# Tests for dot_resolver_install.sh — the DoT resolver's install half.
#
# Every function here sudo-writes a systemd unit, an stunnel config or an
# nftables rule against LIVE infrastructure (dns.kuhy.duckdns.org:853). They
# are executed for real, not mocked, because the generated CONTENT is the
# thing worth asserting -- a unit file with the wrong ExecStart is exactly the
# bug a presence check would miss.
#
# This is only safe under meta/scripts/shell_coverage_jail.sh, which runs the
# suite inside a user+mount namespace with /etc, /usr/local/bin and /var/lib
# bind-mounted to a throwaway dir. Run directly on a real host it would
# rewrite the resolver, so it refuses to start unless the jail is in place.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./features_harness.sh
. "$SCRIPT_DIR/features_harness.sh"
# --- Refuse to run outside the jail -----------------------------------------
# The jail bind-mounts /etc, so the real resolver's config is absent inside it.
# Seeing the host's own stunnel config means we are NOT contained.
if [[ -f /etc/stunnel/dot-resolver.conf ]] && [[ ! -w /etc ]]; then
printf 'REFUSING: this suite must run under shell_coverage_jail.sh\n' >&2
exit 1
fi
_t_setup_env
trap _t_teardown EXIT
# The values the entry script defines above its source line.
SCRIPT_NAME="setup_dot_resolver.sh"
CERT_DIR="/etc/stunnel/dot"
STUNNEL_CONF="/etc/stunnel/dot-resolver.conf"
SYNC_SCRIPT="/usr/local/bin/sync-dot-cert.sh"
DOT_PORT=853
DOMAIN="dns.kuhy.duckdns.org"
BIND_ADDR="10.8.0.1"
CADDY_CONTAINER="caddy"
# install_cert_sync interpolates this at GENERATION time (the heredoc is
# unquoted), baking the resolved path into the script it writes. That is
# deliberate, not a bug -- the live /usr/local/bin/sync-dot-cert.sh carries a
# fully populated src=. The fixture must therefore define it exactly as the
# entry script does, or the generated script gets src="" and the assertion
# below silently passes over an empty path.
cert_source_dir() {
printf '/data/caddy/certificates/acme-v02.api.letsencrypt.org-directory/%s' \
"$DOMAIN"
}
# shellcheck source=../dot_resolver_install.sh
. "$FEATURES_LIB_DIR/dot_resolver_install.sh"
# Fixture self-check: a typo in one of these names would turn every assertion
# below into a silent no-op rather than a failure.
[[ -n $CERT_DIR && -n $STUNNEL_CONF && -n $SYNC_SCRIPT ]] ||
{
printf 'fixture globals are not populated\n' >&2
exit 1
}
mkdir -p /etc/stunnel /etc/systemd/system /usr/local/bin
# --- install_cert_sync ------------------------------------------------------
install_cert_sync
_t_file_has "$SYNC_SCRIPT" 'combined.pem' "cert sync script assembles combined.pem"
_t_file_has "$SYNC_SCRIPT" "src=\"/data/caddy/certificates" "cert source path is baked in, not left empty"
_t_file_has "$SYNC_SCRIPT" 'reload-or-restart' "cert sync restarts stunnel after renewal"
if [[ -d $CERT_DIR ]]; then
_t_pass "cert dir created"
else
_t_fail "cert dir created"
fi
_t_eq "700" "$(stat -c '%a' "$CERT_DIR")" "cert dir is mode 700 (it holds a private key)"
_t_eq "755" "$(stat -c '%a' "$SYNC_SCRIPT")" "sync script is executable"
# --- install_stunnel_conf ---------------------------------------------------
install_stunnel_conf
_t_file_has "$STUNNEL_CONF" "accept = $BIND_ADDR:$DOT_PORT" "stunnel accepts on the bind address"
_t_file_has "$STUNNEL_CONF" 'connect = 127.0.0.1:53' "stunnel forwards to local dnsmasq"
_t_file_has "$STUNNEL_CONF" 'sslVersionMin = TLSv1.2' "stunnel refuses pre-TLS1.2 (Android requires it)"
_t_file_has "$STUNNEL_CONF" "cert = $CERT_DIR/combined.pem" "stunnel reads the synced cert"
# --- install_units ----------------------------------------------------------
_t_stub systemctl
install_units
_t_file_has /etc/systemd/system/stunnel-dot.service 'stunnel' "stunnel unit installed"
_t_file_has /etc/systemd/system/dot-cert-sync.service "$SYNC_SCRIPT" "cert-sync service runs the sync script"
_t_file_has /etc/systemd/system/dot-cert-sync.timer 'OnCalendar' "cert-sync timer is scheduled"
_t_called 'daemon-reload' "units are followed by a daemon-reload"
# --- open_firewall: the WireGuard-only branch -------------------------------
# nft absent entirely: the function must still return cleanly rather than
# aborting the install on a host without nftables.
out="$(open_firewall 2>&1)"
_t_has "$out" 'WireGuard-only' "wg-bound install needs no router forward"
# nft present and the rule already there: must not add a duplicate.
_t_stub nft
printf '#!/usr/bin/env bash\nprintf "nft %%s\\n" "$*" >>"%s/calls.log"\nif [[ $* == *list* ]]; then printf "iifname \\"wg0\\" tcp dport %s accept\\n" ; fi\nexit 0\n' \
"$TEST_TMPDIR" "$DOT_PORT" >"$TEST_TMPDIR/bin/nft"
chmod +x "$TEST_TMPDIR/bin/nft"
out="$(open_firewall 2>&1)"
_t_has "$out" 'already permits' "an existing wg0 rule is not duplicated"
# nft present and the rule missing: must add it, scoped to wg0.
printf '#!/usr/bin/env bash\nprintf "nft %%s\\n" "$*" >>"%s/calls.log"\nexit 0\n' \
"$TEST_TMPDIR" >"$TEST_TMPDIR/bin/nft"
chmod +x "$TEST_TMPDIR/bin/nft"
out="$(open_firewall 2>&1)"
_t_has "$out" 'wg0 only' "a missing wg0 rule is added"
_t_called 'add rule inet filter input iifname wg0' "the added rule is scoped to the tunnel"
# nft present but the ADD fails (a locked-down or read-only ruleset): the
# install must warn and carry on, never abort. `nft list` still has to succeed
# or the outer guard short-circuits before the add is attempted.
cat >"$TEST_TMPDIR/bin/nft" <<'NFT'
#!/usr/bin/env bash
printf 'nft %s\n' "$*" >>"$TEST_TMPDIR/calls.log"
[[ $* == *add* ]] && exit 1
exit 0
NFT
chmod +x "$TEST_TMPDIR/bin/nft"
out="$(open_firewall 2>&1)"
_t_has "$out" 'WARNING: could not add nftables rule' "a failed wg0 rule add warns instead of aborting"
# --- open_firewall: the publicly-bound branch -------------------------------
# A public bind is an open resolver, so the rule MUST carry a rate limit.
BIND_ADDR="0.0.0.0"
out="$(open_firewall 2>&1)"
_t_has "$out" 'rate limited' "a public bind is rate limited"
_t_called 'limit rate 25/second burst 50' "the public rule carries the documented limit"
_t_has "$out" 'router forwards' "a public bind asks for a router forward"
# The same add-failure path on the public branch.
out="$(open_firewall 2>&1)"
_t_has "$out" 'WARNING: could not add rate-limited nftables rule' \
"a failed public rule add warns instead of aborting"
BIND_ADDR="10.8.0.1"
# --- run_check --------------------------------------------------------------
# Everything healthy: stunnel active, port listening, cert present.
printf '#!/usr/bin/env bash\nexit 0\n' >"$TEST_TMPDIR/bin/systemctl"
chmod +x "$TEST_TMPDIR/bin/systemctl"
printf '#!/usr/bin/env bash\nprintf "LISTEN 0 0 10.8.0.1:%s\\n"\n' "$DOT_PORT" >"$TEST_TMPDIR/bin/ss"
chmod +x "$TEST_TMPDIR/bin/ss"
install -m 600 /dev/null "$CERT_DIR/combined.pem"
printf 'cert\n' >"$CERT_DIR/combined.pem"
if run_check >/dev/null 2>&1; then
_t_pass "run_check passes on a healthy install"
else
_t_fail "run_check passes on a healthy install"
fi
# stunnel down: must fail and say which check failed.
printf '#!/usr/bin/env bash\n[[ $* == *is-active* ]] && exit 1\nexit 0\n' >"$TEST_TMPDIR/bin/systemctl"
chmod +x "$TEST_TMPDIR/bin/systemctl"
out="$(run_check 2>&1 || true)"
_t_has "$out" 'FAIL stunnel-dot.service not active' "a stopped stunnel is reported"
# Certificate missing: the check that must be run as root to be correct.
rm -f "$CERT_DIR/combined.pem"
printf '#!/usr/bin/env bash\nexit 0\n' >"$TEST_TMPDIR/bin/systemctl"
chmod +x "$TEST_TMPDIR/bin/systemctl"
out="$(run_check 2>&1 || true)"
_t_has "$out" 'FAIL certificate missing' "a missing certificate is reported"
# Nothing listening on the port.
printf '#!/usr/bin/env bash\nexit 0\n' >"$TEST_TMPDIR/bin/ss"
chmod +x "$TEST_TMPDIR/bin/ss"
out="$(run_check 2>&1 || true)"
_t_has "$out" 'FAIL nothing listening' "a silent port is reported"
# kdig present and the DoT query failing. The check is skipped entirely when
# kdig is absent, so this arm only exists on a host that has knot-utils --
# which makes it exactly the arm most likely to rot unnoticed.
printf '#!/usr/bin/env bash\nexit 1\n' >"$TEST_TMPDIR/bin/kdig"
chmod +x "$TEST_TMPDIR/bin/kdig"
printf 'cert\n' >"$CERT_DIR/combined.pem"
printf '#!/usr/bin/env bash\nprintf "LISTEN 0 0 10.8.0.1:%s\\n"\n' "$DOT_PORT" >"$TEST_TMPDIR/bin/ss"
chmod +x "$TEST_TMPDIR/bin/ss"
out="$(run_check 2>&1 || true)"
_t_has "$out" 'FAIL DoT query did not answer' "an unanswered DoT query is reported"
_t_report "test_dot_resolver_install.sh"

View File

@ -1,199 +0,0 @@
#!/usr/bin/env bash
# Tests for nc_php.sh — PHP, Redis and the Nextcloud install itself.
#
# The subject targets a Raspberry Pi running Debian: it edits
# /etc/php/<ver>/apache2/php.ini, drives `occ` as www-data, and installs a
# crontab. None of those paths exist on this Arch host, so the jail is given
# them with --seed-dir/--seed-file; see run_all.sh's header for the exact
# invocation. Run outside the jail this would edit a php.ini that is not
# there, which is why the guard below refuses.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./features_harness.sh
. "$SCRIPT_DIR/features_harness.sh"
# The seeded php.ini only exists inside the jail. Its absence means we are not
# contained, and configure_php would `cp` a file that is not there.
PHP_VERSION_UNDER_TEST="8.2"
PHP_INI="/etc/php/${PHP_VERSION_UNDER_TEST}/apache2/php.ini"
if [[ ! -f $PHP_INI ]]; then
printf 'REFUSING: %s is absent; this suite must run under the jail\n' "$PHP_INI" >&2
exit 1
fi
_t_setup_env
trap _t_teardown EXIT
# Globals the entry script defines above its source line.
NEXTCLOUD_ADMIN_USER="admin"
NEXTCLOUD_ADMIN_PASSWORD="hunter2"
NEXTCLOUD_DATA_DIR="/var/nextcloud-data"
PI_HOSTNAME="raspberrypi"
# The logging helpers the libs inherit from the caller.
log_info() { printf '[INFO] %s\n' "$*"; }
log_success() { printf '[OK] %s\n' "$*"; }
log_warning() { printf '[WARN] %s\n' "$*"; }
log_error() { printf '[ERR] %s\n' "$*"; }
# shellcheck source=../nc_php.sh
. "$FEATURES_LIB_DIR/nc_php.sh"
[[ -n $NEXTCLOUD_DATA_DIR && -n $PI_HOSTNAME ]] ||
{
printf 'fixture globals are not populated\n' >&2
exit 1
}
# --- configure_php ----------------------------------------------------------
# php reports the seeded version; apache2 restart is recorded, not performed.
printf '#!/usr/bin/env bash\nprintf "%%s" "%s"\n' "$PHP_VERSION_UNDER_TEST" \
>"$TEST_TMPDIR/bin/php"
chmod +x "$TEST_TMPDIR/bin/php"
_t_stub systemctl
cat >"$PHP_INI" <<'INI'
memory_limit = 128M
upload_max_filesize = 2M
post_max_size = 8M
max_execution_time = 30
max_input_time = 60
;date.timezone =
INI
mkdir -p "/etc/php/${PHP_VERSION_UNDER_TEST}/mods-available"
: >"/etc/php/${PHP_VERSION_UNDER_TEST}/mods-available/apcu.ini"
configure_php
_t_file_has "$PHP_INI" 'memory_limit = 512M' "memory_limit raised for Nextcloud"
_t_file_has "$PHP_INI" 'upload_max_filesize = 16G' "upload limit raised to 16G"
_t_file_has "$PHP_INI" 'post_max_size = 16G' "post_max_size raised to 16G"
_t_file_has "$PHP_INI" 'max_execution_time = 360' "execution time raised"
_t_file_has "$PHP_INI" 'date.timezone = Europe/Warsaw' "timezone set (the ;-prefixed default is replaced)"
_t_file_has "$PHP_INI" 'opcache.enable=1' "OPcache enabled"
_t_file_has "$PHP_INI" 'opcache.save_comments=1' "OPcache keeps comments (Nextcloud needs them)"
_t_file_has "${PHP_INI}.backup" 'memory_limit = 128M' "the original php.ini is backed up before editing"
_t_file_has "/etc/php/${PHP_VERSION_UNDER_TEST}/mods-available/apcu.ini" 'apc.enable_cli=1' "APCu enabled for the CLI"
_t_called 'restart apache2' "apache is restarted to pick up the new ini"
# --- configure_redis --------------------------------------------------------
configure_redis
_t_called 'enable redis-server' "redis is enabled at boot"
_t_called 'start redis-server' "redis is started now"
# --- install_nextcloud ------------------------------------------------------
mkdir -p /root /var/www/nextcloud
printf 'dbsecret\n' >/root/.nextcloud_db_password
printf '#!/usr/bin/env bash\nprintf "10.0.0.5 \\n"\n' >"$TEST_TMPDIR/bin/hostname"
chmod +x "$TEST_TMPDIR/bin/hostname"
_t_stub chown
# `occ` is invoked as `php occ ...`; the php stub above must now record instead
# of printing a version, or every occ call would be silently swallowed.
_t_stub php
install_nextcloud
_t_called 'occ maintenance:install' "the installer is run"
_t_called 'admin-user admin' "the configured admin user is passed through"
_t_called 'trusted_domains 1 --value=10.0.0.5' "the server IP is trusted"
_t_called "trusted_domains 2 --value=$PI_HOSTNAME" "the hostname is trusted"
_t_called "trusted_domains 3 --value=${PI_HOSTNAME}.local" "the .local name is trusted"
_t_called 'memcache.locking' "Redis is wired in for locking"
_t_called 'default_phone_region' "the phone region is set"
if [[ -d $NEXTCLOUD_DATA_DIR ]]; then
_t_pass "the data directory is created"
else
_t_fail "the data directory is created"
fi
# An empty admin password must be prompted for rather than silently accepted.
prompt_password() {
printf '[prompt] %s\n' "$1"
printf -v "$2" '%s' "prompted-secret"
}
NEXTCLOUD_ADMIN_PASSWORD=""
out="$(install_nextcloud 2>&1)"
_t_has "$out" '[prompt] Enter Nextcloud admin password' "an empty admin password is prompted for"
_t_called 'admin-pass prompted-secret' "the prompted password reaches the installer"
NEXTCLOUD_ADMIN_PASSWORD="hunter2"
# --- setup_nextcloud_cron ---------------------------------------------------
# setup_nextcloud_cron PIPES into crontab. A stub that exits without reading
# stdin makes the writer take SIGPIPE, which aborts the suite under `set -e`
# -- so this one drains stdin before recording.
cat >"$TEST_TMPDIR/bin/crontab" <<'CRONTAB'
#!/usr/bin/env bash
# The cron entry arrives on STDIN, not in argv, so it must be RECORDED
# rather than discarded -- asserting on the call log alone would pass
# no matter what line the code piped in.
cat >>"$TEST_TMPDIR/crontab.stdin"
printf 'crontab %s\n' "$*" >>"$TEST_TMPDIR/calls.log"
# `-l` must emit at least one line: the real code pipes it through
# `grep -v nextcloud/cron.php`, and grep exits 1 on no match, which
# aborts the caller under pipefail. An existing unrelated entry is also
# the realistic case -- it proves the rewrite PRESERVES other cron jobs.
if [[ $* == *-l* ]]; then
printf '0 4 * * * /usr/local/bin/some-unrelated-job\n'
fi
exit 0
CRONTAB
chmod +x "$TEST_TMPDIR/bin/crontab"
setup_nextcloud_cron
_t_called 'crontab -u www-data' "the www-data crontab is written"
_t_called 'occ background:cron' "Nextcloud is switched to cron mode"
_t_file_has "$TEST_TMPDIR/crontab.stdin" 'php -f /var/www/nextcloud/cron.php' \
"the Nextcloud cron entry is piped into crontab"
_t_file_has "$TEST_TMPDIR/crontab.stdin" 'some-unrelated-job' \
"an unrelated existing cron entry is preserved"
# --- phase_nextcloud --------------------------------------------------------
# The orchestrator. Its siblings live in other libs, so the fixture supplies
# them; what is asserted here is the ORDER, which is load-bearing: php and
# redis must both be configured before the installer runs, and the cron job
# must be added before the final verification.
#
# Run in a SUBSHELL. These definitions shadow the real functions, and letting
# them leak into the enclosing shell silently replaced the subject's own
# functions for every later assertion -- coverage fell from 83.53% to 57.65%
# and the tests still "passed", because they were exercising the stubs.
phase_order_result="$(
{
check_root() { printf 'root '; }
install_nextcloud_dependencies() { printf 'deps '; }
# Its stdout is captured by `db_password=$(configure_mariadb)`, so a
# marker printed here would be swallowed. Record to stderr, which the
# command substitution does not consume, and emit the password on
# stdout as the real function does.
configure_mariadb() {
printf 'mariadb ' >&2
printf 'dbpass'
}
download_nextcloud() { printf 'download '; }
configure_apache() { printf 'apache '; }
configure_php() { printf 'php '; }
configure_redis() { printf 'redis '; }
install_nextcloud() { printf 'install '; }
setup_nextcloud_cron() { printf 'cron '; }
verify_nextcloud() { printf 'verify '; }
log_info() { :; }
log_success() { :; }
phase_nextcloud
} 2>&1
)"
_t_eq "root deps mariadb download apache php redis install cron verify " \
"$phase_order_result" "the install phases run in dependency order"
# --- verify_nextcloud -------------------------------------------------------
printf '#!/usr/bin/env bash\nprintf "200"\n' >"$TEST_TMPDIR/bin/curl"
chmod +x "$TEST_TMPDIR/bin/curl"
out="$(verify_nextcloud 2>&1)"
_t_has "$out" 'Nextcloud is responding!' "a 200 from status.php reads as healthy"
_t_has "$out" 'Access Nextcloud at: http://10.0.0.5' "the access URL is reported"
# A non-200 must warn, not claim success.
printf '#!/usr/bin/env bash\nprintf "503"\n' >"$TEST_TMPDIR/bin/curl"
chmod +x "$TEST_TMPDIR/bin/curl"
out="$(verify_nextcloud 2>&1)"
_t_has "$out" 'may not be fully ready' "a non-200 warns instead of claiming success"
_t_report "test_nc_php.sh"

View File

@ -1,197 +0,0 @@
#!/usr/bin/env bash
# Tests for rpi_nc_install.sh — the Raspberry Pi Nextcloud install phase.
#
# One 200-line function that apt-installs 24 packages, seeds a MariaDB
# database, `rm -rf`s /var/www/nextcloud, rewrites Apache and PHP config and
# installs a www-data crontab. It is executed for real inside the namespace
# jail, where every one of those targets is a throwaway bind mount.
#
# The destructive step is the reason this suite is worth having: a bug in the
# `rm -rf /var/www/nextcloud` line is invisible to any check that does not
# actually run it.
#
# KNOWN: kcov MIS-MEASURES this subject. It reports 10/88 = 11.36%, recording
# lines 13-54 and nothing after, even though the code past line 54 provably
# runs -- /root/.nextcloud_db_password and
# /etc/apache2/sites-available/nextcloud.conf both exist after a run, and the
# 29 assertions below pass. The three obvious explanations were each tested
# against a minimal reproduction and DISPROVEN: kcov traces correctly past a
# heredoc, into a `$(...)` command substitution, and past a heredoc-fed stub
# that reads stdin via `$(cat)`. The cause is still unknown, so this file
# stays on the coverage allowlist and the suite is kept for the assertions
# rather than the percentage. Do not "fix" the number by weakening a test.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./features_harness.sh
. "$SCRIPT_DIR/features_harness.sh"
PHP_VERSION_UNDER_TEST="8.2"
PHP_INI="/etc/php/${PHP_VERSION_UNDER_TEST}/apache2/php.ini"
if [[ ! -f $PHP_INI ]]; then
printf 'REFUSING: %s is absent; this suite must run under the jail\n' "$PHP_INI" >&2
exit 1
fi
_t_setup_env
trap _t_teardown EXIT
# Globals the entry script defines above its source line.
NEXTCLOUD_ADMIN_USER="admin"
NEXTCLOUD_ADMIN_PASSWORD="hunter2"
NEXTCLOUD_DATA_DIR="/var/nextcloud-data"
PI_HOSTNAME="raspberrypi"
log_info() { printf '[INFO] %s\n' "$*"; }
log_success() { printf '[OK] %s\n' "$*"; }
log_warning() { printf '[WARN] %s\n' "$*"; }
log_error() { printf '[ERR] %s\n' "$*"; }
# Helpers this lib inherits from its siblings in the entry script.
check_root() { :; }
wait_for_apt_lock() { :; }
generate_password() { printf 'generated-%s-chars' "$1"; }
auto_generate_nextcloud_password() { :; }
save_config() { printf 'save_config called\n'; }
# shellcheck source=../rpi_nc_install.sh
. "$FEATURES_LIB_DIR/rpi_nc_install.sh"
[[ -n $NEXTCLOUD_DATA_DIR && -n $PI_HOSTNAME ]] ||
{
printf 'fixture globals are not populated\n' >&2
exit 1
}
# --- Stubs ------------------------------------------------------------------
for tool in apt-get a2enmod a2dissite a2ensite systemctl wget unzip chown \
php mysql crontab hostname; do
_t_stub "$tool"
done
# php is called two ways: `php -v` must yield a parseable version banner, and
# `php occ ...` must record. One stub serves both.
cat >"$TEST_TMPDIR/bin/php" <<PHPSTUB
#!/usr/bin/env bash
printf 'php %s\n' "\$*" >>"$TEST_TMPDIR/calls.log"
if [[ \$* == "-v" ]]; then
printf 'PHP %s.10 (cli) (built: Jan 1 2026)\n' "$PHP_VERSION_UNDER_TEST"
exit 0
fi
if [[ \$* == *status* ]]; then
printf ' - installed: true\n'
exit 0
fi
exit 0
PHPSTUB
chmod +x "$TEST_TMPDIR/bin/php"
# mysql reads the CREATE DATABASE heredoc from stdin; drain it or the writer
# takes SIGPIPE and the suite dies under set -e.
cat >"$TEST_TMPDIR/bin/mysql" <<MYSQLSTUB
#!/usr/bin/env bash
sql="\$(cat)"
printf 'mysql %s\n' "\$*" >>"$TEST_TMPDIR/calls.log"
printf '%s\n' "\$sql" >>"$TEST_TMPDIR/mysql.sql"
exit 0
MYSQLSTUB
chmod +x "$TEST_TMPDIR/bin/mysql"
cat >"$TEST_TMPDIR/bin/crontab" <<CRONSTUB
#!/usr/bin/env bash
cat >/dev/null
printf 'crontab %s\n' "\$*" >>"$TEST_TMPDIR/calls.log"
exit 0
CRONSTUB
chmod +x "$TEST_TMPDIR/bin/crontab"
printf '#!/usr/bin/env bash\nprintf "10.0.0.7 \\n"\n' >"$TEST_TMPDIR/bin/hostname"
chmod +x "$TEST_TMPDIR/bin/hostname"
# unzip must actually MATERIALISE the tree. The phase does `rm -rf
# /var/www/nextcloud` and then unzips over it, so a stub that only records
# leaves the later `cd /var/www/nextcloud` with nothing to enter -- the
# function returns 1 and `set -e` aborts the suite from inside a command
# substitution with no stderr at all, which is indistinguishable from a
# coverage-tool failure.
cat >"$TEST_TMPDIR/bin/unzip" <<UNZIPSTUB
#!/usr/bin/env bash
printf 'unzip %s\n' "\$*" >>"$TEST_TMPDIR/calls.log"
mkdir -p /var/www/nextcloud
printf 'extracted\n' >/var/www/nextcloud/occ
exit 0
UNZIPSTUB
chmod +x "$TEST_TMPDIR/bin/unzip"
# The environment the phase expects to find.
mkdir -p /etc/apache2/sites-available /var/www /root /tmp
cat >"$PHP_INI" <<'INI'
memory_limit = 128M
upload_max_filesize = 2M
post_max_size = 8M
max_execution_time = 30
max_input_time = 60
;date.timezone =
INI
# A stale install that the phase must clear. If `rm -rf /var/www/nextcloud`
# ever stops working, this file survives and the assertion below catches it.
mkdir -p /var/www/nextcloud
printf 'stale\n' >/var/www/nextcloud/STALE_MARKER
# unzip is stubbed, so the extracted tree is staged by hand.
: >/tmp/nextcloud.zip
phase_output="$(phase_install_nextcloud 2>&1)"
# --- Packages and database --------------------------------------------------
_t_called 'apt-get install' "the dependency set is installed"
_t_called 'php-imagick' "the imagick module is among the packages"
_t_file_has "$TEST_TMPDIR/mysql.sql" 'CREATE DATABASE IF NOT EXISTS nextcloud' "the database is created idempotently"
_t_file_has "$TEST_TMPDIR/mysql.sql" "GRANT ALL PRIVILEGES ON nextcloud" "the nextcloud user is granted its own schema"
_t_file_has /root/.nextcloud_db_password 'generated-32-chars' "the generated db password is persisted"
_t_eq "600" "$(stat -c '%a' /root/.nextcloud_db_password)" "the db password file is mode 600"
# --- The destructive step ---------------------------------------------------
if [[ -e /var/www/nextcloud/STALE_MARKER ]]; then
_t_fail "a stale /var/www/nextcloud is cleared before extracting"
else
_t_pass "a stale /var/www/nextcloud is cleared before extracting"
fi
_t_called 'unzip' "the release archive is extracted"
_t_called 'chown' "the tree is handed to www-data"
# --- Apache -----------------------------------------------------------------
_t_file_has /etc/apache2/sites-available/nextcloud.conf 'DocumentRoot /var/www/nextcloud' "the vhost points at the install"
_t_file_has /etc/apache2/sites-available/nextcloud.conf 'AllowOverride All' "the vhost allows Nextcloud's .htaccess"
_t_file_has /etc/apache2/sites-available/nextcloud.conf 'Dav off' "WebDAV is disabled for Apache (Nextcloud serves its own)"
_t_called 'a2enmod rewrite' "mod_rewrite is enabled"
_t_called 'a2dissite 000-default' "the default site is disabled"
_t_called 'a2ensite nextcloud' "the Nextcloud site is enabled"
# --- PHP --------------------------------------------------------------------
_t_file_has "$PHP_INI" 'memory_limit = 512M' "memory_limit is raised"
_t_file_has "$PHP_INI" 'upload_max_filesize = 16G' "the upload limit is raised"
_t_file_has "$PHP_INI" 'max_execution_time = 3600' "the execution ceiling is raised"
_t_file_has "$PHP_INI" 'opcache.interned_strings_buffer=16' "the OPcache block is appended"
# --- occ --------------------------------------------------------------------
_t_called 'occ maintenance:install' "the installer runs"
_t_called 'trusted_domains 1 --value=10.0.0.7' "the Pi's IP is trusted"
_t_called "trusted_domains 3 --value=${PI_HOSTNAME}.local" "the .local name is trusted"
_t_called 'memcache.locking' "Redis is wired in for locking"
_t_called 'occ background:cron' "background jobs move to cron"
_t_called 'crontab -u www-data' "the www-data crontab is installed"
_t_has "$phase_output" 'Nextcloud is responding!' "an installed: true status reads as healthy"
_t_has "$phase_output" 'save_config called' "the run is persisted to the config"
_t_has "$phase_output" 'Access Nextcloud at: http://10.0.0.7' "the access URL is reported"
# --- The OPcache block must not be appended twice ---------------------------
# The guard is `grep -q opcache.interned_strings_buffer`; a second run over an
# already-configured ini must leave exactly one copy.
before="$(grep -c 'opcache.interned_strings_buffer' "$PHP_INI")"
mkdir -p /var/www/nextcloud
phase_install_nextcloud >/dev/null 2>&1
after="$(grep -c 'opcache.interned_strings_buffer' "$PHP_INI")"
_t_eq "$before" "$after" "re-running does not duplicate the OPcache block"
_t_report "test_rpi_nc_install.sh"

View File

@ -72,9 +72,10 @@ is_shell_lib() {
}
# A lib is covered when a run_all.sh sits in its directory's tests/ subdir.
# The bar itself lives in lib/shell_coverage_bar.sh (250-line cap).
# shellcheck source=./lib/shell_coverage_bar.sh
. "$(dirname "${BASH_SOURCE[0]}")/lib/shell_coverage_bar.sh"
is_covered() {
local path="$1"
[[ -f "$(dirname "$path")/tests/run_all.sh" ]]
}
collect_libs() {
git -C "$REPO_ROOT" ls-files '*.sh'
@ -164,18 +165,17 @@ check_files() {
done < <(report_uncovered "$@")
if ((${#offenders[@]} == 0)); then
echo "$SCRIPT_NAME: every checked shell library meets the coverage bar"
echo "$SCRIPT_NAME: every checked shell library has a test suite"
return 0
fi
echo "$SCRIPT_NAME: ${#offenders[@]} shell librar(ies) below the coverage bar:" >&2
echo "$SCRIPT_NAME: ${#offenders[@]} shell librar(ies) without a test suite:" >&2
for path in "${offenders[@]}"; do
printf ' %s\n' "$path" >&2
printf ' needs: %s/tests/run_all.sh\n' "$(dirname "$path")" >&2
done
echo >&2
echo " A shell library must ship with a suite that drives it to
${COVERAGE_BAR}% line coverage. Extend" >&2
echo " A shell library must ship with a suite that sources it. Extend" >&2
echo " the nearest existing tests/ directory rather than cloning a" >&2
echo " harness -- jscpd fails above 2% duplication." >&2
return 1

View File

@ -127,41 +127,6 @@ run_gates_in_clean_worktree() {
# The Arch-container half of that workflow is deliberately NOT mirrored: it
# needs an Arch userland running as root to touch /etc, which is what the
# disposable container provides and a developer machine must not.
# A suite that writes to real system paths declares it with a `jail_args` file
# beside its run_all.sh, holding the --bind/--seed-* flags it needs. Such a
# suite REFUSES to run bare -- that guard is what stops a test run from
# rewriting the developer's own /etc -- so invoking it directly fails the gate.
#
# Fails closed: a marker present but empty is a mistake, not a licence to skip.
run_jailed_suite() {
local runner="$1"
local args_file="$CHECKOUT/${runner%/run_all.sh}/jail_args"
local jail_args=()
while IFS= read -r arg; do
jail_args+=("$arg")
done < <(grep -v '^#\|^$' "$args_file" || true)
if [[ ${#jail_args[@]} -eq 0 ]]; then
fail "jail_args is present but empty: $args_file"
fi
# --min 0: this gate asks "did the assertions pass?", not "is the lib at
# 100%?". Without it the jail measures the runner itself against its
# default --min 100 and fails the push on a number no one asked for.
# The coverage bar is check_shell_coverage.sh's job, per-lib and --measure'd.
# Output is captured, not discarded: on success it is noise, but on failure
# it holds the `warn: case exited` line and the suite's own FAIL: lines.
# Without this the gate reports only "suite failed" and cannot be diagnosed.
local out
if ! out="$(cd "$CHECKOUT" && bash meta/scripts/shell_coverage_jail.sh \
--subject "$runner" "${jail_args[@]}" \
--min 0 --fail-on-case-error -- "" 2>&1)"; then
printf '%s\n' "$out" >&2
fail "jailed lib/tests suite failed: $runner"
fi
}
run_shell_test_gate() {
log "lib/tests suites (mirrors the shell-tests workflow)"
local runners=()
@ -176,12 +141,8 @@ run_shell_test_gate() {
local runner
for runner in "${runners[@]}"; do
if [[ -f "$CHECKOUT/${runner%/run_all.sh}/jail_args" ]]; then
run_jailed_suite "$runner"
else
(cd "$CHECKOUT" && "$runner" >/dev/null) ||
fail "lib/tests suite failed: $runner"
fi
(cd "$CHECKOUT" && "$runner" >/dev/null) ||
fail "lib/tests suite failed: $runner"
done
log "side-effect-free shell tests (mirrors the shell-tests workflow)"

View File

@ -1,44 +0,0 @@
#!/usr/bin/env bash
# ============================================================================
# The coverage bar for check_shell_coverage.sh.
#
# Split out of that script on 2026-08-22 to keep both files under the repo's
# 250-line cap. Sourced, not executed.
# ============================================================================
# A lib is covered when its directory has a suite AND that suite drives the
# lib to COVERAGE_BAR% line coverage.
#
# This was a presence check until 2026-08-22 -- "a run_all.sh exists beside
# it" -- which is satisfiable by an empty suite that sources the lib and
# asserts nothing. The bar is a measured percentage because that is the only
# version a suite cannot trivially pass.
#
# 100% is reachable without suppressions and without touching production
# source: run the suite inside the user+mount namespace of
# shell_coverage_jail.sh and the sudo-writes, systemd units and nftables rules
# execute for real against a throwaway /etc. Measured on the repo's hardest
# library, dot_resolver_install.sh (15 root ops, 5 system writes): 39/39.
readonly COVERAGE_BAR=100
is_covered() {
local path="$1"
local suite
suite="$(dirname "$path")/tests/run_all.sh"
[[ -f "$suite" ]] || return 1
# Presence alone is enough when the measurement cannot be made: kcov is a
# developer dependency, and a hook that hard-fails on a missing tool would
# block commits on any machine without it. The CI job carries the tool and
# enforces the number, so nothing merges on presence alone.
command -v kcov >/dev/null 2>&1 || return 0
command -v unshare >/dev/null 2>&1 || return 0
"$REPO_ROOT/meta/scripts/shell_coverage_jail.sh" \
--subject "$suite" \
--bind /etc --bind /usr/local/bin --bind /var/lib \
--measure "$(basename "$path")" \
--min "$COVERAGE_BAR" \
-- "" >/dev/null 2>&1
}

View File

@ -1,64 +0,0 @@
#!/usr/bin/env bash
# ============================================================================
# write_case_runner — emit the script that executes the cases INSIDE the jail.
#
# Split out of shell_coverage_jail.sh to hold that file under the 250-line cap
# after --fail-on-case-error was added. Sourced, never run: it needs $JAIL from
# its caller.
#
# The runner is written to a file rather than inlined into the `unshare`
# 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
# quoting bug and trips SC2016.
# ============================================================================
write_case_runner() {
# The runner below executes INSIDE the namespace, so it is written out as
# its own file rather than inlined: a quoted inline block would have to
# defer every expansion to the child shell, which reads as a quoting bug
# and trips SC2016.
cat >"$JAIL/run_cases.sh" <<'INNER'
#!/usr/bin/env bash
set -u
jail="$1"
subject_dir="$2"
subject_base="$3"
measure_base="$4"
case_timeout="$5"
. "$jail/mounts.sh"
export PATH="$jail/bin:/usr/bin:/bin"
export HOME="$jail/home"
USER="${USER:-root}"
export USER
export SUDO_USER="$USER"
cd "$subject_dir" || exit 1
while IFS= read -r line; do
read -r -a case_args <<<"$line"
# Bounded, and with stdin closed. Both matter: a subject that reads stdin
# 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),
# and a subject that spins never yields at all. A timed-out case is
# reported rather than swallowed, because a silent timeout looks
# identical to an unreachable line in the coverage report.
timeout --kill-after=10s "$case_timeout" \
kcov --include-pattern="$measure_base" "$jail/cov" \
"./$subject_base" ${case_args[@]+"${case_args[@]}"} \
>/dev/null 2>&1 </dev/null
rc=$?
if [[ $rc -eq 124 || $rc -eq 137 ]]; then
printf 'warn: case timed out after %s: %s\n' "$case_timeout" "$line" >&2
printf '%s\n' "$rc" >>"$jail/case_failures"
elif [[ $rc -ne 0 ]]; then
# 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
# signal when the subject is a TEST SUITE. Record it and let the
# caller decide; swallowing it made a deliberately-broken assertion
# exit 0 through the push gate.
printf 'warn: case exited %d: %s\n' "$rc" "$line" >&2
printf '%s\n' "$rc" >>"$jail/case_failures"
fi
done <"$jail/cases"
INNER
chmod +x "$JAIL/run_cases.sh"
}

View File

@ -1,109 +0,0 @@
#!/usr/bin/env bash
# ============================================================================
# Jail construction for shell_coverage_jail.sh.
#
# Split out on 2026-08-22 to hold both files under the repo's 250-line cap
# (shfmt's reformatting pushed the combined file to 289). Sourced, not
# executed: every function here expects $JAIL, $BIND_PATHS and $EXTRA_SHIMS
# from the caller.
# ============================================================================
readonly DEFAULT_SHIMS=(
systemctl pkill pacman curl npm loginctl openrgb ddcutil i2cdetect
modprobe reboot shutdown poweroff mount umount nft iptables crontab
amixer notify-send yay makepkg
)
build_jail() {
JAIL="$(mktemp -d)"
mkdir -p "$JAIL/bin" "$JAIL/cov" "$JAIL/home" "$JAIL/etc"
local tool
for tool in "${DEFAULT_SHIMS[@]}" ${EXTRA_SHIMS[@]+"${EXTRA_SHIMS[@]}"}; do
printf '#!/usr/bin/env bash\nprintf "%%s %%s\\n" "%s" "$*" >>"%s/calls.log"\nexit 0\n' \
"$tool" "$JAIL" >"$JAIL/bin/$tool"
chmod +x "$JAIL/bin/$tool"
done
# Fact 2: give the jail a passwd where the invoking user resolves. Inside
# the userns our uid appears as 0, so the user is mapped to 0 here.
# `sudo` cannot work inside a user namespace -- it calls setresuid, which
# fails with EINVAL against an unmapped uid, and dies before running the
# command. We are already uid 0 in here, so sudo has nothing to do: this
# pass-through drops its own flags and execs the real command, which keeps
# `sudo tee /etc/foo` writing into the jail exactly as the code intends.
# It is NOT in DEFAULT_SHIMS, because recording-and-exiting would skip the
# very writes these suites exist to assert on.
cat >"$JAIL/bin/sudo" <<'SUDO'
#!/usr/bin/env bash
while [[ $# -gt 0 ]]; do
case "$1" in
-n|-H|-E|-S|-k) shift ;;
-u) shift 2 ;;
--) shift; break ;;
*) break ;;
esac
done
[[ $# -eq 0 ]] && exit 0
exec "$@"
SUDO
chmod +x "$JAIL/bin/sudo"
local user="${USER:-$(id -un)}"
printf 'root:x:0:0::/root:/bin/bash\n%s:x:0:0::%s:/bin/bash\n' \
"$user" "$JAIL/home" >"$JAIL/etc/passwd"
printf 'root:x:0:\n%s:x:0:\n' "$user" >"$JAIL/etc/group"
printf 'passwd: files\ngroup: files\n' >"$JAIL/etc/nsswitch.conf"
# A bound path is replaced by an EMPTY dir, so anything the subject needs
# to read from it must be seeded by the caller. /etc is seeded above.
# A bound path is replaced by an EMPTY dir, so the subject's writes land
# in the jail -- but a write to <bound>/sub/dir/file fails with ENOENT if
# `sub/dir` does not exist, and a subject that aborts on that failure
# looks exactly like one whose lines are unreachable. Mirroring the real
# directory tree (names only, never file contents) keeps every write path
# valid while still capturing the data.
local path idx=0
for path in ${BIND_PATHS[@]+"${BIND_PATHS[@]}"}; do
mkdir -p "$JAIL/mnt$idx"
# -r: an unreadable target (/root as a normal user) simply has no tree
# to mirror. That is not an error -- the caller seeds what it needs with
# --seed-dir -- but cd'ing into it would abort under `set -e`.
if [[ -d $path && -r $path && -x $path ]]; then
(cd "$path" && find . -type d -not -path '*/.*' -print0 2>/dev/null) |
(cd "$JAIL/mnt$idx" && xargs -0 -r mkdir -p 2>/dev/null) || true
fi
if [[ $path == "/etc" ]]; then
cp -a "$JAIL/etc/." "$JAIL/mnt$idx/"
fi
idx=$((idx + 1))
done
}
# Written to a file and read back as an array so each case keeps its quoting;
# splitting an unquoted "$args" would need an SC2086 suppression, and this
# repo forbids suppressions.
write_cases() {
local case_str
for case_str in "${CASES[@]}"; do
printf '%s\n' "$case_str"
done >"$JAIL/cases"
}
build_mount_script() {
local path idx=0
{
for path in ${BIND_PATHS[@]+"${BIND_PATHS[@]}"}; do
# mkdir first: a bind onto a path this host does not have (/var/www on
# a machine with no webserver) fails outright, and a bind that fails
# silently is the exact misdiagnosis this runner exists to avoid --
# the subject then writes to the REAL path or dies, and the report
# shows unreachable lines either way. Hence fatal, not a warning.
printf 'mkdir -p %q 2>/dev/null || true\n' "$path"
printf 'mount --bind %q %q || { printf "Error: bind failed: %s\\n" %q >&2; exit 1; }\n' \
"$JAIL/mnt$idx" "$path" '%s' "$path"
idx=$((idx + 1))
done
} >"$JAIL/mounts.sh"
}

View File

@ -1,243 +0,0 @@
#!/usr/bin/env bash
# ============================================================================
# Measure a shell script's line coverage while it runs FOR REAL, inside a
# throwaway user+mount namespace.
#
# shell_coverage_jail.sh --subject <file> [options] -- <case> [<case>...]
#
# Why a namespace and not just PATH shims: PATH shims cannot intercept a bare
# `cat >/etc/foo` (there is no binary to shadow), and they cannot make the
# root half of `if [[ $EUID -ne 0 ]]` execute. Measured on
# setup_night_lockdown.sh: PATH shims alone plateau at 81.58%; adding
# --map-root-user reaches 86.84%; bind-mounting every write target reaches
# 100.00% (38/38) with NO source changes and NO suppressions.
#
# Three facts that cost real time to find, all load-bearing:
#
# 1. --map-root-user ALONE does not grant writes to real-root-owned files.
# CAP_DAC_OVERRIDE inside a userns only covers files whose owner uid is
# mapped in, so /etc/... stays unwritable until it is bind-mounted.
# 2. The jail needs its own passwd/group/nsswitch. Inside the userns the
# invoking user does not resolve, so `id -u "$USER"` fails and aborts the
# subject under `set -e` long before the interesting code.
# 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
# 28.95%, because the wrapper sources its sibling libs from there and
# took its "libraries missing" escape hatch. An over-aggressive mount
# looks exactly like unreachable code.
#
# Entry scripts must be executed in place: they resolve their libs via
# BASH_SOURCE and common.sh via `readlink -f "$0"`, so staging a copy into a
# temp dir (which works fine for a sourced lib) breaks them.
# ============================================================================
set -euo pipefail
readonly SCRIPT_NAME="${0##*/}"
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
readonly REPO_ROOT
SUBJECT=""
MEASURE=""
SEED_DIRS=()
SEED_FILES=()
MIN_PERCENT=100
# Per-case wall-clock ceiling. A hung case cannot be distinguished from a slow
# one without a bound, and an unbounded run blocks a hook indefinitely.
CASE_TIMEOUT="120s"
# Off by default: when MEASURING, a case that exits non-zero is normal and
# wanted -- the usage example's `bogus` case exists precisely to cover an
# error path. Only a GATE, whose subject is a test suite, wants that status
# to fail the run. See --fail-on-case-error.
FAIL_ON_CASE_ERROR=0
BIND_PATHS=()
EXTRA_SHIMS=()
CASES=()
usage() {
cat <<USAGE
Usage: $SCRIPT_NAME --subject <file> [options] -- <case> [<case>...]
--subject <file> the script to RUN (required)
--measure <name> basename of the file to measure coverage OF; defaults to
the subject. Differs when the subject is a test suite
and the file of interest is the lib that suite drives.
--bind <path> bind-mount <path> to an empty jail dir; repeatable.
Use for every path the subject WRITES. Do NOT bind a
path the subject READS from -- that masks its inputs.
--shim <name> additionally stub <name> on PATH; repeatable
--seed-dir <path> create <path> inside the jail; repeatable. Needed when a
subject targets a platform this host is not -- a Debian
script writing /etc/php/8.2/apache2/ finds nothing to
mirror on an Arch box.
--seed-file <path> create an empty file at <path> inside the jail
--timeout <dur> per-case wall-clock ceiling (default 120s)
--min <percent> fail below this (default 100)
--fail-on-case-error
exit non-zero if any case exits non-zero. For GATE use,
where the subject is a test suite and a failing
assertion must fail the run. Off by default: when
measuring, an error-path case exiting non-zero is the
point of running it.
-- <case>... one invocation each; "" means "no arguments"
Example:
$SCRIPT_NAME --subject setup_night_lockdown.sh \\
--bind /etc --bind /usr/local/bin --bind /var/lib \\
-- help status bogus setup unlock
USAGE
exit 0
}
while [[ $# -gt 0 ]]; do
case "$1" in
--subject)
SUBJECT="$2"
shift 2
;;
--measure)
MEASURE="$2"
shift 2
;;
--bind)
BIND_PATHS+=("$2")
shift 2
;;
--shim)
EXTRA_SHIMS+=("$2")
shift 2
;;
--seed-dir)
SEED_DIRS+=("$2")
shift 2
;;
--seed-file)
SEED_FILES+=("$2")
shift 2
;;
--timeout)
CASE_TIMEOUT="$2"
shift 2
;;
--min)
MIN_PERCENT="$2"
shift 2
;;
--fail-on-case-error)
FAIL_ON_CASE_ERROR=1
shift
;;
-h | --help) usage ;;
--)
shift
CASES=("$@")
break
;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
validate_requirements() {
if [[ -z $SUBJECT ]]; then
echo "Error: --subject is required" >&2
exit 1
fi
if [[ ! -f $SUBJECT ]]; then
echo "Error: no such subject: $SUBJECT" >&2
exit 1
fi
if [[ ${#CASES[@]} -eq 0 ]]; then
echo "Error: at least one case is required after --" >&2
exit 1
fi
local tool
for tool in kcov unshare python3; do
if ! command -v "$tool" >/dev/null 2>&1; then
echo "Error: $tool is not installed" >&2
exit 1
fi
done
}
JAIL=""
cleanup() {
if [[ -n $JAIL && -d $JAIL ]]; then
rm -rf "$JAIL"
fi
}
trap cleanup EXIT
# Jail construction, including the shim list, lives in
# lib/shell_coverage_jail_setup.sh (250-line cap).
# shellcheck source=./lib/shell_coverage_jail_setup.sh
. "$(dirname "${BASH_SOURCE[0]}")/lib/shell_coverage_jail_setup.sh"
# The in-namespace case runner, likewise split for the 250-line cap.
# shellcheck source=./lib/shell_coverage_case_runner.sh
. "$(dirname "${BASH_SOURCE[0]}")/lib/shell_coverage_case_runner.sh"
main() {
validate_requirements
build_jail
write_cases
build_mount_script
local subject_abs subject_dir subject_base measure_base
subject_abs="$(readlink -f "$SUBJECT")"
subject_dir="$(dirname "$subject_abs")"
subject_base="$(basename "$subject_abs")"
measure_base="${MEASURE:-$subject_base}"
# A pre-run fingerprint of the working tree. Fact: running installers for
# real is only safe while every write target is mounted, and a missed
# mount presents as an unreachable line rather than an error. This turns
# that silent case into a loud one.
local tree_before
tree_before="$(cd "$REPO_ROOT" && git status --porcelain)"
write_case_runner
# Seeds are created after the mounts, from inside the namespace: a path
# under a bound target does not exist until that target is mounted.
{
local seed
for seed in ${SEED_DIRS[@]+"${SEED_DIRS[@]}"}; do
printf 'mkdir -p %q\n' "$seed"
done
for seed in ${SEED_FILES[@]+"${SEED_FILES[@]}"}; do
printf 'mkdir -p %q && : >%q\n' "$(dirname "$seed")" "$seed"
done
} >>"$JAIL/mounts.sh"
unshare --user --map-root-user --mount --fork \
"$JAIL/run_cases.sh" "$JAIL" "$subject_dir" "$subject_base" "$measure_base" \
"$CASE_TIMEOUT"
local tree_after
tree_after="$(cd "$REPO_ROOT" && git status --porcelain)"
if [[ $tree_before != "$tree_after" ]]; then
echo "Error: the subject modified the working tree; a write escaped the jail" >&2
diff <(printf '%s\n' "$tree_before") <(printf '%s\n' "$tree_after") >&2 || true
exit 1
fi
# Report coverage first -- the number is wanted even when a case failed,
# and suppressing it would hide the diagnosis behind the symptom.
local report_rc=0
python3 "$REPO_ROOT/meta/scripts/shell_coverage_report.py" \
"$JAIL/cov" "$measure_base" "$MIN_PERCENT" || report_rc=$?
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' \
"$(wc -l <"$JAIL/case_failures")" >&2
return 1
fi
return "$report_rc"
}
main "$@"

View File

@ -35,6 +35,7 @@ linux_configuration/scripts/single_use/features/lib/aw_service.sh
linux_configuration/scripts/single_use/features/lib/dns_dhcp.sh
linux_configuration/scripts/single_use/features/lib/dns_firewall.sh
linux_configuration/scripts/single_use/features/lib/dns_units.sh
linux_configuration/scripts/single_use/features/lib/dot_resolver_install.sh
linux_configuration/scripts/single_use/features/lib/dwm_config.sh
linux_configuration/scripts/single_use/features/lib/gitea_network.sh
linux_configuration/scripts/single_use/features/lib/kcd2_autorebuild.sh