Compare commits

...

12 Commits

Author SHA1 Message Date
a2b235210f Handoff: 8 libs left; record the array-literal exclusion
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
Updates state after arch_perf_fixes.sh and ubuntu_perf_more.sh landed:
allowlist 98 -> 91, seven libs cleared, 14 commits, and a fixes/lib/tests
suite of 22 files and ~330 assertions.

Adds the second instrument finding of the session to the list a future
session must know about: multi-line ARRAY LITERAL elements and their closing
paren are not statements, because bash reports the whole assignment at its
opening line. That took arch_perf_fixes.sh 93.48% -> 100%, and it is
load-bearing for the work that remains -- thorium_repairs.sh has four such
arrays and ubuntu_perf_fixes.sh one.

Also flags that the seven libs measured by an EARLIER session (dwm_config,
aw_autostart, rpi_nc_install, transcribe_*, clean_audio_filters,
pacman_hook_stall_setup) all predate both instrument fixes, so their recorded
percentages are stale and several may already be at 100%. Re-measure before
writing a single test for them.

Drops the "Not caused by this campaign" note about the red Python tests CI to
stay under the 250-line cap; it is unchanged and already in project memory.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 20:15:55 +02:00
28f2925c30 Instrument: multi-line array elements are not statements; clear arch_perf_fixes
Fourth flavour of defect (a) found this session, after multi-line quotes,
`} |` and the backslash-continued assignment. bash reports a multi-line array
assignment at its OPENING line and never emits the element lines or the
closing paren, so kcov instrumenting them inflates the denominator:

    +L3 items=('one' 'two')      # opened line 3, closed line 6
                                 # lines 4, 5, 6: never emitted

The rule is therefore symmetric with the existing multi-line-quote case: the
opening line is the statement, everything up to the closing paren is data.
_closes_array() finds that paren by recomputing quote state per candidate, so
an element like "a(b)" does not end the literal early.

Measured effect through fixes/lib/tests/run_all.sh:

  arch_perf_fixes.sh  93.48% -> 100.00%  (43/43)
  bt_audio.sh        100.00% -> 100.00%  (127/127)
  arch_perf_report.sh 100.00% -> 100.00% (59/59)
  arch_perf_probes.sh 100.00% -> 100.00% (93/93)
  ubuntu_perf_more.sh 100.00% -> 100.00% (32/32)
  bt_report.sh       100.00% -> 100.00%  (37/37)
  bt_pairing.sh      100.00% -> 100.00%  (65/65)

One gained, six held, none went DOWN. Acceptance test unchanged:
dot_resolver_install.sh 39/39 and rpi_nc_ca.sh 73/73. arch_perf_fixes.sh
therefore comes off the allowlist in the same commit, confirmed by the real
gate with no exemption.

The fail-open check, since over-detection INFLATES coverage: the old and new
predicates were diffed over every allowlisted lib plus the six cleared ones,
printing each newly excluded line WITH its text. All 91 across 10 libs are
array elements or closing parens -- common.sh's tool tables, packages.sh's
associative arrays, arch_sysctl.sh's sysctl maps, thorium_repairs.sh's four
path lists, ubuntu_perf_fixes.sh's sssd units, and so on. No statement caught.

Tests cover both directions, including three negatives: a single-line
`x=(a b)`, an element containing a parenthesis, and `x=$(echo hi)` which is a
command substitution rather than an array. Module stays at 100% branch
coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 20:13:45 +02:00
0c92a00f0f Test arch_perf_fixes.sh to 93.48% and fix the journal regex a third time
Eighth of the 16 untested fixes/lib libs. 22 assertions; 43/46 = 93.48%. The
lib STAYS on the allowlist -- see the artifact below.

Third instance of the same dead branch. Line 16 matched on
`([0-9]+\.?[0-9]*)\ G`, a required space before the unit, while journalctl
prints "4.2G" with no separator, so the vacuum could never run. Fixed to an
optional space, as in arch_perf_report.sh.

This one differs from that earlier fix and the difference was confirmed with
the user before landing: arch_perf_report.sh's vacuum sits behind
--apply-safe-fixes, but THIS one runs whenever fix_arch_performance.sh runs.
So the fix makes an unflagged destructive action live -- the script will now
really vacuum the journal to 300M once it passes a gigabyte. That is the
function's evident intent, since its next act is to write a permanent 300M
cap, and the user approved it explicitly.

Three absolute paths moved behind overrides defaulting to the real ones:
JOURNALD_CONF_DIR, SYSTEMD_UNIT_DIR (fix_media_organizer writes
/etc/systemd/system/media-organizer.service) and ORGANIZE_SCRIPT_CANDIDATES.
Verified afterwards that the real unit file still carries its 2026-07-25
mtime and the journald drop-in its 2026-03-02 one, i.e. a bare un-jailed
run_all.sh touched neither.

The three uncovered lines (68-70) are the element lines of a multi-line array
literal. `PS4` + `set -x` on a minimal case shows bash reporting the whole
assignment at its OPENING line and never emitting the elements or the closing
paren, so they are data, not statements -- a fourth flavour of defect (a),
after multi-line quotes, `} |` and the backslash-continued assignment. The
array is provably used: the loop on the next line iterates it and the
media-organizer assertions pass.

Worth fixing, unlike the bt_adapter one-liner: the form appears in three of
the remaining untested libs (thorium_repairs.sh has four) and in nine
allowlisted libs repo-wide. That lands as its own commit next.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 19:34:12 +02:00
99a9804d75 Test ubuntu_perf_more.sh to 100%: allowlist 93 -> 92
Seventh of the 16 untested fixes/lib libs and the first of the ubuntu-perf
pair, which gets its own harness here. 24 assertions; 32/32 = 100.00%
through run_all.sh on the first measurement, confirmed at --min 100 (exit 0),
then cleared with the real gate and no exemption.

Two absolute paths had to move behind env overrides, defaulting to the real
ones: fix_journal writes /etc/systemd/journald.conf.d/size-limit.conf and
run_undo globs /root for undo scripts. Binding those in the jail was rejected
for the same reason as bt_pairing.sh's udev rule -- run_all.sh runs UN-jailed
in ci_mirror.sh and in CI, so a bind mount protects the coverage run and
nothing else. JOURNALD_CONF_DIR and UNDO_DIR follow the UDEV_RULES_DIR
precedent.

Proof the suite is safe where it runs un-jailed: after a bare run_all.sh the
real /etc/systemd/journald.conf.d/size-limit.conf still carries its 2026-03-02
mtime, a genuine artifact of a past production run, and no
undo_ubuntu_performance_*.sh exists in /root.

Worth noting for the rest of the family: run_undo ends in `exit`, so its cases
run inside an explicit subshell. A command substitution already provides one,
so the exit ends only that subshell rather than the whole test file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 19:25:21 +02:00
d8c4a84470 Handoff: apply prettier formatting
The pre-push prettier hook rejected the hand-formatted markdown, which the
handoff itself warns about. Content unchanged; still exactly 250 lines.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 19:13:58 +02:00
976a111651 Handoff: 10 libs left, and the traps that cost this session time
Rewrites the handoff for the state after five libs were cleared (98 -> 93).

Corrections to the previous handoff, both of which cost time to discover:

- the "arch perf six" do NOT share one entry script. They span four:
  optimize_arch_desktop.sh, diagnose_arch_performance.sh,
  fix_arch_performance.sh and nvidia_troubleshoot.sh. The table now names
  the owner of each remaining lib.
- `_t_unstub` was described as already existing in the pacman harness. It did
  not exist anywhere. It does now, in lib_test_core.sh, along with _t_hide,
  _t_stub_stdin, _t_stub_cat and _t_stub_writes.

Also corrects an arithmetic slip in this session's own commit messages: they
read "95 -> 93" and so on, one low, because they counted total file lines
rather than entries (the allowlist holds 13 comment lines). The diff against
503ba1fc is the authority: five removals, 98 -> 93. Noted in the handoff so
the next session does not inherit the drift.

New material worth carrying forward:

- work the jail in a detached worktree, copying one-way INTO it. Copying out
  is how this session silently reverted its own uncommitted harness edit,
  twice, and briefly misattributed it to another agent.
- shfmt reformats staged shell files and WILL change a lib's denominator. It
  rewrote bt_audio.sh's one-line blocks and invalidated a 100% measurement
  taken minutes earlier. Re-measure after pre-commit touches anything.
- the backslash-continuation predicate is narrower than "has a backslash":
  only a continued ASSIGNMENT caps a lib, because bash attributes those to
  the last line of the run and a continued COMMAND to its first.
- two production bugs were found by writing tests, both dead branches. Check
  whether an untestable-looking branch is reachable at all before working
  around it.
- a background commit reported "completed (exit code 0)" while the commit
  itself had aborted on the file-length cap. Check the result, not the
  notification.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 19:10:05 +02:00
fa7b05da74 Test arch_perf_probes.sh to 100%: allowlist 93 -> 92
Sixth of the 16 untested fixes/lib libs, and the first with no dead branch to
fix -- the whole job was test-writing. 43 assertions across two files;
93/93 = 100.00% through run_all.sh, twice, the second at --min 100 (exit 0),
then cleared with the real gate confirming and no exemption.

The one genuine gap was check_memory_pressure's high-swap branch (lines
158-159), which fires only when swap is heavily used WHILE RAM is still
available -- a state this host does not happen to be in. The lib reads the
absolute /proc/meminfo, but every read goes through `awk`, so stubbing awk
supplies controlled figures without touching /proc: the stub answers on the
pattern being matched and execs the real awk for anything else. Both
directions are covered, including RAM genuinely exhausted, which must NOT be
flagged because it is not the stutter signature.

Everything else here is branch coverage of probes whose inputs are external
commands: failed systemd units, ACPI error counts, a CPU-hungry Xorg,
governors all-performance vs one-powersave vs unsupported, thermal
throttling excerpts, the TLP/power-profiles-daemon conflict in all three
combinations, and storage health with and without fstrim/smartctl.

lib_test_core.sh gains _t_stub_cat. "Print this fixture file" is by far the
commonest stub shape, and writing it inline forces every call site to embed
a literal ${LIB_TEST_DEV} that must not expand at write time -- SC2016 on
every use. Passing the fixture NAME as data removes the class outright, and
two earlier bluetooth test files are simplified onto it. All 21 test files
and three harnesses now lint clean with no suppression anywhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 19:04:50 +02:00
c309c95f5a Clear bt_audio.sh and arch_perf_report.sh: allowlist 95 -> 93
Both were already tested to their reachable ceiling earlier in this session
(a5b6663c, ffcf99f1) and held below 100% only by the closing-brace artifact
that d989cd7e removed. With the instrument corrected they measure:

  bt_audio.sh          127/127 = 100.00%
  arch_perf_report.sh   59/59  = 100.00%

both at --min 100 with exit 0, and check_shell_coverage.sh returns
"every checked shell library meets the coverage bar" with their allowlist
lines already gone, i.e. with no exemption. bt_report.sh and bt_pairing.sh
were gated in the same run to confirm the two libs cleared earlier did not
regress.

Note that the closing-brace exclusion is now load-bearing: reverting
d989cd7e without also restoring these two lines would turn every subsequent
commit red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 18:40:05 +02:00
d989cd7ebf Coverage instrument: a closing brace plus an operator is not a statement
continuation_lines() excluded the continuation lines of multi-line QUOTED
arguments but nothing else, so a line holding only a group's closing brace
and an operator -- `} |`, `} >>"$REPORT_FILE"` -- stayed in the denominator
while bash attributed no statement to it. That capped four fixes/lib libs
below 100% with no test able to move them.

Why the anchor makes this safe: bash attributes every command INSIDE a group
to its own line, and a pipe's right-hand side to its own line, leaving the
brace-plus-operator line with nothing. Anchoring the pattern on a LEADING
`}` therefore excludes only lines that can hold no statement. A one-liner
`{ echo a; } >file` begins with `{` and is untouched; a bare `}` closing a
function has no operator and is untouched.

Measured effect, all through fixes/lib/tests/run_all.sh:

  bt_audio.sh          96.97% -> 100.00%  (127/127)
  arch_perf_report.sh  98.33% -> 100.00%  (59/59)
  bt_report.sh        100.00% -> 100.00%  (37/37)
  bt_pairing.sh       100.00% -> 100.00%  (65/65)
  bt_adapter.sh        98.55% ->  98.55%  (68/69, capped by a different flavour)

Two gained, three held, none went DOWN -- the handoff's regression signal.
That is not luck: _measure computes covered_set = (executed|traced) &
denominator, so for a lib already at 100% the covered set IS the denominator
and removing a subset cannot lower it. The five gated pacman_hook_stall libs
are safe by the same arithmetic.

Acceptance test from the handoff passes unchanged: dot_resolver_install.sh
39/39 and rpi_nc_ca.sh 73/73, both 100.00%.

The fail-open check that actually matters, since over-detection INFLATES
coverage and could promote an untested lib: the new predicate was run over
every lib in the allowlist plus the cleared ones, printing each newly
excluded line WITH its text. All 17 across 10 libs are genuine
brace-plus-operator lines; no ordinary statement was caught.

Tests cover both directions, including the two negative cases (a bare `}`
and a single-line `{ ...; } >file`), keeping the module at 100% branch
coverage. The quote scanner moved into _quote_after() to stay under the
C901 complexity limit rather than suppressing it.

Deliberately NOT fixed here: the backslash-continued ASSIGNMENT flavour that
caps bt_adapter.sh line 97. bash attributes those to the LAST line of the run
but a backslash-continued plain COMMAND to its FIRST, so that predicate needs
a command-vs-assignment distinction. One line in one lib; not worth the
landmine today.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 18:29:47 +02:00
ffcf99f102 Test arch_perf_report.sh to 98.33% and fix its dead journal-size check
Fifth of the 16 untested fixes/lib libs and the first of the arch-performance
group, which gets its own harness here. 38 assertions across two files. The
lib STAYS on the allowlist at 59/60 = 98.33%, measured twice.

The second dead branch this campaign has found, fixed here. Lines 36 and 65
matched on:

    ([0-9]+\.?[0-9]*)\ (G|M)

a REQUIRED space before the unit. journalctl actually prints "Archived and
active journals take up 305.5M in the file system." with no separator --
verified against the real binary on this machine. So check_journal_size could
never report a large journal and apply_safe_fixes could never vacuum one:
both were unreachable. The space is now optional, and tests cover the spaced
and unspaced forms so neither can rot.

NOTE: this makes a previously-dead DESTRUCTIVE action live. With
--apply-safe-fixes and a journal over a gigabyte, the entry script will now
really run `journalctl --vacuum-size=300M`. That is the flag's documented
purpose and it stays behind the flag, but it has never actually executed
before today.

Line 20, the one uncovered line, is `} >>"$REPORT_FILE"` -- the closing brace
of a redirected group. A minimal probe writes both inner lines to the file
while bash attributes no statement to the brace, and the report assertions
independently prove the group runs, since they read the text it writes. Same
defect (a) class as bt_audio's `} |`.

That form now caps four libs: bt_audio.sh, arch_perf_report.sh, and
arch_perf_probes.sh and nvidia_config.sh which are still untested. So the
continuation_lines() fix is worth landing after all -- as its own commit,
next, so a denominator change can be reverted without taking these tests
with it.

_t_hide and _t_full_path move from bt_harness.sh into lib_test_core.sh: they
are generic PATH plumbing and the arch harness needs them for the
"nvidia-smi is not installed" branch. All twelve existing suites re-run green
after the move.

One trap worth recording: apply_safe_fixes appends to the ACTIONS array, so
it must be called directly rather than inside "$(...)" -- a command
substitution runs it in a subshell where the appends die with it, and the
assertions read an empty array.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 18:06:57 +02:00
a5b6663c02 Test bt_audio.sh to 96.97% and fix its wpctl health check
Fourth of the 16 untested fixes/lib libs, the largest at 214 lines, and the
last of the bluetooth family. 47 assertions across three files. The lib
STAYS on the allowlist: 128/132 = 96.97%, twice with the same line set.

The bug the tests found, fixed here. Line 21 read:

    if timeout 3 _run_as_user wpctl status &>/dev/null; then

`timeout` is a binary and `_run_as_user` is a shell function that is never
exported, so this always failed with rc=127 -- "timeout: failed to run
command '_run_as_user'". check_pipewire_health therefore reported PipeWire
hung on EVERY run and restarted a healthy audio stack every time
fix_bluetooth.sh ran. The healthy branch was unreachable, which is why the
test for it could not be written without first noticing. Now
`_run_as_user timeout 3 wpctl status`: same bound, inside the sudo'd command.

Why 96.97% and not 100%. An earlier run of this suite read 99/99 = 100.00%,
and that number was wrong -- it measured the file before pre-commit's
`shfmt -w` reformatted it. shfmt rewrites the `{ ...; } \` + `| bluetoothctl`
one-liners into multi-line blocks ending in `} |`, which raises the
denominator 99 -> 132. Confirmed unavoidable by running shfmt against HEAD's
own copy: it rewrites there too, so reverting the reformat is not stable.

The four uncovered lines (90, 113, 137, 157) are each that `} |` -- the pipe
operator joining a block to bluetoothctl, not a statement. They do execute:
a `{ echo a; echo b; } | consumer` block writes every marker to a file even
though bash's xtrace never reports the left-hand side, because a pipe's LHS
runs in a subshell whose xtrace is not captured. kcov instruments them and
cannot attribute them; defect (a) in docs/kcov-under-report.md, third flavour.

Scope, measured: the continuation-pipe form appears ONLY in bt_adapter.sh
(pre-format) and bt_audio.sh (post-shfmt). None of the remaining twelve
untested libs carries either, so this does not block the campaign and the
detector fix stays off the critical path.

Also worth 90.91% -> 96.97% on its own: the bluetoothctl stubs now drain
stdin before exiting. Real bluetoothctl consumes its whole input; a stub
that read one line and exited closed the pipe early, so the writing block
took SIGPIPE partway through and its later lines never ran.

NOTE for whoever edits this file next: bt_audio.sh is now exactly 250 lines,
at the cap. The next change to it needs a split, not a comment trim.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 17:52:24 +02:00
434cb7587e Test bt_adapter.sh to 98.55%; line 97 is unreachable by construction
Third of the 16 untested fixes/lib libs, and the first that does NOT come
off the allowlist. 68/69 = 98.55%, up from 45/69. The remaining line is
not a missing test:

  PS4='+TRACE:${BASH_SOURCE##*/}:${LINENO} ' bash -x

shows bash attributing the whole multi-line dbus-send assignment in
_services_resolved to line 100, and never emitting line 97 at all. Line 97
is the OPENING line of a backslash-continued statement; kcov instruments
it, bash never attributes a statement to it. That is defect (a) in
docs/kcov-under-report.md -- a wrong denominator -- and no test can move it.

continuation_lines() in shell_coverage_lines.py already excludes such lines,
but only detects them by tracking QUOTE state, so a line ending in an
unquoted backslash slips through. Fixing that is deliberately left out of
this commit: it changes the denominator for every measured lib, and if it
regresses one of the libs now gated with no exemption, reverting a mixed
commit would throw away these tests too.

Scope of the problem, measured rather than guessed -- backslash
continuations are confined to the bluetooth family: bt_audio.sh 10,
bt_adapter.sh 7, bt_pairing.sh 3, pacman_hook_stall_summary.sh 2, and ZERO
in the other 12 remaining libs. So this caps bt_audio.sh next and then stops
mattering.

Also replaces the harness's _t_only_path with _t_hide. _t_only_path dropped
PATH to $FAKE_BIN alone, which hid grep, head and sort as well as the tool
under test -- so the "usbreset is not installed" case died in a cascade of
"command not found" and passed for the wrong reason instead of exercising
the fallback. _t_hide rebuilds PATH from symlinks to every real executable
except the named ones; verified directly that command -v usbreset is then
empty while grep and head still resolve.

bt_report.sh (37/37) and bt_pairing.sh (65/65) re-measured at --min 100,
both exit 0, so neither cleared lib regressed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 17:10:15 +02:00
37 changed files with 2712 additions and 210 deletions

View File

@ -1,71 +1,61 @@
# Next session: test the 16 untested `fixes/lib` libs to 100%
# Next session: the 8 remaining untested `fixes/lib` libs
> **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 job
`linux_configuration/scripts/single_use/fixes/lib/` has 22 libs. Six are done
and off the allowlist. **Sixteen have no tests at all.** Write them, to 100%
line coverage, and take each one off `meta/shell-coverage-allowlist.txt`.
`linux_configuration/scripts/single_use/fixes/lib/` has 22 libs. **Eight still
have no tests.** Write them, to 100% line coverage, and take each one off
`meta/shell-coverage-allowlist.txt`.
That is the largest remaining block of real test-writing work in the campaign.
| lines | lib | entry script |
| ----- | ------------------------- | ------------------------------------- |
| 215 | `ubuntu_perf_fixes.sh` | `fix_ubuntu_performance.sh` |
| 202 | `arch_hardware.sh` | `optimize_arch_desktop.sh` |
| 180 | `nvidia_config.sh` | `nvidia_troubleshoot.sh` |
| 179 | `thorium_repairs.sh` | `fix_thorium.sh` |
| 161 | `hosts_guard_migrate.sh` | `migrate_hosts_guard_to_guard_lib.sh` |
| 141 | `hosts_guard_rollback.sh` | same |
| 126 | `arch_cpu.sh` | `optimize_arch_desktop.sh` |
| 122 | `arch_sysctl.sh` | `optimize_arch_desktop.sh` |
| lines | lib | family |
| ----- | ------------------------- | -------------------------------------- |
| 215 | `ubuntu_perf_fixes.sh` | ubuntu perf |
| 214 | `bt_audio.sh` | bluetooth (`fix_bluetooth.sh`) |
| 202 | `arch_hardware.sh` | arch perf (`optimize_arch_desktop.sh`) |
| 180 | `nvidia_config.sh` | arch perf |
| 179 | `thorium_repairs.sh` | standalone |
| 166 | `arch_perf_probes.sh` | arch perf |
| 161 | `hosts_guard_migrate.sh` | hosts guard |
| 150 | `bt_adapter.sh` | bluetooth |
| 141 | `hosts_guard_rollback.sh` | hosts guard |
| 128 | `bt_pairing.sh` | bluetooth |
| 126 | `arch_cpu.sh` | arch perf |
| 122 | `arch_sysctl.sh` | arch perf |
| 121 | `arch_perf_fixes.sh` | arch perf |
| 103 | `arch_perf_report.sh` | arch perf |
| 80 | `ubuntu_perf_more.sh` | ubuntu perf |
| 76 | `bt_report.sh` | bluetooth |
**Suggested order: smallest first, grouped by entry script.** The three
`optimize_arch_desktop.sh` libs (`arch_cpu`, `arch_sysctl`, `arch_hardware`)
share a harness; so do the two hosts-guard libs and the two ubuntu-perf ones.
**Suggested order: smallest first, by family.** `bt_report.sh` (76) then the
rest of the bluetooth four; the arch-perf six share `optimize_arch_desktop.sh`
and will share stubs. Do not start with `ubuntu_perf_fixes.sh`.
**The last handoff mis-grouped these — do not trust its "arch perf six share
one entry script" claim.** They span four different entry scripts, as above.
## Everything you need already exists — do NOT build a new harness
`fixes/lib/tests/` is a working suite. It has:
`fixes/lib/tests/` is a working suite: **20 test files, all green, all
shellcheck-clean with zero suppressions.** It has three layers:
- `run_all.sh` — the runner. **This is the subject the gate measures through.**
- `pacman_hook_stall_harness.sh` (205 lines) — lib-level harness: `mktemp -d`
sandbox, a `FAKE_BIN` PATH stub dir, `_t_eq` / `_t_pass` / `_t_fail`,
and `_t_unstub` (which also runs `hash -r`).
- `pacman_hook_stall_entry_harness.sh` (142 lines) — same for entry scripts.
- Eight `test_*.sh` files to copy the shape from.
- `lib_test_core.sh` — the shared primitives. Read this first:
- `_t_eq` / `_t_contains` / `_t_lacks` / `_t_pass` / `_t_fail`
- `_t_stub NAME BODY`, and the three helpers that exist to keep call sites
free of quoted `$`: **`_t_stub_stdin NAME` (body from a quoted heredoc),
`_t_stub_cat NAME FIXTURE` (print `$DEV/FIXTURE`), `_t_stub_writes NAME
ARGNUM CONTENT`**. Use these instead of `_t_stub foo '...$1...'`, which
trips SC2016 every single time.
- `_t_unstub NAME...` (runs `hash -r`; deleting the file alone does not work)
- **`_t_hide TOOL...`** — rebuilds PATH from symlinks to every real binary
EXCEPT the named ones. This is how you test a "not installed" branch when
the host genuinely has the tool. Do NOT drop PATH to `$FAKE_BIN` alone:
that also hides `grep`/`head`/`awk`, and the case then passes for the
wrong reason.
- `_t_calls` / `_t_reset_calls` — what the stubs recorded.
- Two family harnesses, `bt_harness.sh` and `arch_perf_harness.sh`. Each
sources the core, sources the real `scripts/lib/common.sh` for the
production `log_*`/`has_cmd` helpers (it is inert at source time), and
redefines the helpers that live in the **entry script** rather than any lib.
**jscpd fails the commit above 2% duplication**, so extend/parameterise these
rather than cloning a harness per family. If a family genuinely needs
different setup, add a small harness that _sources_ the existing one.
No `jail_args` file sits beside `run_all.sh`, deliberately: the harness
confines every write to its own `mktemp -d` and stubs external commands on
PATH. Keep it that way — the new tests must not write to `/etc`, `/var` or
`/usr`. If a lib insists on writing an absolute path, stub the writer, do not
add a bind mount.
## What these libs touch (drives your stubs)
`systemctl` (most common), `bluetoothctl`, `pacman`, `sysctl`, `sudo`,
`nvidia-*`, `apt-get`. `systemctl`, `pacman` and `sudo` are already in the
jail's `DEFAULT_SHIMS`; the rest you stub in `FAKE_BIN`.
Two entry scripts source these libs, and are the place to look for how each
lib is really called:
- `linux_configuration/scripts/single_use/fixes/fix_bluetooth.sh`
- `linux_configuration/scripts/single_use/fixes/optimize_arch_desktop.sh`
**To add a family:** copy `arch_perf_harness.sh`'s shape. It is ~100 lines and
the only family-specific parts are the entry-script helpers and the default
stub list. jscpd already excludes `**/lib/tests/**`, so shared test setup
carries no duplication risk.
## The loop, per lib
@ -82,131 +72,176 @@ timeout 900s bash meta/scripts/shell_coverage_jail.sh \
# 4. close the gap, repeat until 100.00%
```
**Always measure through `run_all.sh`, never a single test file.** That is the
subject `is_covered()` builds, and the runner's number can be LOWER than a
suite's own.
**Always measure through `run_all.sh`, never a single test file.**
## The bar for taking a lib off the allowlist
Do all three. This is the standard the five cleared libs met:
1. Measure 100.00% through `run_all.sh`.
2. **Measure again at `--min 100`** so a shortfall is a non-zero exit rather
than a number you might misread.
3. Remove the line from `meta/shell-coverage-allowlist.txt`, then run the real
gate with no exemption and confirm exit 0:
2. **Measure again at `--min 100`** so a shortfall is a non-zero exit.
3. Remove the line from `meta/shell-coverage-allowlist.txt`, then run the gate
with no exemption and confirm exit 0:
```bash
bash meta/scripts/check_shell_coverage.sh <path to lib>.sh
# expect: "every checked shell library meets the coverage bar"
```
Two matching runs matters: this directory's suites drive timing loops, and a
timing-dependent suite can vary its line set between runs (`dwm_config.sh` was
observed doing exactly that). A flaky 100% becomes a red CI job whose cause is
invisible.
Allowlist is at **91** entries — count with `grep -vc '^#'`, since the file
also holds 13 comment lines.
Allowlist is at **98** entries. Each lib you finish takes it down by one.
## Work the jail in a detached worktree
## The instrument is FIXED — trust its numbers now
The jail fingerprints `git status --porcelain` and aborts with "a write
escaped the jail" if the tree changes **during** a run — it compares a delta,
so a pre-existing dirty file is fine but any concurrent write is not. Editing
anything mid-run trips it, and so does a background build.
Use a throwaway worktree and **copy one-way, INTO it, never out**:
```bash
SP=/tmp/claude-.../scratchpad # your scratchpad
git worktree add --detach "$SP/cov" HEAD
cp <files> "$SP/cov/<same paths>" # never the reverse
```
Copying _out_ of the worktree is how the last session silently reverted its
own uncommitted harness edit, twice, and misdiagnosed it as another agent.
## The instrument: FIXED, and now correct for two more shapes
Coverage = `(PS4-traced lines | kcov hits) & (kcov line set - continuation lines)`
Two passes, two namespaces, because kcov's ptrace and bash's xtrace cannot
share a process. Full detail in `docs/kcov-under-report.md`. You should not
need to touch it. If you do, the acceptance test is
`dot_resolver_install.sh` = 39/39 and `rpi_nc_ca.sh` = 73/73, and **no lib's
percentage may go DOWN** — a drop means a lost trace, not a stricter
instrument.
`continuation_lines()` in `meta/scripts/lib/shell_coverage_lines.py` excludes
lines kcov instruments but bash attributes no statement to. It now handles:
One bound to know: the report may print
- continuation lines of a multi-line **quoted** argument (pre-existing);
- **multi-line array literal elements and the closing paren** — bash reports
the whole assignment at its OPENING line. This alone took
`arch_perf_fixes.sh` 93.48% -> 100%, and it matters for the libs left:
`thorium_repairs.sh` has four such arrays and `ubuntu_perf_fixes.sh` one.
- **a closing brace plus an operator** — `} |`, `} >>file` (added in
`d989cd7e`). This alone took `bt_audio.sh` 96.97% -> 100% and
`arch_perf_report.sh` 98.33% -> 100%.
```
outside kcov's line set (ran, but counted in neither half): 68, 70, ...
Acceptance test if you ever touch it: `dot_resolver_install.sh` = 39/39 and
`rpi_nc_ca.sh` = 73/73, **through `features/lib/tests/run_all.sh` WITH the
`jail_args` file beside it** (that suite refuses to run bare). And **no lib's
percentage may go DOWN**.
Note the arithmetic that bounds any denominator change: `_measure` computes
`covered_set = (executed|traced) & denominator`, so a lib already at 100.00%
**cannot** regress from excluding more lines. Over-exclusion is the only real
risk — it inflates coverage and could promote an untested lib — so audit any
new predicate by printing every newly-excluded line **with its text**.
### The one known-unfixed artifact
`bt_adapter.sh` sits at **98.55% (68/69), still exempt**, capped by line 97:
the opening line of a backslash-continued **assignment**
(`result=$(dbus-send ... \`). bash attributes that statement to the LAST line
of the run, so the opening line can never be covered.
**The predicate is narrower than "has a backslash".** A backslash-continued
plain **command** (`apply_fix "..." \`) is attributed to its **FIRST** line and
covers normally — `bt_pairing.sh` has three and reached 100%. Only the
assignment flavour caps a lib. Find them with:
```bash
grep -nE '^[[:space:]]*(local[[:space:]]+)?[A-Za-z_][A-Za-z0-9_]*=.*\\$' <lib>
```
That **cannot inflate a number** — such a line is by construction one the
trace saw execute, so folding it in only ever raises the figure. It does mean
the lib is measured over a subset of its statements. Read the list before
clearing that lib; if the lines are ordinary statements, say so in the
evidence.
Across all 22 libs that matches only `bt_adapter.sh` (1) and `bt_audio.sh` (2),
and bt_audio still reached 100%, so this blocks exactly one line in one lib.
Fixing it means teaching `continuation_lines()` the command-vs-assignment
distinction. Not worth it for one entry unless you hit it again.
## Two production bugs were found by writing tests. Expect more.
Both were dead branches that no test could have covered without noticing:
- `bt_audio.sh:21` — `timeout 3 _run_as_user wpctl status`. `timeout` is a
binary and cannot invoke a shell function, so it always returned 127 and
the PipeWire health check restarted a healthy audio stack on every run.
- `arch_perf_report.sh:36,65` — the journal-size regex required a space
before the unit (`4.2 G`), but `journalctl` prints `305.5M`. The size
check and the vacuum were both unreachable.
**When a branch looks untestable, check whether it is actually reachable in
production before writing a test around it.** The user's standing answer when
asked has been "fix it in this commit".
## Traps that cost real time
- **Never edit the working tree while a measurement runs.** The jail
fingerprints `git status --porcelain` and aborts with "a write escaped the
jail". Editing an unrelated file trips it. FALSE alarm; cost two runs last
session, the second time after it had already been diagnosed. Commit before
starting a sweep; use the scratchpad for notes.
- **A sweep's output file buffers.** `pgrep -x kcov` is the liveness signal,
not file growth. A measurement silent for minutes is usually still running;
this directory's suites take 30s+ per kcov pass, and there are two passes.
- **`shfmt` runs on every staged shell file and WILL reformat your lib.** It
rewrote `bt_audio.sh`'s `{ ...; } \` one-liners into multi-line blocks,
which raised its denominator 99 -> 132 and invalidated a 100% measurement
taken minutes earlier. **Re-measure after pre-commit reformats anything**,
and put the post-format number in the evidence.
- **`bt_audio.sh` is now exactly 250 lines, AT the cap.** The next edit to it
needs a file split, not a comment trim.
- **A stub must consume what the real tool consumes.** A `bluetoothctl` stub
that read one line and exited closed the pipe, so the writing
`{ ...; } | bluetoothctl` block took SIGPIPE partway through and its later
lines never ran. `cat >/dev/null` before exiting was worth 6 points.
- **A function that appends to a global array must not be called inside
`$( )`.** The subshell dies with the substitution and the array is empty.
Redirect to a file and `cat` it instead.
- **A top-level stub function SHADOWS the subject's own** for every later
assertion. Put redefinitions in a subshell, and bind them with
`eval '_real_name() { _my_recorder "$@"; }'` so shellcheck still sees the
recorder as called (SC2329).
- **A prepended stub dir cannot hide a real binary** — use `_t_hide`.
- **Do not `pgrep -f shell_coverage_jail` in a wait loop** — the loop's own
command line matches, so it never exits.
- **`--fail-on-case-error` or you are flying blind.** The jail suppresses the
suite's stdout, so assertions fail invisibly without it.
- **To find WHERE a suite dies, use an `exit <n>` sentinel.** The jail
surfaces the code. The only way to tell a tracing failure from an abort.
- **`rm -f "$TEST_TMPDIR/bin/foo"` does NOT hide foo.** bash caches executable
locations. Use `_t_unstub`, which also runs `hash -r`.
- **A prepended stub dir cannot hide a real binary.** If the host genuinely
has the tool, REPLACE PATH or jail it, or the "not installed" case tests
nothing.
- **A stub must materialise what the real tool creates.** A record-only stub
in a `[[ ! -s $file ]]` chain silently exercises the NEXT branch.
- **A top-level stub function SHADOWS the subject's own** for every later
assertion. Put redefinitions in a subshell.
- **`shfmt` and `prettier` reformat after your check passes** — re-check the
250-line cap after staging, and expect the pre-push prettier hook to reject
hand-formatted markdown.
- **Commits and pushes exceed a 2-minute foreground timeout.** Background them.
- **Commits exceed a 2-minute foreground timeout.** Background them, and
**check the result** — a `file-length-cap` failure aborted one commit that
a task notification had reported as "completed (exit code 0)".
- **`mapfile` is bash-only**; the Bash tool's shell is zsh. Wrap in `bash -c`.
- **Two-strike rule.** Two failed attempts at the same thing -> stop, document,
keep the working state.
## Rules that will bite you
- **No suppressions, ever.** Fix SC2016/SC2155/EXE001/PLR2004 at the source.
- **Never weaken an assertion to move a number.** If a percentage looks absurd
while assertions pass, suspect the instrument and re-measure.
- **No suppressions, ever.** Fix SC2016/SC2034/SC2329/C901 at the source. The
three `_t_stub_*` helpers and `_quote_after()` exist precisely because the
alternative was a `# shellcheck disable`.
- **Never weaken an assertion to move a number.**
- **Every commit touching code needs evidence** in
`docs/superpowers/evidence/<slug>-<date>.json` (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.
- **New test files need the exec bit** — `git add --chmod=+x` only changes the
INDEX; `chmod +x` the working tree too or the shebang hook fails.
- **Stage narrowly.** Another session may be working in this repo at the same
time; `git restore --staged` anything you did not touch.
- **New test files need the exec bit** — `chmod +x` the working tree.
- **Stage narrowly.**
- Work directly on `main`. `git stash` and branch creation are blocked.
## State as of 2026-08-22
## State as of 2026-08-22 (end of session)
Allowlist **98**. Instrument fixed and pushed (`81191f40`, `29b8c5a7`). Five
libs cleared (`83de41f4`). `fixes/lib/tests/run_all.sh` added (`347222b9`).
Allowlist **91**, down from 98 — seven libs cleared. Fourteen commits,
`4cfc3fdd`..`28f2925c`. The `fixes/lib/tests` suite is 22 files / ~330
assertions, all green, all shellcheck-clean with zero suppressions.
Already measured — do NOT redo:
| lib | coverage | status |
| --------------------- | --------------------- | -------------------------- |
| `bt_report.sh` | **37/37 = 100.00%** | CLEARED |
| `bt_pairing.sh` | **65/65 = 100.00%** | CLEARED |
| `bt_audio.sh` | **127/127 = 100.00%** | CLEARED |
| `arch_perf_report.sh` | **59/59 = 100.00%** | CLEARED |
| `arch_perf_probes.sh` | **93/93 = 100.00%** | CLEARED |
| `ubuntu_perf_more.sh` | **32/32 = 100.00%** | CLEARED |
| `arch_perf_fixes.sh` | **43/43 = 100.00%** | CLEARED |
| `bt_adapter.sh` | 68/69 = 98.55% | exempt, see artifact above |
| lib | coverage |
| ---------------------------- | ------------------- |
| `rpi_nc_ca.sh` | **73/73 = 100.00%** |
| `dot_resolver_install.sh` | **39/39 = 100.00%** |
| `dwm_config.sh` | 65/66 = 98.48% |
| `pacman_hook_stall_setup.sh` | 26/27 = 96.30% |
| `aw_autostart.sh` | 80/82 = 97.56% |
| `rpi_nc_install.sh` | 85/88 = 96.59% |
| `transcribe_pkgmgr.sh` | 49/50 = 98.00% |
| `clean_audio_filters.sh` | 85/93 = 91.40% |
| `transcribe_deps.sh` | 48/52 = 92.31% |
Measured by an earlier session, all still exempt: `dwm_config.sh` 98.48%,
`pacman_hook_stall_setup.sh` 96.30%, `aw_autostart.sh` 97.56%,
`rpi_nc_install.sh` 96.59%, `transcribe_pkgmgr.sh` 98.00%,
`clean_audio_filters.sh` 91.40%, `transcribe_deps.sh` 92.31%. **All predate
both instrument fixes and may now measure higher — re-measure before writing
a single test for them.**
`rpi_nc_ca.sh` and `dot_resolver_install.sh` are at 100% and could come off
the allowlist whenever you want, by the three-step bar above.
`rpi_nc_ca.sh` (73/73) and `dot_resolver_install.sh` (39/39) are at 100% and
could come off the allowlist whenever you want, by the three-step bar.
**`nc_php.sh` does not measure at all** — "kcov instrumented no lines", on the
pre-fix instrument too (checked at `078d3463` in a throwaway worktree). Not a
regression. Its old 84/85 = 98.82% does not reproduce; treat as unverified.
## 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`. Needs
dependency pinning; deliberately excluded from `check_ci_green.sh`. Do not
fold it into this work.
pre-fix instrument too. Not a regression; treat as unverified.

View File

@ -0,0 +1,17 @@
{
"title": "Test arch_perf_probes.sh to 100% and clear it from the shell-coverage allowlist",
"objective": "Cover the sixth of the sixteen untested fixes/lib libs, the diagnostic-probe half of diagnose_arch_performance.sh. Unlike the two libs before it this one contains no dead branch, so the whole job is test-writing: reaching the swap-pressure branch that depends on /proc/meminfo, and the governor branches that depend on a real /sys tree.",
"acceptance_criteria": [
"arch_perf_probes.sh measures 100.00% (93/93) through lib/tests/run_all.sh, twice, the second run at --min 100 with exit 0.",
"check_shell_coverage.sh exits 0 for arch_perf_probes.sh with its allowlist line removed, i.e. with no exemption.",
"The check_memory_pressure swap branch is genuinely exercised with controlled figures, not skipped because this host happens to swap.",
"Every file in fixes/lib/tests stays under the repo's 250-line cap and passes shellcheck with no suppression added.",
"The five libs cleared earlier in the session still pass the gate."
],
"out_of_scope": [
"Any change to arch_perf_probes.sh itself.",
"bt_adapter.sh, still exempt at 98.55% for the backslash-continued assignment flavour of defect (a).",
"The remaining ten untested fixes/lib libs."
],
"verifier": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh (expects all 21 files passing, 16 + 27 for the two arch_perf_probes files), plus bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure arch_perf_probes.sh --min 100 --fail-on-case-error -- \"\" (expects 93/93 = 100.00% and exit 0), plus bash meta/scripts/check_shell_coverage.sh linux_configuration/scripts/single_use/fixes/lib/arch_perf_probes.sh (expects exit 0)."
}

View File

@ -0,0 +1,18 @@
{
"title": "Test arch_perf_report.sh, open the arch-performance family, and fix the dead journal-size check",
"objective": "Cover the fifth of the sixteen untested fixes/lib libs and stand up the harness the arch-performance group will share. Writing the tests exposed a second dead branch -- the journal size regex demanded a space before the unit that journalctl never prints -- so this lands that fix alongside the coverage. The lib stops at 98.33%: its last line is a redirected closing brace no test can reach.",
"acceptance_criteria": [
"arch_perf_report.sh measures 98.33% (59/60) through lib/tests/run_all.sh, twice, with line 20 the only uncovered line both times.",
"The old journal regex is shown NOT to match journalctl's real output before the fix, and the fixed one shown to match both the spaced and unspaced forms.",
"Line 20 is shown to be a closing brace of a redirected group that executes, not a missing test.",
"meta/shell-coverage-allowlist.txt is UNCHANGED -- arch_perf_report.sh does not meet the 100% bar.",
"The four bluetooth suites and the eight pacman_hook_stall suites still pass after _t_hide and _t_full_path move into lib_test_core.sh.",
"Every file stays under the repo's 250-line cap, and pre-commit passes with no suppression added."
],
"out_of_scope": [
"Clearing arch_perf_report.sh, bt_audio.sh or bt_adapter.sh from the allowlist. All three are capped by defect (a) in docs/kcov-under-report.md.",
"Changing continuation_lines() in meta/scripts/lib/shell_coverage_lines.py. That is the next commit, kept separate so a denominator change can be reverted without losing these tests.",
"The remaining eleven untested fixes/lib libs."
],
"verifier": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh (expects all files passing, 17 + 21 for the two arch_perf_report files), plus bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure arch_perf_report.sh --min 1 --fail-on-case-error -- \"\" (expects 59/60 = 98.33%, uncovered 20), plus bash meta/scripts/check_shell_coverage.sh on the cleared libs (expects exit 0)."
}

View File

@ -0,0 +1,17 @@
{
"title": "Test bt_adapter.sh, and record why its last line is unreachable",
"objective": "Cover the third of the sixteen untested fixes/lib libs. Unlike the first two this one does NOT come off the allowlist: it tops out at 98.55% because line 97 is the opening line of a backslash-continued statement, which kcov instruments but bash never attributes a statement to. The deliverable is therefore the tests plus a proven diagnosis, not a cleared entry.",
"acceptance_criteria": [
"bt_adapter.sh measures 98.55% (68/69) through lib/tests/run_all.sh, with line 97 the only uncovered line.",
"The claim that line 97 is unreachable is proven by a PS4 trace showing bash attributing the statement to line 100, not asserted.",
"bt_report.sh and bt_pairing.sh still measure 100.00% at --min 100 with exit 0, since both are now gated with no exemption.",
"The whole suite passes bare: run_all.sh reports all test files passing.",
"Every test file stays under the repo's 250-line cap, and pre-commit passes with no suppression added."
],
"out_of_scope": [
"Removing bt_adapter.sh from meta/shell-coverage-allowlist.txt. It is not at 100%, so it does not meet the bar.",
"Changing continuation_lines() in meta/scripts/lib/shell_coverage_lines.py to recognise backslash continuations. That alters the denominator for every measured lib and must land on its own, so a regression can be reverted without losing these tests.",
"Reformatting bt_adapter.sh to collapse the multi-line dbus-send call. Production source is not rewritten to please the coverage tool."
],
"verifier": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh (expects all files passing, 14 + 27 for the two bt_adapter files), plus bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure bt_adapter.sh --min 1 --fail-on-case-error -- \"\" (expects 68/69 = 98.55%, uncovered: 97), plus the same command with --measure bt_report.sh and --measure bt_pairing.sh at --min 100 (expects 37/37 and 65/65, exit 0)."
}

View File

@ -0,0 +1,19 @@
{
"title": "Test bt_audio.sh to its reachable ceiling, and fix the timeout bug the tests found",
"objective": "Finish the bluetooth family, the fourth of the sixteen untested fixes/lib libs and the largest at 214 lines. Writing the tests exposed a real production bug -- `timeout 3 _run_as_user wpctl status` can never succeed, because timeout is a binary and _run_as_user is a shell function -- so this lands the fix alongside the coverage rather than testing a broken branch into permanence. The lib reaches 96.97% and stays exempt: the last four lines are pipe operators no test can reach.",
"acceptance_criteria": [
"bt_audio.sh measures 96.97% (128/132) through lib/tests/run_all.sh, twice, with the same line set both times.",
"The four uncovered lines are shown to be `} |` pipe operators rather than statements, and shown to execute, before the shortfall is accepted.",
"shfmt is shown to rewrite HEAD's one-line block form, proving the reformat that raised the denominator is unavoidable rather than something to revert.",
"The healthy branch of check_pipewire_health is actually reachable: a test asserts 'PipeWire is responsive' and passes, which was impossible before the fix.",
"meta/shell-coverage-allowlist.txt is UNCHANGED -- bt_audio.sh does not meet the 100% bar.",
"Every test file stays under the repo's 250-line cap, and pre-commit passes with no suppression added."
],
"out_of_scope": [
"Clearing bt_audio.sh or bt_adapter.sh from the allowlist. Both are capped by defect (a) in docs/kcov-under-report.md.",
"Changing continuation_lines() in meta/scripts/lib/shell_coverage_lines.py to exclude `} |` and backslash-continued assignments. It changes the denominator for every measured lib and must land on its own; measured to affect only these two libs.",
"Reverting shfmt's reformat of bt_audio.sh, which the pre-commit hook would reapply on the next commit touching the file.",
"The remaining twelve untested fixes/lib libs, none of which carry either continuation-pipe form."
],
"verifier": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh (expects all files passing, 20 + 15 + 12 for the three bt_audio files), plus bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure bt_audio.sh --min 1 --fail-on-case-error -- \"\" (expects 128/132 = 96.97%, uncovered 90 113 137 157), plus bash meta/scripts/check_shell_coverage.sh (expects exit 0, with bt_audio.sh still exempt)."
}

View File

@ -0,0 +1,50 @@
{
"intent": "Test linux_configuration/scripts/single_use/fixes/lib/arch_perf_fixes.sh, eighth of the 16 untested fixes/lib libs, and fix a third instance of the dead journal-size regex. The lib reaches 93.48% and STAYS on the allowlist: the three remaining lines are the element lines of a multi-line array literal, which bash attributes to the array's opening line.",
"scope": [
"linux_configuration/scripts/single_use/fixes/lib/arch_perf_fixes.sh (journal regex, plus three env overrides for absolute paths)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_arch_perf_fixes.sh (new, 22 assertions)",
"linux_configuration/scripts/single_use/fixes/lib/tests/arch_perf_harness.sh (three new overrides and their per-test reset)",
"meta/shell-coverage-allowlist.txt is deliberately UNCHANGED: arch_perf_fixes.sh does not meet the 100% bar",
"Non-goal: extending continuation_lines() for multi-line array literals, which lands separately"
],
"changes": [
"Fixed the journal size regex at arch_perf_fixes.sh:16, the THIRD instance of the same bug: it required a space before the unit (([0-9]+\\.?[0-9]*)\\ G) but journalctl prints '4.2G' with no separator, so the vacuum branch was dead. The space is now optional, matching the fix already made in arch_perf_report.sh.",
"Added JOURNALD_CONF_DIR, SYSTEMD_UNIT_DIR and ORGANIZE_SCRIPT_CANDIDATES overrides, all defaulting to the real paths. fix_journal writes a journald drop-in, fix_media_organizer writes /etc/systemd/system/media-organizer.service, and the organizer script is probed at two absolute home paths. run_all.sh runs UN-jailed in ci_mirror.sh and in CI, so a bind mount would protect only the coverage run.",
"Added test_arch_perf_fixes.sh covering fix_journal (multi-gigabyte journal vacuumed and capped, a small journal capped but not vacuumed, and an already-configured cap left alone), fix_nm_wait_online (enabled and already-disabled), and fix_media_organizer (script missing, unit written with the right user and ExecStart, an already-correct unit skipped, and a unit naming the wrong user rewritten)."
],
"verification": [
{
"command": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh",
"result": "pass",
"evidence": "arch_perf_fixes: 22 passed, 0 failed. All fixes lib test files passed, so the six cleared libs and the eight pacman_hook_stall suites stay green."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure arch_perf_fixes.sh --min 1 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "arch_perf_fixes.sh: 43/46 lines = 93.48%, uncovered 68, 69, 70."
},
{
"command": "PS4='+L${LINENO} ' bash -x on a minimal multi-line array literal",
"result": "pass",
"evidence": "bash reports the whole assignment at the OPENING line ('+L3 items=(\\'one\\' \\'two\\')') and never emits the element lines or the closing paren. So lines 68-70 of arch_perf_fixes.sh are data inside a multi-line array, not statements; the array is provably used, since the loop on line 71 iterates it and the media-organizer assertions pass."
},
{
"command": "ls -la /etc/systemd/system/media-organizer.service after a bare (un-jailed) run of run_all.sh",
"result": "pass",
"evidence": "Still dated 2026-07-25, a genuine artifact of a past production run, untouched by the suite. The journald drop-in likewise keeps its 2026-03-02 mtime."
},
{
"command": "Scope the artifact: grep for multi-line array literals across fixes/lib and the allowlist",
"result": "pass",
"evidence": "Three of the remaining untested libs use the form (arch_perf_fixes.sh 1, thorium_repairs.sh 4, ubuntu_perf_fixes.sh 1), and nine allowlisted libs repo-wide contain a '=(' line ending. Large enough to be worth extending continuation_lines(), which follows as its own commit."
}
],
"risks": [
"The journal regex fix makes a previously-dead vacuum live: fix_journal will now really run 'journalctl --vacuum-size=300M' when the journal exceeds a gigabyte. Unlike arch_perf_report.sh's version this one is NOT behind an --apply-safe-fixes flag; it runs whenever fix_arch_performance.sh runs. That is the function's evident intent -- it is named fix_journal and its next act is to write a permanent 300M cap -- but the behaviour change is real and worth stating.",
"arch_perf_fixes.sh stays on the allowlist at 93.48% pending the array-literal detector change."
],
"rollback": [
"git revert the commit; it adds one test file, three harness overrides, and changes one regex plus three path defaults in the lib. No allowlist entry is touched.",
"After rollback, run bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh and confirm the remaining suites pass."
]
}

View File

@ -0,0 +1,53 @@
{
"intent": "Test linux_configuration/scripts/single_use/fixes/lib/arch_perf_probes.sh to 100% line coverage and take it off the shell-coverage allowlist, sixth of the 16 untested fixes/lib libs.",
"scope": [
"linux_configuration/scripts/single_use/fixes/lib/tests/test_arch_perf_probes.sh (new, 16 assertions)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_arch_perf_probes_health.sh (new, 27 assertions)",
"linux_configuration/scripts/single_use/fixes/lib/tests/lib_test_core.sh (new _t_stub_cat helper)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_bt_pairing_usb.sh and test_bt_adapter_reset.sh (simplified onto _t_stub_cat)",
"meta/shell-coverage-allowlist.txt (one line removed)",
"Non-goal: any change to arch_perf_probes.sh itself -- unlike the two libs before it, this one had no dead branch"
],
"changes": [
"Added test_arch_perf_probes.sh covering collect_basics (a quiet machine, failed systemd units, frequent ACPI errors, a CPU-hungry Xorg, and the load-average threshold) and check_cpu_governor (all cores on performance, one core left on powersave, and no governor files at all).",
"Added test_arch_perf_probes_health.sh covering check_thermal_state (sensors present and clean, throttling messages excerpted, sensors absent), check_power_services (both daemons enabled, neither enabled, exactly one enabled), check_storage_health (healthy disk, disabled fstrim.timer, missing smartctl), and check_memory_pressure (heavy swap with RAM free, heavy swap with RAM exhausted, and a swapless machine).",
"The high-swap branch is reached by stubbing awk rather than /proc/meminfo, which the lib reads by absolute path: every meminfo read goes through awk, so the stub answers on the pattern being matched and execs the real awk for every other call. That closed lines 158-159, the only genuine test gap in the lib.",
"Added _t_stub_cat to lib_test_core.sh: the commonest stub shape is 'print this fixture file', and writing it inline forced every call site to embed a literal ${LIB_TEST_DEV} that must not expand at write time. Passing the fixture name as data removes that whole class of SC2016 with no suppression, and two earlier bluetooth test files were simplified onto it.",
"Removed linux_configuration/scripts/single_use/fixes/lib/arch_perf_probes.sh from meta/shell-coverage-allowlist.txt."
],
"verification": [
{
"command": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh",
"result": "pass",
"evidence": "arch_perf_probes (basics/governor): 16 passed; arch_perf_probes (health): 27 passed; both 0 failed. All 21 test files in the directory pass, so the five cleared libs and the eight pacman_hook_stall suites stay green after _t_stub_cat landed."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure arch_perf_probes.sh --min 1 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "arch_perf_probes.sh: 93/93 lines = 100.00%, up from 91/93 = 97.85% before the check_memory_pressure swap branch was covered. No 'outside kcov's line set' lines reported."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure arch_perf_probes.sh --min 100 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "arch_perf_probes.sh: 93/93 lines = 100.00%, exit code 0. Second matching run at the --min 100 bar."
},
{
"command": "bash meta/scripts/check_shell_coverage.sh on arch_perf_probes.sh, arch_perf_report.sh and bt_audio.sh",
"result": "pass",
"evidence": "'check_shell_coverage.sh: every checked shell library meets the coverage bar', exit 0, with the arch_perf_probes.sh allowlist line already removed so it had no exemption. The other two are included to confirm the libs cleared in c309c95f did not regress."
},
{
"command": "shellcheck on every file in fixes/lib/tests",
"result": "pass",
"evidence": "All 21 test files plus the three harnesses lint clean, with no suppression added anywhere in this commit."
}
],
"risks": [
"check_cpu_governor and collect_basics read absolute paths (/sys/devices/system/cpu via find, /proc/loadavg) that have no environment override, so those cases are driven by stubbing the command the lib shells out to (find, getconf, ps, systemctl, journalctl). The load-average case additionally self-skips with an explicit note if this host's 1-minute load happens to sit below 1, so it cannot silently start asserting nothing.",
"The awk stub used for the swap cases execs /usr/bin/awk for any pattern it does not recognise. If the lib later reads a new /proc/meminfo field, the stub will fall through to the real awk and the fabricated figures will silently stop applying to that field rather than failing loudly."
],
"rollback": [
"git revert the commit; that restores the arch_perf_probes.sh allowlist line and deletes the two test files together.",
"After rollback, run bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh and confirm the remaining suites pass, then bash meta/scripts/check_shell_coverage.sh to confirm the gate is green with arch_perf_probes.sh exempt again."
]
}

View File

@ -0,0 +1,55 @@
{
"intent": "Test linux_configuration/scripts/single_use/fixes/lib/arch_perf_report.sh, fifth of the 16 untested fixes/lib libs and the first of the arch-performance group, and fix a second production bug the tests exposed: the journal size check could never fire. The lib reaches 98.33% and STAYS on the allowlist, capped by one closing-brace line.",
"scope": [
"linux_configuration/scripts/single_use/fixes/lib/arch_perf_report.sh (two regexes: the journal size match)",
"linux_configuration/scripts/single_use/fixes/lib/tests/arch_perf_harness.sh (new family harness)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_arch_perf_report.sh (new, 17 assertions)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_arch_perf_report_fixes.sh (new, 21 assertions)",
"linux_configuration/scripts/single_use/fixes/lib/tests/lib_test_core.sh and bt_harness.sh (_t_hide/_t_full_path moved into the core)",
"meta/shell-coverage-allowlist.txt is deliberately UNCHANGED: arch_perf_report.sh does not meet the 100% bar"
],
"changes": [
"Fixed the journal size regexes in arch_perf_report.sh, lines 36 and 65. Both required a SPACE before the unit -- ([0-9]+\\.?[0-9]*)\\ (G|M) -- but journalctl prints 'Archived and active journals take up 305.5M in the file system.' with no separator, verified on this machine. check_journal_size could therefore never report a large journal, and apply_safe_fixes could never vacuum one: both were dead code. The space is now optional (\\ ?), and tests cover the spaced and unspaced forms.",
"Added arch_perf_harness.sh: sources lib_test_core.sh and the real scripts/lib/common.sh, points REPORT_FILE into the throwaway tmpdir, and redefines add_finding, add_action and run_and_log verbatim from diagnose_arch_performance.sh, which owns them rather than any lib.",
"Added test_arch_perf_report.sh covering check_gpu_state (nvidia-smi absent, an idle GPU pinned in P0, a busy P0 GPU that must NOT be flagged, an idle GPU in a low-power state, and nvidia-smi returning nothing) and check_journal_size (gigabyte, megabyte, space-separated, and journalctl failing).",
"Added test_arch_perf_report_fixes.sh covering apply_safe_fixes (disabled by the flag, nothing to do, enabling a disabled fstrim.timer, disabling a conflicting tlp.service, and vacuuming a multi-gigabyte journal) and print_summary (clean run, findings listed and counted, actions section).",
"Moved _t_hide and _t_full_path from bt_harness.sh into lib_test_core.sh. They are generic PATH plumbing, not bluetooth-specific, and the arch harness needs them for the 'nvidia-smi is not installed' branch.",
"apply_safe_fixes is called directly rather than inside a command substitution: it appends to the ACTIONS array, and a substitution runs it in a subshell where those appends die with it, leaving the assertions reading an empty array."
],
"verification": [
{
"command": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh",
"result": "pass",
"evidence": "arch_perf_report (probes): 17 passed; arch_perf_report (fixes/summary): 21 passed; both 0 failed. All fixes lib test files passed, so the four bluetooth libs and the eight pacman_hook_stall suites stay green after _t_hide moved into the core."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure arch_perf_report.sh --min 1 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "arch_perf_report.sh: 59/60 lines = 98.33%, uncovered: 20. Run twice with the identical line set."
},
{
"command": "bash -c 'line=\"...take up 4.2G in the file system.\"; [[ $line =~ ([0-9]+\\.?[0-9]*)\\ (G|M) ]]'",
"result": "pass",
"evidence": "Reproduced the bug before fixing: NO MATCH against the old regex, so no journal size could ever be flagged. With the optional space the same line matches and yields 4.2G. journalctl on this host prints '305.5M' with no space, confirming the real format the old regex excluded."
},
{
"command": "Read uncovered line 20 and probe it minimally",
"result": "pass",
"evidence": "Line 20 is '} >>\"$REPORT_FILE\"', the closing brace of a redirected group. A minimal probe ({ echo a; echo b; } >>file inside a function) writes both lines to the file while bash attributes no statement to the closing brace. The report assertions independently prove the group runs, since they read the very text it writes. Same defect (a) class as bt_audio's '} |' lines."
},
{
"command": "grep -lE '^[[:space:]]*\\}[[:space:]]*>' over all 22 fixes/lib libs",
"result": "pass",
"evidence": "The redirected-closing-brace form appears in arch_perf_report.sh, arch_perf_probes.sh and nvidia_config.sh. Together with bt_audio.sh's '} |' that is four libs capped by one detector gap, which is why the continuation_lines() fix is now worth landing as its own commit."
}
],
"risks": [
"The journal regex fix makes a previously-dead DESTRUCTIVE action live. apply_safe_fixes will now actually run 'journalctl --vacuum-size=300M' when the entry script is invoked with --apply-safe-fixes and the journal exceeds a gigabyte, deleting roughly 3.9G of logs on a 4.2G journal. That is the documented intent of the flag, and the vacuum still only runs behind it, but it has never actually executed before this commit.",
"arch_perf_report.sh stays on the allowlist at 98.33%, capped by line 20. Clearing it needs continuation_lines() in meta/scripts/lib/shell_coverage_lines.py to exclude a closing brace followed by a redirection or pipe, which lands separately so a regression can be reverted without losing these tests.",
"The GPU tests stub nvidia-smi rather than reading the real card, so they assert on the lib's parsing of a known nvidia-smi contract, not on this host's actual GPU state."
],
"rollback": [
"git revert the commit; it adds a harness and two test files, moves two helpers between harness files, and changes two regexes in one lib. No allowlist entry is touched.",
"After rollback, run bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh and confirm the remaining suites pass; the coverage gate is unaffected since arch_perf_report.sh stays exempt either way."
]
}

View File

@ -0,0 +1,56 @@
{
"intent": "Teach continuation_lines() that the element lines and closing paren of a multi-line array literal are not statements. This is defect (a) in docs/kcov-under-report.md, in the fourth flavour found this session, and it caps arch_perf_fixes.sh plus at least two of the libs still to be tested.",
"scope": [
"meta/scripts/lib/shell_coverage_lines.py (one regex, one helper, and array state in the main loop)",
"python_pkg/tests/test_shell_coverage_lines.py (four new cases: one positive, three negative)",
"Non-goal: the backslash-continued ASSIGNMENT flavour that caps bt_adapter.sh line 97, still deferred",
"meta/shell-coverage-allowlist.txt (arch_perf_fixes.sh removed, since the fix takes it to 100%)"
],
"changes": [
"Added _ARRAY_OPEN, matching an assignment whose value opens a multi-line array literal -- `local -a c=(`, `declare -A m=(`, `FILES=(`, `x+=(` -- with nothing but an optional comment after the paren. While open, every line is excluded until a `)` that is not itself inside quotes.",
"Added _closes_array(), which finds that closing paren by recomputing quote state from the start of the line for each candidate, so an element like \"a(b)\" does not end the literal early.",
"The rule is symmetric with the existing multi-line-quote case: bash reports the WHOLE assignment at its OPENING line, so that line stays a statement and everything up to the closing paren is data.",
"Added four tests: a multi-line array marks its elements and closing paren; a single-line `x=(a b)` does NOT; an element containing a parenthesis does not close the literal early; and `x=$(echo hi)` is a command substitution rather than an array literal.",
"Removed linux_configuration/scripts/single_use/fixes/lib/arch_perf_fixes.sh from meta/shell-coverage-allowlist.txt: the fix takes it to 100.00%, so it now meets the bar."
],
"verification": [
{
"command": "PS4='+L${LINENO} ' bash -x on a minimal multi-line array literal",
"result": "pass",
"evidence": "bash prints '+L3 items=(\\'one\\' \\'two\\')' for an array opened on line 3 and closed on line 6, and never emits lines 4, 5 or 6. The elements and closing paren are data; only the opening line is a statement."
},
{
"command": "python3 -m coverage run --branch --source=meta/scripts/lib -m pytest python_pkg/tests/test_shell_coverage_lines.py",
"result": "pass",
"evidence": "22 passed. shell_coverage_lines.py: 71 statements, 48 branches, 0 missed, 0 partial = 100%, so both arms of every new branch are covered as the repo's fail_under=100 branch gate requires."
},
{
"command": "Diff old vs new predicate over every allowlisted lib plus the six already cleared, printing each newly excluded line WITH its text",
"result": "pass",
"evidence": "91 newly excluded lines across 10 libs, and every one is an array element or a closing paren: common.sh's tool tables, packages.sh's associative arrays, arch_sysctl.sh's sysctl key/value maps, thorium_repairs.sh's four path lists, ubuntu_perf_fixes.sh's sssd unit list, clean_audio_filters.sh's model search paths, trace_prefix.sh, trace_stubs.sh and arch_perf_fixes.sh's candidate list. No ordinary statement was caught -- the fail-open direction this module's test header warns about."
},
{
"command": "Re-measure seven libs through fixes/lib/tests/run_all.sh after the change",
"result": "pass",
"evidence": "arch_perf_fixes.sh 93.48% -> 100.00% (43/43). bt_audio.sh 127/127, arch_perf_report.sh 59/59, arch_perf_probes.sh 93/93, ubuntu_perf_more.sh 32/32, bt_report.sh 37/37 and bt_pairing.sh 65/65 all unchanged at 100.00%. One gained, six held, none went DOWN."
},
{
"command": "The handoff's acceptance test: dot_resolver_install.sh and rpi_nc_ca.sh through features/lib/tests/run_all.sh with its jail_args",
"result": "pass",
"evidence": "dot_resolver_install.sh: 39/39 = 100.00% and rpi_nc_ca.sh: 73/73 = 100.00%, exactly the figures the handoff names as the instrument's acceptance criteria."
},
{
"command": "bash meta/scripts/check_shell_coverage.sh linux_configuration/scripts/single_use/fixes/lib/arch_perf_fixes.sh",
"result": "pass",
"evidence": "'check_shell_coverage.sh: every checked shell library meets the coverage bar', exit 0, with the allowlist line already removed so the lib had no exemption."
}
],
"risks": [
"This is the second denominator change of the session, so the same arithmetic bound applies: _measure computes covered_set = (executed|traced) & denominator, so a lib already at 100.00% cannot regress from excluding more lines. The six cleared libs were re-measured anyway and all held.",
"_ARRAY_OPEN deliberately requires the line to END at the open paren. `x=(a` followed by more elements on later lines would not match, and neither would a `for x in (` construct, which is not valid bash anyway. Narrower than necessary is the safe direction here, since over-detection inflates coverage."
],
"rollback": [
"git revert the commit; continuation_lines() loses array tracking and the four new tests go with it.",
"After rollback, re-measure arch_perf_fixes.sh and expect it back at 93.48%. It is not on the cleared list at that point, so no gate breaks -- but if the follow-up clearing commit has landed, revert that too."
]
}

View File

@ -0,0 +1,47 @@
{
"intent": "Test linux_configuration/scripts/single_use/fixes/lib/bt_adapter.sh, third of the 16 untested fixes/lib libs. It reaches 98.55% and STAYS on the allowlist: the one remaining line is not reachable by any test, for an instrument reason recorded below.",
"scope": [
"linux_configuration/scripts/single_use/fixes/lib/tests/test_bt_adapter.sh (new, 14 assertions: check_firmware and _download_firmware)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_bt_adapter_reset.sh (new, 27 assertions: check_adapter_stuck, _reload_btusb, _services_resolved, _full_adapter_reset_and_connect, _verify_audio_sink)",
"linux_configuration/scripts/single_use/fixes/lib/tests/bt_harness.sh (_t_only_path replaced by _t_hide)",
"Non-goal: removing bt_adapter.sh from meta/shell-coverage-allowlist.txt -- it is at 98.55%, not 100%, so it does not meet the bar",
"Non-goal: fixing the continuation-line detector, or reformatting bt_adapter.sh to suit the tool"
],
"changes": [
"Added test_bt_adapter.sh covering check_firmware (no .hcd named in dmesg, a missing file that triggers the download, an already-installed file, and de-duplication of repeated names via sort -u) and _download_firmware (wget succeeding, and the curl fallback when wget fails).",
"Added test_bt_adapter_reset.sh covering check_adapter_stuck (responsive adapter, no USB dongle, the usbreset path, the btusb-reload fallback when usbreset is absent, and an unparseable USB ID), _reload_btusb, _services_resolved (boolean true, boolean false, and dbus-send failing), _full_adapter_reset_and_connect, and _verify_audio_sink (pactl absent, card found on the first probe, and never found after five retries).",
"Replaced the harness's _t_only_path with _t_hide, which rebuilds PATH from symlinks to every real executable EXCEPT the named ones. _t_only_path dropped PATH to $FAKE_BIN alone, which also hid grep, head and sort -- so a 'usbreset not installed' case died in a cascade of 'command not found' and passed for the wrong reason rather than exercising the fallback. Verified directly: after _t_hide usbreset, command -v usbreset is empty while grep and head still resolve.",
"test_bt_adapter_reset.sh sources bt_audio.sh as well: bt_adapter.sh calls _run_as_user and _restart_pipewire_stack, which live in bt_audio.sh, and fix_bluetooth.sh sources both. Sourcing it reproduces the real resolution order instead of stubbing the two helpers.",
"sleep is stubbed for _full_adapter_reset_and_connect (34 real seconds) and _verify_audio_sink (5 retries x 3s), with the calls still recorded so the retry-count assertion is on the real loop."
],
"verification": [
{
"command": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh",
"result": "pass",
"evidence": "bt_adapter (firmware): 14 passed, 0 failed; bt_adapter (reset/probe): 27 passed, 0 failed. All fixes lib test files passed, so bt_report, both bt_pairing files and the eight pacman_hook_stall suites stay green."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure bt_adapter.sh --min 1 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "bt_adapter.sh: 68/69 lines = 98.55%, up from 45/69 = 65.22% before _full_adapter_reset_and_connect and _verify_audio_sink were covered. Only line 97 remains uncovered."
},
{
"command": "PS4='+TRACE:${BASH_SOURCE##*/}:${LINENO} ' bash -x, driving _services_resolved directly",
"result": "pass",
"evidence": "bash attributes the whole multi-line dbus-send assignment to line 100 ('+TRACE:bt_adapter.sh:100 result=...'), and never emits line 97 at all. Line 97 is the OPENING line of a backslash-continued statement: kcov instruments it, bash never attributes a statement to it, so no test can cover it. This is defect (a) in docs/kcov-under-report.md -- a wrong denominator, not a missing test."
},
{
"command": "grep -c '\\\\$' on each of the 22 fixes/lib libs",
"result": "pass",
"evidence": "Backslash continuations are confined to the bluetooth family: bt_audio.sh 10, bt_adapter.sh 7, bt_pairing.sh 3, pacman_hook_stall_summary.sh 2, and ZERO in the other 12 remaining libs. So this artifact caps bt_adapter.sh and will cap bt_audio.sh, but does not block the rest of the campaign."
}
],
"risks": [
"bt_adapter.sh stays on the allowlist at 98.55%. Clearing it needs meta/scripts/lib/shell_coverage_lines.py:continuation_lines to also treat a line ending in an unquoted backslash as a continuation -- it currently tracks quote state only. That change alters the denominator for every measured lib, so it is deliberately NOT bundled here: if it regresses one of the five pacman_hook_stall libs that are already gated with no exemption, reverting a mixed commit would throw away these tests too.",
"Two check_firmware cases read the real /usr/lib/firmware/brcm (the lib hardcodes that path). The already-installed case is driven by whatever .hcd is genuinely present and self-skips with a note if the directory is empty; the download case uses BCM99999-nonexistent.hcd, a name no distribution ships. An earlier draft used BCM20702A1-0b05-17cb.hcd, which IS installed on this host, and silently exercised the wrong branch -- caught by the assertion, not by inspection."
],
"rollback": [
"git revert the commit; it adds two test files and changes one harness helper, and touches no production lib and no allowlist entry.",
"After rollback, run bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh and confirm the remaining suites pass; no coverage gate changes, since bt_adapter.sh stays exempt either way."
]
}

View File

@ -0,0 +1,67 @@
{
"intent": "Test linux_configuration/scripts/single_use/fixes/lib/bt_audio.sh, fourth of the 16 untested fixes/lib libs, and fix a production bug the tests exposed: check_pipewire_health could never see a healthy PipeWire. The lib reaches 96.97% and STAYS on the allowlist -- the four remaining lines are unreachable by construction, for the instrument reason recorded below.",
"scope": [
"linux_configuration/scripts/single_use/fixes/lib/bt_audio.sh (one-line behaviour fix at the timeout call)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_bt_audio.sh (new, 20 assertions)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_bt_audio_connect.sh (new, 15 assertions)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_bt_audio_health.sh (new, 12 assertions)",
"linux_configuration/scripts/single_use/fixes/lib/tests/lib_test_core.sh (new _t_stub_stdin helper)",
"Non-goal: the remaining twelve untested fixes/lib libs",
"meta/shell-coverage-allowlist.txt is deliberately UNCHANGED: bt_audio.sh does not meet the 100% bar"
],
"changes": [
"Fixed lib/bt_audio.sh:21. It read `if timeout 3 _run_as_user wpctl status`, but `timeout` is a binary and cannot invoke a shell function, so the call always failed with rc=127 ('timeout: failed to run command _run_as_user'). check_pipewire_health therefore reported PipeWire hung on EVERY run and restarted a healthy audio stack every time. Now `_run_as_user timeout 3 wpctl status`, which keeps the 3-second bound but puts it inside the sudo'd command where it can actually run. Confirmed _run_as_user is never exported, so no caller relied on the old shape.",
"Added test_bt_audio.sh covering check_pipewire_health (wpctl absent, responsive, and hung), _run_as_user (SUDO_USER set and the USER fallback), _restart_pipewire_stack, and set_audio_profile (empty TARGET_MAC, pactl absent, no matching card, the SBC-XQ switch, and a healthy profile left alone).",
"Added test_bt_audio_connect.sh covering connect_device: empty TARGET_MAC, already connected, paired with a successful direct connect, a failed direct connect that falls through to scan-and-fail, a full scan/pair/trust/connect for an unpaired device, and a device found by the scan whose connection never becomes healthy.",
"Added test_bt_audio_health.sh covering _check_connection_health: not connected, services resolved on the first probe, services resolving only after the full adapter reset (driven by a counting dbus-send stub), and services that never resolve at all.",
"Added _t_stub_stdin to lib_test_core.sh. Stub bodies are data containing $1 and ${VAR} that must survive verbatim, and writing them as single-quoted strings tripped SC2016 on every use; reading the body from stdin via a quoted heredoc keeps it literal with no suppression.",
"Made the bluetoothctl stubs drain their stdin (`cat >/dev/null`) before exiting. The real tool consumes its whole input; a stub that read one line and exited closed the pipe early, so the writing `{ ...; } |` block took SIGPIPE partway through and its later lines never ran. That alone was worth 90.91% -> 96.97%."
],
"verification": [
{
"command": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh",
"result": "pass",
"evidence": "bt_audio (pipewire): 20 passed; bt_audio (connect): 15 passed; bt_audio (health): 12 passed; all 0 failed. All fixes lib test files passed, so bt_report, bt_pairing, bt_adapter and the eight pacman_hook_stall suites stay green."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure bt_audio.sh --min 1 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "bt_audio.sh: 128/132 lines = 96.97%, uncovered 90, 113, 137, 157."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure bt_audio.sh --min 1 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "bt_audio.sh: 128/132 lines = 96.97%, identical to the first run. Two matching runs, so the figure is not timing-dependent."
},
{
"command": "Read the uncovered lines before deciding whether the lib could be cleared",
"result": "pass",
"evidence": "Lines 90, 113, 137 and 157 are each the `} |` that closes a piped block -- the pipe OPERATOR joining the block to `bluetoothctl`, not a statement. Proven executable with a marker file: a `{ echo a; echo b; } | consumer` block writes every marker even though bash's xtrace never reports the left-hand side, because a pipe's LHS runs in a subshell whose xtrace is not captured. So the lines run; kcov cannot attribute them."
},
{
"command": "bash -c 'timeout 3 _run_as_user wpctl status'",
"result": "pass",
"evidence": "Reproduced the bug directly before fixing: \"timeout: failed to run command '_run_as_user': No such file or directory\", rc=127. After the fix the healthy branch is reachable and its test ('PipeWire is responsive') passes."
},
{
"command": "shfmt -w on HEAD's bt_audio.sh, then diff against HEAD",
"result": "pass",
"evidence": "shfmt REWRITES HEAD's `{ ...; } \\` + `| bluetoothctl` one-liners into multi-line blocks ending in `} |`. The pre-commit hook runs `shfmt -w` on every staged shell file, so this reformat is unavoidable on any commit touching the file and reverting it is not stable. That is why 96.97% is accepted rather than restored to the pre-format 100%."
},
{
"command": "grep -lnE '^[[:space:]]*\\|' and grep -lE '\\}[[:space:]]*\\|[[:space:]]*$' over all 22 fixes/lib libs",
"result": "pass",
"evidence": "The continuation-pipe form is confined to the bluetooth family: bt_adapter.sh carries the pre-format flavour and bt_audio.sh the post-shfmt one. None of the remaining twelve untested libs has either, so this artifact does not block the rest of the campaign."
}
],
"risks": [
"bt_audio.sh stays on the allowlist at 96.97%. The four uncovered lines are `} |` pipe operators that kcov instruments but bash never attributes a statement to -- the same defect (a) class as bt_adapter.sh line 97, in a third flavour. Clearing either lib needs meta/scripts/lib/shell_coverage_lines.py to exclude these forms, which changes the denominator for every measured lib and must land on its own.",
"An earlier measurement of this lib read 99/99 = 100.00%. That number measured the file BEFORE pre-commit's shfmt reformatted it, and is superseded by 128/132 = 96.97% here. The reformat raised the denominator from 99 to 132 by splitting six one-line blocks into their constituent statements.",
"The bt_audio.sh fix changes runtime behaviour: fix_bluetooth.sh will now SKIP the PipeWire/WirePlumber restart when wpctl answers within 3 seconds, where before it restarted the audio stack on every run. That is the intended behaviour of the function as written.",
"bt_audio.sh is now exactly 250 lines, i.e. AT the repo cap. The next edit to it must split the file; a comment trim will not buy room twice."
],
"rollback": [
"git revert the commit; it adds three test files, one core helper and a one-line behaviour fix, and touches no allowlist entry.",
"After rollback, run bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh and confirm the remaining suites pass. No coverage gate changes, since bt_audio.sh stays exempt either way."
]
}

View File

@ -0,0 +1,43 @@
{
"intent": "Take bt_audio.sh and arch_perf_report.sh off the shell-coverage allowlist. Both were already tested to their reachable ceiling; the closing-brace fix in d989cd7e removed the instrument artifact that was holding them below 100%, so they now meet the bar with no exemption.",
"scope": [
"meta/shell-coverage-allowlist.txt (two lines removed)",
"Non-goal: any test or lib change -- the tests landed in a5b6663c and ffcf99f1, the instrument fix in d989cd7e, and this commit only records the consequence",
"Non-goal: bt_adapter.sh, still exempt at 98.55% for the backslash-continued assignment flavour"
],
"changes": [
"Removed linux_configuration/scripts/single_use/fixes/lib/bt_audio.sh from meta/shell-coverage-allowlist.txt.",
"Removed linux_configuration/scripts/single_use/fixes/lib/arch_perf_report.sh from meta/shell-coverage-allowlist.txt.",
"Confirmed the diff removes exactly those two lines and nothing else."
],
"verification": [
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure bt_audio.sh --min 100 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "bt_audio.sh: 127/127 lines = 100.00%, exit code 0. Measured at the --min 100 bar so a shortfall would be a non-zero exit rather than a number to misread."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure arch_perf_report.sh --min 100 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "arch_perf_report.sh: 59/59 lines = 100.00%, exit code 0."
},
{
"command": "bash meta/scripts/check_shell_coverage.sh on bt_audio.sh, arch_perf_report.sh, bt_report.sh and bt_pairing.sh",
"result": "pass",
"evidence": "'check_shell_coverage.sh: every checked shell library meets the coverage bar', exit 0, run with both allowlist lines already removed so neither lib had an exemption. bt_report.sh and bt_pairing.sh are included to confirm the two libs cleared earlier in the session did not regress."
},
{
"command": "git diff meta/shell-coverage-allowlist.txt",
"result": "pass",
"evidence": "Exactly two removed lines, both the intended ones, and no additions. The allowlist drops from 95 to 93 fixes/lib-relevant entries."
}
],
"risks": [
"Both libs are now gated at 100% with no exemption, so any future change to them, to their tests, or to continuation_lines() that lowers their coverage will fail the commit. That is the point of clearing them, but it means the closing-brace exclusion is now load-bearing: reverting d989cd7e without also restoring these two allowlist lines would turn every subsequent commit red.",
"The measurements were made in a detached worktree under the scratchpad, because the jail aborts on any working-tree delta during a run. The libs and tests were byte-identical to the commits named above."
],
"rollback": [
"git revert the commit; that restores both allowlist lines and returns the two libs to exempt status.",
"After rollback, run bash meta/scripts/check_shell_coverage.sh on both libs and confirm it exits 0 with them exempt."
]
}

View File

@ -0,0 +1,44 @@
{
"intent": "Teach continuation_lines() that a line holding only a group's closing brace plus an operator (`} |`, `} >>file`) is not a statement, so kcov stops inflating the denominator with it. This is defect (a) in docs/kcov-under-report.md, in the flavour that caps four fixes/lib libs.",
"scope": [
"meta/scripts/lib/shell_coverage_lines.py (one regex and one branch)",
"python_pkg/tests/test_shell_coverage_lines.py (four new cases: two positive, two negative)",
"Non-goal: the backslash-continued ASSIGNMENT flavour that caps bt_adapter.sh line 97 -- it needs a command-vs-assignment distinction and is one line in one lib",
"Non-goal: clearing any lib from meta/shell-coverage-allowlist.txt, which follows in its own commit once each is re-measured"
],
"changes": [
"Added _CLOSING_BRACE_OP = ^\\s*\\}\\s*(\\||>>?|<|&>) and one branch in continuation_lines() that excludes matching lines when no quote is open.",
"Anchoring on a LEADING closing brace is what makes this safe. bash attributes each command inside a group to its own line, and a pipe's right-hand side to its own line, so the brace-plus-operator line is left with no statement. A one-liner `{ echo a; } >file` starts with `{` and does not match; a bare `}` closing a function carries no operator and does not match.",
"Added four tests: `} |` and `} >>\"$REPORT_FILE\"` are continuations; a bare `}` closing a function and a single-line `{ echo a; } >\"$out\"` are NOT. The negative pair is the important half, because over-detection shrinks the denominator and INFLATES coverage -- the fail-open direction this test module's own header calls out."
],
"verification": [
{
"command": "python3 -m coverage run --branch --source=meta/scripts/lib -m pytest python_pkg/tests/test_shell_coverage_lines.py",
"result": "pass",
"evidence": "18 passed. shell_coverage_lines.py: 56 statements, 40 branches, 0 missed, 0 partial = 100% -- so the new branch is covered in both directions, as the repo's fail_under=100 branch gate requires."
},
{
"command": "Audit every line the new predicate newly excludes across the whole allowlist plus the cleared libs",
"result": "pass",
"evidence": "17 lines excluded across 10 libs, and every one re-matched the brace-plus-operator shape when printed with its text: integrity.sh:68/118, aw_autostart.sh:65, rpi_nc_ssl.sh:88, wg_sshd.sh:66, arch_perf_probes.sh:46/93, arch_perf_report.sh:20, bt_audio.sh:90/113/137/145/157, nvidia_config.sh:68, trace_prefix.sh:100, trace_stubs.sh:69, adb_trusted.sh:29. No ordinary statement was caught."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject .../fixes/lib/tests/run_all.sh --measure <lib> --min 1 --fail-on-case-error -- \"\", for five libs",
"result": "pass",
"evidence": "bt_audio.sh 96.97% -> 100.00% (127/127), arch_perf_report.sh 98.33% -> 100.00% (59/59), bt_report.sh 100.00% (37/37) unchanged, bt_pairing.sh 100.00% (65/65) unchanged, bt_adapter.sh 98.55% (68/69) unchanged. Two libs gained, three held, none went DOWN -- the handoff's stated regression signal."
},
{
"command": "The handoff's acceptance test: dot_resolver_install.sh and rpi_nc_ca.sh through features/lib/tests/run_all.sh with its jail_args",
"result": "pass",
"evidence": "dot_resolver_install.sh: 39/39 = 100.00% and rpi_nc_ca.sh: 73/73 = 100.00%, exactly the figures the handoff names as the instrument's acceptance criteria."
}
],
"risks": [
"A denominator change touches every measured lib, which is why it lands alone. The arithmetic bounds the blast radius: _measure computes denominator = kcov's line set minus excluded, and covered_set = (executed | traced) & denominator, so for any lib already at 100.00% the covered set IS the denominator and removing a subset leaves it at 100.00%. The five gated pacman_hook_stall libs, bt_report and bt_pairing therefore cannot regress, which the measurements above confirm for the two that were re-run.",
"The predicate is deliberately narrow. It does not cover `} &&`, `} ||` or a closing brace followed by a comment, and it does not touch the backslash-continued assignment flavour. Each would need its own evidence that bash attributes no statement to the line."
],
"rollback": [
"git revert the commit; continuation_lines() returns to quote-state detection only and the four new tests go with it.",
"After rollback, re-measure bt_audio.sh and arch_perf_report.sh and expect them back at 96.97% and 98.33%; neither is on the allowlist-cleared list, so no gate breaks."
]
}

View File

@ -0,0 +1,51 @@
{
"intent": "Test linux_configuration/scripts/single_use/fixes/lib/ubuntu_perf_more.sh to 100% line coverage and take it off the shell-coverage allowlist, seventh of the 16 untested fixes/lib libs and the first of the ubuntu-performance pair.",
"scope": [
"linux_configuration/scripts/single_use/fixes/lib/ubuntu_perf_more.sh (two env overrides for its absolute write/read targets)",
"linux_configuration/scripts/single_use/fixes/lib/tests/ubuntu_perf_harness.sh (new family harness)",
"linux_configuration/scripts/single_use/fixes/lib/tests/test_ubuntu_perf_more.sh (new, 24 assertions)",
"meta/shell-coverage-allowlist.txt (one line removed)",
"Non-goal: ubuntu_perf_fixes.sh, the 215-line other half of this family"
],
"changes": [
"Added JOURNALD_CONF_DIR and UNDO_DIR overrides to ubuntu_perf_more.sh, defaulting to /etc/systemd/journald.conf.d and /root respectively. fix_journal writes a journald drop-in and run_undo globs /root for undo scripts; both are absolute, and lib/tests/run_all.sh runs UN-jailed in ci_mirror.sh and in CI, so a bind mount would have protected only the coverage run. Same env-override seam bt_pairing.sh uses for UDEV_RULES_DIR.",
"Added ubuntu_perf_harness.sh: sources lib_test_core.sh and the real scripts/lib/common.sh, points UNDO_SCRIPT at the tmpdir, and redefines add_undo verbatim from fix_ubuntu_performance.sh, which owns it rather than any lib.",
"Added test_ubuntu_perf_more.sh covering fix_journal (first run writing the cap, an already-configured drop-in that must be skipped, and a drop-in capping a DIFFERENT size that must be rewritten), fix_snap_startup (timer enabled and already disabled), and run_undo (no script present, a script that runs, and several scripts where the most recent must win).",
"run_undo ends in `exit`, so each of its cases runs inside an explicit subshell: a command substitution already provides one, so the exit ends only that subshell rather than the whole test file."
],
"verification": [
{
"command": "bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh",
"result": "pass",
"evidence": "ubuntu_perf_more: 24 passed, 0 failed. All fixes lib test files passed, so the six libs cleared so far and the eight pacman_hook_stall suites stay green."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure ubuntu_perf_more.sh --min 1 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "ubuntu_perf_more.sh: 32/32 lines = 100.00% on the first measurement. No 'outside kcov's line set' lines reported."
},
{
"command": "bash meta/scripts/shell_coverage_jail.sh --subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh --measure ubuntu_perf_more.sh --min 100 --fail-on-case-error -- \"\"",
"result": "pass",
"evidence": "ubuntu_perf_more.sh: 32/32 lines = 100.00%, exit code 0. Second matching run at the --min 100 bar."
},
{
"command": "bash meta/scripts/check_shell_coverage.sh linux_configuration/scripts/single_use/fixes/lib/ubuntu_perf_more.sh",
"result": "pass",
"evidence": "'check_shell_coverage.sh: every checked shell library meets the coverage bar', exit 0, with the allowlist line already removed so the lib had no exemption."
},
{
"command": "ls -la /etc/systemd/journald.conf.d/ after a bare (un-jailed) run of run_all.sh",
"result": "pass",
"evidence": "size-limit.conf still dated 2026-03-02, i.e. a genuine artifact of a past production run, untouched by the suite. No undo_ubuntu_performance_*.sh exists in /root. This is the check that proves the suite is safe where it actually runs un-jailed; the jail cannot give it."
}
],
"risks": [
"fix_journal restarts systemd-journald and run_undo executes an arbitrary shell script. Both are exercised only through stubs and a tmpdir: systemctl is stubbed by the harness, and the undo script the test runs is one the test wrote into UNDO_DIR. Nothing in this suite can restart a real service or run a real /root script.",
"The two new overrides mean a future caller could redirect a production journald drop-in by exporting JOURNALD_CONF_DIR. That matches the existing UDEV_RULES_DIR precedent in bt_pairing.sh, and the defaults are unchanged, so the entry script's behaviour is identical."
],
"rollback": [
"git revert the commit; that restores the ubuntu_perf_more.sh allowlist line, removes the two overrides and deletes the harness and test file together.",
"After rollback, run bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh and confirm the remaining suites pass, then bash meta/scripts/check_shell_coverage.sh to confirm the gate is green with ubuntu_perf_more.sh exempt again."
]
}

View File

@ -13,7 +13,9 @@ fix_journal() {
usage_line=$(journalctl --disk-usage 2>/dev/null || true)
local needs_vacuum=false
if [[ $usage_line =~ ([0-9]+\.?[0-9]*)\ G ]]; then
# Optional space before the unit: journalctl prints "305.5M in the file
# system", with no separator, so requiring one made this dead code.
if [[ $usage_line =~ ([0-9]+\.?[0-9]*)\ ?G ]]; then
needs_vacuum=true
fi
@ -24,7 +26,7 @@ fix_journal() {
fi
# Create permanent size cap via drop-in
local dropin_dir="/etc/systemd/journald.conf.d"
local dropin_dir="${JOURNALD_CONF_DIR:-/etc/systemd/journald.conf.d}"
local dropin_file="$dropin_dir/size-limit.conf"
if [[ -f $dropin_file ]] && grep -q 'SystemMaxUse=300M' "$dropin_file"; then
@ -58,12 +60,12 @@ fix_nm_wait_online() {
# Fix 5: media-organizer.service
# ===================================================================
fix_media_organizer() {
local service_file="/etc/systemd/system/media-organizer.service"
local service_file="${SYSTEMD_UNIT_DIR:-/etc/systemd/system}/media-organizer.service"
# Find the organize_downloads.sh script
local script_path=""
local candidates=(
"/home/kuhy/testsAndMisc/linux_configuration/scripts/utils/organize_downloads.sh"
"${ORGANIZE_SCRIPT_CANDIDATES:-/home/kuhy/testsAndMisc/linux_configuration/scripts/utils/organize_downloads.sh}"
"/home/kuhy/linux-configuration/scripts/utils/organize_downloads.sh"
)
for candidate in "${candidates[@]}"; do

View File

@ -33,7 +33,10 @@ check_journal_size() {
journal_line=$(journalctl --disk-usage 2>/dev/null || true)
echo "Journal usage: ${journal_line:-unknown}" >>"$REPORT_FILE"
if [[ $journal_line =~ ([0-9]+\.?[0-9]*)\ (G|M) ]]; then
# The space before the unit is OPTIONAL: journalctl prints "305.5M in
# the file system", with no separator, so requiring one made this check
# dead code that could never report a large journal.
if [[ $journal_line =~ ([0-9]+\.?[0-9]*)\ ?(G|M) ]]; then
local value unit
value="${BASH_REMATCH[1]}"
unit="${BASH_REMATCH[2]}"
@ -62,7 +65,8 @@ apply_safe_fixes() {
local journal_line
journal_line=$(journalctl --disk-usage 2>/dev/null || true)
if [[ $journal_line =~ ([0-9]+\.?[0-9]*)\ G ]]; then
# Optional space, as in check_journal_size above.
if [[ $journal_line =~ ([0-9]+\.?[0-9]*)\ ?G ]]; then
journalctl --vacuum-size=300M
add_action "Vacuumed systemd journal to 300M."
fi

View File

@ -17,8 +17,10 @@ check_pipewire_health() {
return 0
fi
# Test if PipeWire is responding within 3 seconds
if timeout 3 _run_as_user wpctl status &>/dev/null; then
# Timeout goes INSIDE _run_as_user: `timeout` is a binary and cannot
# invoke a shell function, so wrapping it outside always returned 127
# and reported a healthy PipeWire as hung.
if _run_as_user timeout 3 wpctl status &>/dev/null; then
log_ok "PipeWire is responsive."
return 0
fi
@ -77,8 +79,16 @@ connect_device() {
# ---- Attempt 1: direct connect (existing pairing) ----
if echo "$info" | grep -q "Paired: yes"; then
log_info "Device is already paired. Trying direct connect..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "connect $TARGET_MAC"; sleep 15; } \
| bluetoothctl 2>/dev/null || true
{
echo "agent on"
echo "default-agent"
sleep 1
echo "power on"
sleep 1
echo "connect $TARGET_MAC"
sleep 15
} |
bluetoothctl 2>/dev/null || true
if _check_connection_health "$TARGET_MAC"; then
return 0
@ -93,8 +103,15 @@ connect_device() {
# ---- Attempt 2: scan + pair from scratch ----
log_info "Scanning for $TARGET_MAC (20 seconds)..."
log_info "Make sure the device is in pairing mode."
{ echo "power on"; sleep 1; echo "scan on"; sleep 20; echo "scan off"; sleep 2; } \
| bluetoothctl 2>/dev/null || true
{
echo "power on"
sleep 1
echo "scan on"
sleep 20
echo "scan off"
sleep 2
} |
bluetoothctl 2>/dev/null || true
# Check if device was found
local devices
@ -109,17 +126,36 @@ connect_device() {
# Pair
log_info "Pairing..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "pair $TARGET_MAC"; sleep 5; } \
| bluetoothctl 2>/dev/null || true
{
echo "agent on"
echo "default-agent"
sleep 1
echo "power on"
sleep 1
echo "pair $TARGET_MAC"
sleep 5
} |
bluetoothctl 2>/dev/null || true
# Trust (so it auto-reconnects in the future)
log_info "Trusting..."
{ echo "trust $TARGET_MAC"; sleep 2; } | bluetoothctl 2>/dev/null || true
{
echo "trust $TARGET_MAC"
sleep 2
} | bluetoothctl 2>/dev/null || true
# Connect
log_info "Connecting..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "connect $TARGET_MAC"; sleep 15; } \
| bluetoothctl 2>/dev/null || true
{
echo "agent on"
echo "default-agent"
sleep 1
echo "power on"
sleep 1
echo "connect $TARGET_MAC"
sleep 15
} |
bluetoothctl 2>/dev/null || true
# Verify connection + services + audio
if _check_connection_health "$TARGET_MAC"; then

View File

@ -0,0 +1,106 @@
#!/usr/bin/env bash
# lib/tests/arch_perf_harness.sh — shared setup for the arch performance lib
# tests (arch_perf_report.sh, arch_perf_probes.sh).
#
# Sourced, not executed. Builds on lib_test_core.sh and adds the pieces these
# libs read from their entry script, diagnose_arch_performance.sh:
#
# * REPORT_FILE, FINDINGS, ACTIONS and the APPLY_SAFE_FIXES flag;
# * add_finding, add_action and run_and_log, redefined verbatim from the
# entry script -- they live there rather than in any lib, the same
# arrangement pacman_hook_stall_harness.sh handles with log_size;
# * the real log_*/has_cmd helpers, via scripts/lib/common.sh.
#
# REPORT_FILE points into the throwaway tmpdir, so the probes' report writes
# never leave the sandbox.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FIXES_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
REPO_ROOT="$(cd "${FIXES_DIR}/../../../.." && pwd)"
# shellcheck source=lib_test_core.sh
. "${SCRIPT_DIR}/lib_test_core.sh"
# shellcheck source=../../../../lib/common.sh
. "${REPO_ROOT}/linux_configuration/scripts/lib/common.sh"
# --- globals and helpers owned by diagnose_arch_performance.sh --------------
# These four are read by the libs under test, never by this harness, so
# static analysis cannot see the use; export makes the intent explicit.
export REPORT_FILE="${TEST_TMPDIR}/report.log"
# arch_perf_fixes.sh writes a journald drop-in and a systemd unit, and probes
# two absolute home paths for organize_downloads.sh. All three are behind
# overrides defaulting to the real locations, because run_all.sh runs UN-jailed
# in ci_mirror.sh and in CI, where a bind mount would protect nothing.
export JOURNALD_CONF_DIR="${TEST_TMPDIR}/journald.conf.d"
export SYSTEMD_UNIT_DIR="${TEST_TMPDIR}/systemd_units"
export ORGANIZE_SCRIPT_CANDIDATES="${TEST_TMPDIR}/organize_downloads.sh"
export APPLY_SAFE_FIXES="false"
export INSTALL_TOOLS="false"
declare -a FINDINGS=()
declare -a ACTIONS=()
# Verbatim from diagnose_arch_performance.sh.
add_finding() {
FINDINGS+=("$1")
log_warn "$1"
}
add_action() {
ACTIONS+=("$1")
log_info "$1"
}
run_and_log() {
local header="$1"
shift
{
echo
echo "=== $header ==="
"$@" 2>&1 || true
} >>"$REPORT_FILE"
}
# --- external tool stubs ----------------------------------------------------
_arch_default_stubs() {
local tool
for tool in nvidia-smi lspci journalctl systemctl sysctl lsblk sensors \
free uptime ps top swapon findmnt pacman systemd-analyze; do
_t_stub "$tool" 'exit 0'
done
}
# arch_reset — start a test group from "nothing has happened yet".
arch_reset() {
_t_reset_calls
FINDINGS=()
ACTIONS=()
APPLY_SAFE_FIXES="false"
INSTALL_TOOLS="false"
export APPLY_SAFE_FIXES INSTALL_TOOLS
: >"$REPORT_FILE"
rm -rf "${JOURNALD_CONF_DIR}" "${SYSTEMD_UNIT_DIR}"
mkdir -p "${JOURNALD_CONF_DIR}" "${SYSTEMD_UNIT_DIR}"
rm -f "${ORGANIZE_SCRIPT_CANDIDATES}"
_t_full_path
_arch_default_stubs
}
# _t_report — the report file's contents this round.
_t_report() {
cat "$REPORT_FILE" 2>/dev/null || true
}
# _t_findings / _t_actions — the recorded findings and actions, one per line.
_t_findings() {
printf '%s\n' "${FINDINGS[@]:-}"
}
_t_actions() {
printf '%s\n' "${ACTIONS[@]:-}"
}
arch_reset

View File

@ -99,22 +99,6 @@ SUDO_BODY
_t_stub sudo "$sudo_body"
}
# _t_only_path — restrict PATH to $FAKE_BIN plus coreutils, so a tool absent
# from $FAKE_BIN is genuinely "not installed" as far as has_cmd/command -v is
# concerned. Used for the has_cmd false branches.
_t_only_path() {
PATH="${FAKE_BIN}"
hash -r
}
# _t_full_path — restore the prepended-stub PATH set up by lib_test_core.sh.
_t_full_path() {
PATH="${FAKE_BIN}:${LIB_TEST_ORIG_PATH}"
hash -r
}
export LIB_TEST_ORIG_PATH="${PATH#"${FAKE_BIN}:"}"
# bt_reset — start a test group from "nothing has happened yet".
bt_reset() {
_t_reset_calls

View File

@ -85,6 +85,54 @@ STUB_PREAMBLE
hash -r
}
# _t_stub_writes NAME ARGNUM CONTENT — stub NAME so it writes CONTENT to the
# path in its ARGNUM-th argument, then succeeds.
#
# Exists because downloaders take their destination positionally
# (`wget -q "$url" -O "$dest"` puts it in $4), and writing that stub body as a
# quoted string means embedding a literal $4 the writer must not expand. The
# argument number is passed as data instead, so no caller needs to quote a $.
_t_stub_writes() {
local name="$1" argnum="$2" content="$3"
# The dollar that selects the positional argument is assembled from a
# character rather than written literally, so nothing in this file is a
# quoted expression that only looks like it should expand.
local dollar
dollar="$(printf '\044')"
local body
body="printf %s '${content}' >\"${dollar}{${argnum}}\""
body+="
exit 0"
_t_stub "$name" "$body"
}
# _t_stub_cat NAME FIXTURE — stub NAME so it prints the contents of
# $DEV/FIXTURE, a file the test writes beforehand.
#
# The commonest stub shape by far, and the one that otherwise forces every
# caller to embed a literal ${LIB_TEST_DEV} that must not expand at write
# time. Passing the fixture NAME as data keeps every call site quote-free.
_t_stub_cat() {
local name="$1" fixture="$2"
_t_stub_stdin "$name" <<STUB_CAT
cat "\${LIB_TEST_DEV}/${fixture}"
STUB_CAT
}
# _t_stub_stdin NAME — stub NAME with a multi-line body read from stdin.
#
# The body is data, not code this file evaluates, so a `$1` or `${VAR}` in it
# must survive verbatim to the stub file. Feeding it through stdin (from a
# quoted heredoc at the call site) keeps it literal without wrapping it in a
# single-quoted string, which static analysis flags as a non-expanding
# expression on every use.
_t_stub_stdin() {
local name="$1"
local body
body="$(cat)"
_t_stub "$name" "$body"
}
# _t_unstub NAME... — remove stubs and drop bash's cached executable paths.
#
# `rm` alone does NOT hide a stub: bash caches the resolved location of every
@ -99,6 +147,54 @@ _t_unstub() {
hash -r
}
# _t_hide TOOL... — make TOOL genuinely unfindable, so has_cmd/command -v
# report it absent.
#
# A prepended stub dir cannot do this: every tool these libs probe for
# (usbreset, pactl, wpctl) really exists on an Arch desktop, so PATH has to
# stop resolving it. Dropping PATH to $FAKE_BIN alone is NOT the answer
# either -- that also hides grep, head, awk and sort, which these libs use
# on the very branch under test, turning a "not installed" case into a
# cascade of "command not found".
#
# Instead a shim dir is built containing a symlink to every real executable
# on PATH EXCEPT the hidden ones, and PATH is pointed at it.
_t_hide() {
local hide_dir="${TEST_TMPDIR}/hidden_path"
rm -rf "$hide_dir"
mkdir -p "$hide_dir"
local -A hidden=()
local tool
for tool in "$@"; do
hidden["$tool"]=1
done
local dir entry name
local IFS=':'
for dir in ${LIB_TEST_ORIG_PATH}; do
[[ -d "$dir" ]] || continue
for entry in "$dir"/*; do
name="${entry##*/}"
[[ -n "${hidden[$name]:-}" ]] && continue
[[ -x "$entry" && ! -d "$entry" ]] || continue
[[ -e "${hide_dir}/${name}" ]] && continue
ln -s "$entry" "${hide_dir}/${name}" 2>/dev/null || true
done
done
PATH="${FAKE_BIN}:${hide_dir}"
hash -r
}
# _t_full_path — restore the prepended-stub PATH set up by lib_test_core.sh.
_t_full_path() {
PATH="${FAKE_BIN}:${LIB_TEST_ORIG_PATH}"
hash -r
}
export LIB_TEST_ORIG_PATH="${PATH#"${FAKE_BIN}:"}"
# _t_calls — print everything the stubs recorded this round.
_t_calls() {
cat "${DEV}/calls" 2>/dev/null || true

View File

@ -0,0 +1,122 @@
#!/usr/bin/env bash
# Tests for lib/arch_perf_fixes.sh: fix_journal, fix_nm_wait_online and
# fix_media_organizer.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=arch_perf_harness.sh
. "${SCRIPT_DIR}/arch_perf_harness.sh"
# shellcheck source=../arch_perf_fixes.sh
. "${FIXES_DIR}/lib/arch_perf_fixes.sh"
dropin="${JOURNALD_CONF_DIR}/size-limit.conf"
unit="${SYSTEMD_UNIT_DIR}/media-organizer.service"
# --- fix_journal ------------------------------------------------------------
# A multi-gigabyte journal is vacuumed AND capped. This only fires because the
# size regex now tolerates journalctl's spaceless "4.2G" output; with the old
# pattern the vacuum was unreachable.
arch_reset
_t_stub journalctl 'echo "Archived and active journals take up 4.2G in the file system."'
fix_journal
_t_contains "$(_t_calls)" "journalctl --vacuum-size=300M" \
"fix_journal: vacuums a multi-gigabyte journal"
_t_contains "$(cat "$dropin" 2>/dev/null)" "SystemMaxUse=300M" \
"fix_journal: writes the permanent size cap"
_t_contains "$(_t_calls)" "systemctl restart systemd-journald" \
"fix_journal: restarts journald after writing the cap"
# A journal already under a gigabyte is left alone, but still capped.
arch_reset
_t_stub journalctl 'echo "Archived and active journals take up 240.0M in the file system."'
out="$(fix_journal 2>&1)"
_t_contains "$out" "already under 1GiB" \
"fix_journal: reports a journal that is already small enough"
_t_lacks "$(_t_calls)" "journalctl --vacuum-size" \
"fix_journal: does not vacuum a journal measured in megabytes"
_t_contains "$(cat "$dropin" 2>/dev/null)" "SystemMaxUse=300M" \
"fix_journal: still writes the cap for a small journal"
# The cap already exists: it is not rewritten and journald is not restarted.
arch_reset
_t_stub journalctl 'echo "120.0M"'
printf '[Journal]\nSystemMaxUse=300M\n' >"$dropin"
out="$(fix_journal 2>&1)"
_t_contains "$out" "size cap already configured" \
"fix_journal: reports an already-configured size cap"
_t_lacks "$(_t_calls)" "systemctl restart systemd-journald" \
"fix_journal: does not restart journald when the cap already exists"
# --- fix_nm_wait_online -----------------------------------------------------
arch_reset
_t_stub systemctl 'exit 0'
fix_nm_wait_online
_t_contains "$(_t_calls)" "systemctl disable NetworkManager-wait-online.service" \
"fix_nm_wait_online: disables the wait-online unit when it is enabled"
arch_reset
_t_stub systemctl 'exit 1'
out="$(fix_nm_wait_online 2>&1)"
_t_contains "$out" "already disabled" \
"fix_nm_wait_online: reports a unit that is already disabled"
_t_lacks "$(_t_calls)" "systemctl disable" \
"fix_nm_wait_online: does not re-disable an already-disabled unit"
# --- fix_media_organizer ----------------------------------------------------
# The organizer script is nowhere to be found: the fix is skipped. Both
# candidate paths are absolute; the first is overridden into the tmpdir and
# the second is a real home path that does not exist on this machine.
arch_reset
if [[ -f /home/kuhy/linux-configuration/scripts/utils/organize_downloads.sh ]]; then
_t_pass "fix_media_organizer: SKIP not-found case (the second candidate exists here)"
else
out="$(fix_media_organizer 2>&1)"
_t_contains "$out" "not found — skipping" \
"fix_media_organizer: skips when no organize_downloads.sh exists"
_t_lacks "$(_t_calls)" "systemctl daemon-reload" \
"fix_media_organizer: writes no unit when the script is missing"
fi
# The script exists: the unit is written, reloaded and enabled.
arch_reset
printf '#!/bin/bash\necho organize\n' >"$ORGANIZE_SCRIPT_CANDIDATES"
out="$(SUDO_USER="kuhy" fix_media_organizer 2>&1)"
unit_text="$(cat "$unit" 2>/dev/null)"
_t_contains "$unit_text" "Description=Media File Organizer" \
"fix_media_organizer: writes the unit description"
_t_contains "$unit_text" "User=kuhy" \
"fix_media_organizer: runs the unit as the invoking user, not root"
_t_contains "$unit_text" "ExecStart=${ORGANIZE_SCRIPT_CANDIDATES}" \
"fix_media_organizer: points ExecStart at the script it found"
_t_contains "$(_t_calls)" "systemctl daemon-reload" \
"fix_media_organizer: reloads systemd after writing the unit"
_t_contains "$(_t_calls)" "systemctl enable media-organizer.service" \
"fix_media_organizer: enables the unit"
_t_contains "$(_t_calls)" "systemctl stop media-organizer.service" \
"fix_media_organizer: stops the old unit before replacing it"
# An already-correct unit is left alone.
arch_reset
printf '#!/bin/bash\n' >"$ORGANIZE_SCRIPT_CANDIDATES"
printf 'User=kuhy\nExecStart=%s\n' "$ORGANIZE_SCRIPT_CANDIDATES" >"$unit"
out="$(SUDO_USER="kuhy" fix_media_organizer 2>&1)"
_t_contains "$out" "already correctly configured" \
"fix_media_organizer: skips a unit that is already correct"
_t_eq "" "$(_t_calls)" \
"fix_media_organizer: runs no systemctl command when the unit is correct"
# A unit that exists but names the WRONG user is rewritten.
arch_reset
printf '#!/bin/bash\n' >"$ORGANIZE_SCRIPT_CANDIDATES"
printf 'User=someoneelse\nExecStart=%s\n' "$ORGANIZE_SCRIPT_CANDIDATES" >"$unit"
out="$(SUDO_USER="kuhy" fix_media_organizer 2>&1)"
_t_contains "$(cat "$unit")" "User=kuhy" \
"fix_media_organizer: rewrites a unit that names the wrong user"
echo
echo "arch_perf_fixes: ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,119 @@
#!/usr/bin/env bash
# Tests for lib/arch_perf_probes.sh: collect_basics and check_cpu_governor.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=arch_perf_harness.sh
. "${SCRIPT_DIR}/arch_perf_harness.sh"
# shellcheck source=../arch_perf_probes.sh
. "${FIXES_DIR}/lib/arch_perf_probes.sh"
# --- collect_basics ---------------------------------------------------------
# A quiet machine: every section is logged, and nothing is flagged.
arch_reset
_t_stub uname 'echo "Linux kuhy-pc 7.1.9-arch1-1"'
_t_stub uptime 'echo " 12:00:00 up 2:00, 1 user, load average: 0.10, 0.20, 0.30"'
_t_stub free 'echo "Mem: 32Gi 8Gi 24Gi"'
_t_stub swapon 'exit 0'
_t_stub lscpu 'echo "CPU(s): 16"'
_t_stub df 'echo "/dev/nvme0n1p2 100G 40G 60G 40% /"'
_t_stub systemd-analyze 'echo "Startup finished in 3.2s"'
_t_stub systemctl 'exit 0'
_t_stub journalctl 'exit 0'
_t_stub getconf 'echo 16'
_t_stub ps 'echo " PID COMMAND %CPU %MEM"'
collect_basics
report="$(_t_report)"
_t_contains "$report" "=== Kernel ===" "collect_basics: logs the kernel section"
_t_contains "$report" "=== Uptime ===" "collect_basics: logs the uptime section"
_t_contains "$report" "=== Memory ===" "collect_basics: logs the memory section"
_t_contains "$report" "=== Boot Time ===" "collect_basics: logs the boot time section"
_t_contains "$report" "=== Failed Units ===" "collect_basics: logs the failed units section"
_t_contains "$report" "=== Top CPU Processes ===" \
"collect_basics: logs the top CPU processes snapshot"
_t_eq "" "$(_t_findings)" "collect_basics: flags nothing on a quiet machine"
# Failed units, frequent ACPI errors and a busy Xorg are each flagged.
arch_reset
_t_stub getconf 'echo 16'
_t_stub_stdin systemctl <<'STUB_BODY'
if [[ "$*" == *"--failed --no-legend"* ]]; then
echo "foo.service loaded failed failed Foo"
echo "bar.service loaded failed failed Bar"
fi
exit 0
STUB_BODY
_t_stub_stdin journalctl <<'STUB_BODY'
for _ in 1 2 3 4 5 6; do
echo "kernel: ACPI Error: something went wrong"
done
exit 0
STUB_BODY
_t_stub_stdin ps <<'STUB_BODY'
if [[ "$*" == *"-C Xorg"* ]]; then
echo " 45.0"
exit 0
fi
echo " PID COMMAND %CPU %MEM"
STUB_BODY
collect_basics
findings="$(_t_findings)"
_t_contains "$findings" "systemd units are failed (2)" \
"collect_basics: flags failed systemd units and counts them"
_t_contains "$findings" "ACPI errors detected" \
"collect_basics: flags frequent ACPI errors"
_t_contains "$findings" "Xorg is using high CPU (45%)" \
"collect_basics: flags a CPU-hungry Xorg"
# A load average at or above the thread count is flagged. /proc/loadavg is
# read directly by the lib, so the case is driven by a low CPU count instead.
arch_reset
_t_stub getconf 'echo 1'
_t_stub systemctl 'exit 0'
_t_stub journalctl 'exit 0'
_t_stub ps 'echo none'
collect_basics
if [[ $(awk '{print int($1)}' /proc/loadavg) -ge 1 ]]; then
_t_contains "$(_t_findings)" "load average is at/above CPU thread count" \
"collect_basics: flags a load average at or above the thread count"
else
_t_pass "collect_basics: SKIP load case (this host's 1-minute load is below 1)"
fi
# --- check_cpu_governor -----------------------------------------------------
# The lib runs `find /sys/devices/system/cpu`, a real path with no override,
# so `find` is stubbed to control which governor files it reports.
arch_reset
mkdir -p "${TEST_TMPDIR}/gov"
echo "performance" >"${TEST_TMPDIR}/gov/cpu0"
echo "performance" >"${TEST_TMPDIR}/gov/cpu1"
printf '%s\n%s\n' "${TEST_TMPDIR}/gov/cpu0" "${TEST_TMPDIR}/gov/cpu1" >"${DEV}/gov_list"
_t_stub_cat find gov_list
check_cpu_governor
_t_contains "$(_t_report)" "CPU governor summary: performance:2" \
"check_cpu_governor: summarises the governors in use"
_t_eq "" "$(_t_findings)" "check_cpu_governor: flags nothing when every core is on performance"
# A core left on powersave is the condition the probe exists for.
arch_reset
echo "powersave" >"${TEST_TMPDIR}/gov/cpu1"
_t_stub_cat find gov_list
check_cpu_governor
_t_contains "$(_t_findings)" "governor includes 'powersave'" \
"check_cpu_governor: flags a core left on the powersave governor"
# No governor files at all: an action, not a finding, and no hang.
arch_reset
: >"${DEV}/gov_list"
_t_stub_cat find gov_list
check_cpu_governor
_t_contains "$(_t_actions)" "CPU governor files not found" \
"check_cpu_governor: records an action when no governor files exist"
_t_eq "" "$(_t_findings)" "check_cpu_governor: records no finding when governors are unsupported"
echo
echo "arch_perf_probes (basics/governor): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,189 @@
#!/usr/bin/env bash
# Tests for lib/arch_perf_probes.sh: check_thermal_state, check_power_services,
# check_storage_health and check_memory_pressure.
# Split from test_arch_perf_probes.sh for the 250-line cap.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=arch_perf_harness.sh
. "${SCRIPT_DIR}/arch_perf_harness.sh"
# shellcheck source=../arch_perf_probes.sh
. "${FIXES_DIR}/lib/arch_perf_probes.sh"
# --- check_thermal_state ----------------------------------------------------
# sensors present and dmesg clean: the section is logged, nothing flagged.
arch_reset
_t_stub sensors 'echo "Core 0: +45.0C"'
_t_stub dmesg 'echo "usb 1-1: new high-speed USB device"'
check_thermal_state
_t_contains "$(_t_report)" "=== Temperatures (sensors) ===" \
"check_thermal_state: logs the sensors output when sensors is installed"
_t_eq "" "$(_t_findings)" "check_thermal_state: flags nothing when dmesg is clean"
# Throttling messages in dmesg are flagged and excerpted into the report.
arch_reset
_t_stub sensors 'echo "Core 0: +95.0C"'
_t_stub dmesg 'echo "CPU2: Core temperature above threshold, cpu clock throttled"'
check_thermal_state
_t_contains "$(_t_findings)" "thermal/throttling related messages" \
"check_thermal_state: flags throttling messages in the kernel log"
_t_contains "$(_t_report)" "=== Thermal/Throttling dmesg excerpts ===" \
"check_thermal_state: excerpts the throttling lines into the report"
# sensors absent: an action recommending lm_sensors. The host may have a real
# sensors binary, so _t_hide takes it off PATH.
arch_reset
_t_unstub sensors
_t_hide sensors
_t_stub dmesg 'echo "nothing interesting"'
check_thermal_state
_t_full_path
_t_contains "$(_t_actions)" "Install lm_sensors" \
"check_thermal_state: recommends lm_sensors when sensors is missing"
# --- check_power_services ---------------------------------------------------
# Both daemons enabled: the classic conflict.
arch_reset
_t_stub systemctl 'exit 0'
check_power_services
_t_contains "$(_t_report)" "Power services: tlp=true, power-profiles-daemon=true" \
"check_power_services: records both daemons as enabled"
_t_contains "$(_t_findings)" "Both TLP and power-profiles-daemon are enabled" \
"check_power_services: flags the TLP/ppd conflict"
# Neither enabled: an action, not a finding.
arch_reset
_t_stub systemctl 'exit 1'
check_power_services
_t_contains "$(_t_report)" "Power services: tlp=false, power-profiles-daemon=false" \
"check_power_services: records both daemons as disabled"
_t_contains "$(_t_actions)" "No power management daemon is enabled" \
"check_power_services: recommends enabling a power daemon when none is"
_t_eq "" "$(_t_findings)" "check_power_services: flags nothing when neither daemon runs"
# Exactly one enabled is the healthy case: neither finding nor action.
arch_reset
_t_stub_stdin systemctl <<'STUB_BODY'
[[ "$*" == *"power-profiles-daemon"* ]] && exit 0
exit 1
STUB_BODY
check_power_services
_t_contains "$(_t_report)" "tlp=false, power-profiles-daemon=true" \
"check_power_services: records a single enabled daemon"
_t_eq "" "$(_t_findings)" "check_power_services: flags nothing when only one daemon is enabled"
_t_eq "" "$(_t_actions)" "check_power_services: recommends nothing when one daemon is enabled"
# --- check_storage_health ---------------------------------------------------
arch_reset
_t_stub lsblk 'echo "nvme0n1 Samsung 990 0 1T disk"'
_t_stub fstrim 'echo "/: 12 GiB (trimmed)"'
_t_stub systemctl 'exit 0'
_t_stub smartctl 'echo "SMART overall-health self-assessment test result: PASSED"'
_t_stub findmnt 'echo "/dev/nvme0n1p2"'
check_storage_health
_t_contains "$(_t_report)" "=== Block Devices ===" \
"check_storage_health: logs the block device list"
_t_contains "$(_t_report)" "=== fstrim dry-run ===" \
"check_storage_health: logs the fstrim dry run when fstrim is present"
_t_contains "$(_t_actions)" "fstrim.timer is enabled" \
"check_storage_health: records an enabled fstrim.timer as good"
_t_eq "" "$(_t_findings)" "check_storage_health: flags nothing on a healthy disk"
# fstrim.timer disabled is a finding; smartctl missing is an action.
arch_reset
_t_stub lsblk 'echo "sda disk"'
_t_stub systemctl 'exit 1'
_t_unstub smartctl
_t_hide smartctl fstrim
check_storage_health
_t_full_path
_t_contains "$(_t_findings)" "fstrim.timer is not enabled" \
"check_storage_health: flags a disabled fstrim.timer"
_t_contains "$(_t_actions)" "Install smartmontools" \
"check_storage_health: recommends smartmontools when smartctl is missing"
# --- check_memory_pressure --------------------------------------------------
# /proc/meminfo is read directly by the lib and cannot be redirected, so this
# asserts on the shape of the result rather than on fabricated numbers.
arch_reset
check_memory_pressure
report="$(_t_report)"
if grep -q '^SwapTotal: *0 ' /proc/meminfo; then
_t_lacks "$report" "Swap usage:" \
"check_memory_pressure: reports no swap usage when the host has no swap"
else
_t_contains "$report" "Swap usage:" \
"check_memory_pressure: records swap usage when the host has swap"
fi
if [[ -f /proc/pressure/memory ]]; then
_t_contains "$report" "=== Memory PSI ===" \
"check_memory_pressure: logs the kernel memory pressure counters"
else
_t_lacks "$report" "=== Memory PSI ===" \
"check_memory_pressure: omits the PSI section when the kernel lacks it"
fi
# The high-swap branch: swap heavily used while RAM is still available. The
# lib reads the absolute /proc/meminfo, but every read goes through `awk`, so
# stubbing awk supplies controlled figures without touching /proc. The stub
# answers on the pattern the lib greps for, and defers to the real awk for
# any other call (check_thermal_state and collect_basics use it too).
arch_reset
_t_stub_stdin awk <<'STUB_BODY'
case "$1" in
*MemTotal*) echo 32000000 ;;
*MemAvailable*) echo 20000000 ;;
*SwapTotal*) echo 8000000 ;;
*SwapFree*) echo 2000000 ;;
*) exec /usr/bin/awk "$@" ;;
esac
STUB_BODY
check_memory_pressure
_t_contains "$(_t_report)" "Swap usage: 75%" \
"check_memory_pressure: computes the swap usage percentage"
_t_contains "$(_t_findings)" "High swap usage while RAM is still available" \
"check_memory_pressure: flags heavy swapping while RAM is free"
_t_contains "$(_t_actions)" "lowering swappiness" \
"check_memory_pressure: recommends lowering swappiness"
# Heavy swap use with RAM genuinely exhausted is NOT the stutter signature,
# so it must not be flagged.
arch_reset
_t_stub_stdin awk <<'STUB_BODY'
case "$1" in
*MemTotal*) echo 32000000 ;;
*MemAvailable*) echo 500000 ;;
*SwapTotal*) echo 8000000 ;;
*SwapFree*) echo 2000000 ;;
*) exec /usr/bin/awk "$@" ;;
esac
STUB_BODY
check_memory_pressure
_t_contains "$(_t_report)" "Swap usage: 75%" \
"check_memory_pressure: still records the percentage when RAM is exhausted"
_t_eq "" "$(_t_findings)" \
"check_memory_pressure: does not flag swapping when RAM is genuinely full"
# A machine with no swap at all skips the whole swap section.
arch_reset
_t_stub_stdin awk <<'STUB_BODY'
case "$1" in
*MemTotal*) echo 32000000 ;;
*MemAvailable*) echo 20000000 ;;
*SwapTotal*) echo 0 ;;
*SwapFree*) echo 0 ;;
*) exec /usr/bin/awk "$@" ;;
esac
STUB_BODY
check_memory_pressure
_t_lacks "$(_t_report)" "Swap usage:" \
"check_memory_pressure: reports no swap usage on a swapless machine"
echo
echo "arch_perf_probes (health): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,116 @@
#!/usr/bin/env bash
# Tests for lib/arch_perf_report.sh: check_gpu_state, check_journal_size,
# apply_safe_fixes and print_summary.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=arch_perf_harness.sh
. "${SCRIPT_DIR}/arch_perf_harness.sh"
# shellcheck source=../arch_perf_report.sh
. "${FIXES_DIR}/lib/arch_perf_report.sh"
# --- check_gpu_state --------------------------------------------------------
# No nvidia-smi: falls back to listing PCI display devices. The host may have
# a real nvidia-smi, so _t_hide takes it off PATH outright.
arch_reset
_t_unstub nvidia-smi
_t_hide nvidia-smi
_t_stub lspci 'echo "01:00.0 VGA compatible controller [0300]: NVIDIA Corporation GA104"'
check_gpu_state
_t_full_path
_t_contains "$(_t_report)" "=== PCI VGA Devices ===" \
"check_gpu_state: logs PCI display devices when nvidia-smi is absent"
_t_eq "" "$(_t_findings)" "check_gpu_state: records no finding without nvidia-smi"
# An idle GPU pinned in P0 is the condition the check exists for.
arch_reset
_t_stub_stdin nvidia-smi <<'STUB_BODY'
case "$1" in
--query-gpu=pstate) echo P0 ;;
--query-gpu=utilization.gpu) echo 2 ;;
--query-gpu=power.draw) echo 31.5 ;;
*) echo "full nvidia-smi output" ;;
esac
STUB_BODY
check_gpu_state
_t_contains "$(_t_report)" "NVIDIA pstate: P0" \
"check_gpu_state: records the reported pstate"
_t_contains "$(_t_report)" "NVIDIA util: 2%" \
"check_gpu_state: records the reported utilisation"
_t_contains "$(_t_report)" "NVIDIA power: 31.5W" \
"check_gpu_state: records the reported power draw"
_t_contains "$(_t_findings)" "P0 high-performance state while mostly idle" \
"check_gpu_state: flags a GPU idling in P0"
_t_contains "$(_t_actions)" "prefer iGPU mode" \
"check_gpu_state: recommends the iGPU for desktop workloads"
# A busy GPU in P0 is normal and must NOT be flagged.
arch_reset
_t_stub_stdin nvidia-smi <<'STUB_BODY'
case "$1" in
--query-gpu=pstate) echo P0 ;;
--query-gpu=utilization.gpu) echo 87 ;;
--query-gpu=power.draw) echo 210 ;;
*) echo "out" ;;
esac
STUB_BODY
check_gpu_state
_t_eq "" "$(_t_findings)" "check_gpu_state: does not flag a P0 GPU that is actually busy"
# An idle GPU in a low-power state is also fine.
arch_reset
_t_stub_stdin nvidia-smi <<'STUB_BODY'
case "$1" in
--query-gpu=pstate) echo P8 ;;
--query-gpu=utilization.gpu) echo 0 ;;
--query-gpu=power.draw) echo 9 ;;
*) echo "out" ;;
esac
STUB_BODY
check_gpu_state
_t_eq "" "$(_t_findings)" "check_gpu_state: does not flag an idle GPU in a low-power state"
# nvidia-smi present but answering nothing: the report records "unknown".
arch_reset
_t_stub nvidia-smi 'exit 0'
check_gpu_state
_t_contains "$(_t_report)" "NVIDIA pstate: unknown" \
"check_gpu_state: records 'unknown' when nvidia-smi returns nothing"
# --- check_journal_size -----------------------------------------------------
arch_reset
_t_stub journalctl 'echo "Archived and active journals take up 4.2G in the file system."'
check_journal_size
_t_contains "$(_t_report)" "Journal usage:" "check_journal_size: records journal usage"
_t_contains "$(_t_findings)" "journal is large (4.2G)" \
"check_journal_size: flags a multi-gigabyte journal"
# The real journalctl format, with NO space before the unit -- this is what
# the machine actually prints, and requiring a space made the check dead.
arch_reset
_t_stub journalctl 'echo "Archived and active journals take up 240.0M in the file system."'
check_journal_size
_t_eq "" "$(_t_findings)" "check_journal_size: does not flag a journal measured in megabytes"
_t_contains "$(_t_report)" "240.0M" \
"check_journal_size: records the megabyte figure verbatim"
# A space-separated figure must keep working too.
arch_reset
_t_stub journalctl 'echo "Archived and active journals take up 6.1 G in the file system."'
check_journal_size
_t_contains "$(_t_findings)" "journal is large (6.1G)" \
"check_journal_size: still flags a space-separated gigabyte figure"
arch_reset
_t_stub journalctl 'exit 1'
check_journal_size
_t_contains "$(_t_report)" "Journal usage: unknown" \
"check_journal_size: records 'unknown' when journalctl fails"
_t_eq "" "$(_t_findings)" "check_journal_size: records no finding when journalctl fails"
echo
echo "arch_perf_report (probes): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,111 @@
#!/usr/bin/env bash
# Tests for lib/arch_perf_report.sh: apply_safe_fixes and print_summary.
# Split from test_arch_perf_report.sh for the 250-line cap.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=arch_perf_harness.sh
. "${SCRIPT_DIR}/arch_perf_harness.sh"
# shellcheck source=../arch_perf_report.sh
. "${FIXES_DIR}/lib/arch_perf_report.sh"
# --- apply_safe_fixes -------------------------------------------------------
# Off by default: the flag guards every mutation.
arch_reset
APPLY_SAFE_FIXES="false"
apply_safe_fixes >"${TEST_TMPDIR}/out" 2>&1
out="$(cat "${TEST_TMPDIR}/out")"
_t_eq "" "$out" "apply_safe_fixes: does nothing unless APPLY_SAFE_FIXES is true"
_t_eq "" "$(_t_calls)" "apply_safe_fixes: runs no command when disabled"
# fstrim.timer already enabled, no tlp/ppd conflict, small journal: nothing
# to do, but the pass still announces itself.
arch_reset
APPLY_SAFE_FIXES="true"
_t_stub systemctl 'exit 0'
_t_stub journalctl 'echo "Archived and active journals take up 120.0M in the file system."'
apply_safe_fixes >"${TEST_TMPDIR}/out" 2>&1
out="$(cat "${TEST_TMPDIR}/out")"
_t_contains "$out" "Applying safe fixes" "apply_safe_fixes: announces the pass"
_t_lacks "$(_t_calls)" "systemctl enable --now fstrim.timer" \
"apply_safe_fixes: does not re-enable an already-enabled fstrim.timer"
_t_lacks "$(_t_calls)" "journalctl --vacuum-size" \
"apply_safe_fixes: does not vacuum a journal measured in megabytes"
# fstrim.timer disabled: it gets enabled.
arch_reset
APPLY_SAFE_FIXES="true"
_t_stub_stdin systemctl <<'STUB_BODY'
if [[ "$1" == "is-enabled" && "$2" == "fstrim.timer" ]]; then
exit 1
fi
exit 0
STUB_BODY
_t_stub journalctl 'echo "120.0M"'
apply_safe_fixes >"${TEST_TMPDIR}/out" 2>&1
out="$(cat "${TEST_TMPDIR}/out")"
_t_contains "$(_t_calls)" "systemctl enable --now fstrim.timer" \
"apply_safe_fixes: enables a disabled fstrim.timer"
_t_contains "$(_t_actions)" "Enabled and started fstrim.timer" \
"apply_safe_fixes: records enabling fstrim.timer as an action"
# tlp and power-profiles-daemon both enabled: tlp is disabled to break the
# conflict.
arch_reset
APPLY_SAFE_FIXES="true"
_t_stub systemctl 'exit 0'
_t_stub journalctl 'echo "120.0M"'
apply_safe_fixes >"${TEST_TMPDIR}/out" 2>&1
out="$(cat "${TEST_TMPDIR}/out")"
_t_contains "$(_t_calls)" "systemctl disable --now tlp.service" \
"apply_safe_fixes: disables tlp.service when it conflicts with ppd"
_t_contains "$(_t_actions)" "Disabled tlp.service" \
"apply_safe_fixes: records disabling tlp.service as an action"
# A multi-gigabyte journal gets vacuumed. This only fires because the size
# regex now tolerates journalctl's spaceless "4.2G" output.
arch_reset
APPLY_SAFE_FIXES="true"
_t_stub systemctl 'exit 0'
_t_stub journalctl 'echo "Archived and active journals take up 4.2G in the file system."'
apply_safe_fixes >"${TEST_TMPDIR}/out" 2>&1
out="$(cat "${TEST_TMPDIR}/out")"
_t_contains "$(_t_calls)" "journalctl --vacuum-size=300M" \
"apply_safe_fixes: vacuums a multi-gigabyte journal"
_t_contains "$(_t_actions)" "Vacuumed systemd journal to 300M" \
"apply_safe_fixes: records the vacuum as an action"
# --- print_summary ----------------------------------------------------------
arch_reset
out="$(print_summary 2>&1)"
_t_contains "$out" "Arch Performance Diagnostics" "print_summary: prints the banner"
_t_contains "$out" "Report: ${REPORT_FILE}" "print_summary: names the report file"
_t_contains "$out" "No high-confidence bottlenecks detected" \
"print_summary: reports a clean run when there are no findings"
_t_contains "$out" "systemd-analyze blame" \
"print_summary: suggests the deep-analysis commands"
arch_reset
add_finding "first problem" >/dev/null
add_finding "second problem" >/dev/null
out="$(print_summary 2>&1)"
_t_contains "$out" "Likely issues found (2)" \
"print_summary: counts the findings it lists"
_t_contains "$out" "- first problem" "print_summary: lists the first finding"
_t_contains "$out" "- second problem" "print_summary: lists the second finding"
_t_lacks "$out" "No high-confidence bottlenecks" \
"print_summary: does not claim a clean run when findings exist"
arch_reset
add_action "do the thing" >/dev/null
out="$(print_summary 2>&1)"
_t_contains "$out" "Actions/recommendations:" \
"print_summary: prints the actions section when actions exist"
_t_contains "$out" "- do the thing" "print_summary: lists the recorded action"
echo
echo "arch_perf_report (fixes/summary): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,118 @@
#!/usr/bin/env bash
# Tests for lib/bt_adapter.sh: check_firmware and _download_firmware.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=bt_harness.sh
. "${SCRIPT_DIR}/bt_harness.sh"
# shellcheck source=../bt_adapter.sh
. "${FIXES_DIR}/lib/bt_adapter.sh"
# _dmesg_out TEXT — stub dmesg to emit TEXT.
_dmesg_out() {
printf '%s\n' "$1" >"${DEV}/dmesg_out"
local body
body="$(
cat <<'DMESG_BODY'
cat "${LIB_TEST_DEV}/dmesg_out"
DMESG_BODY
)"
_t_stub dmesg "$body"
}
# _record_download ARGS... — stand-in for the real downloader, recording only.
_record_download() {
printf 'download_called %s\n' "$*" >>"${DEV}/fixes"
}
# --- check_firmware ---------------------------------------------------------
# dmesg mentions no .hcd file at all: nothing is missing.
bt_reset
_dmesg_out "usb 1-1: new full-speed USB device number 2"
out="$(check_firmware 2>&1)"
_t_contains "$out" "No missing firmware detected" \
"check_firmware: reports nothing missing when dmesg names no .hcd file"
_t_eq "" "$(_t_fixes)" "check_firmware: applies no fix when no firmware is missing"
# dmesg names a firmware file that is NOT present under the absolute
# /usr/lib/firmware the lib reads, so the download branch runs. The name is
# deliberately one no distribution ships; the "already installed" arm is
# covered by the real-path case below.
bt_reset
_dmesg_out "bluetooth hci0: Direct firmware load for brcm/BCM99999-nonexistent.hcd failed"
out="$(
# Called indirectly by check_firmware.
eval '_download_firmware() { _record_download "$@"; }'
check_firmware 2>&1
)"
_t_contains "$out" "Missing firmware: brcm/BCM99999-nonexistent.hcd" \
"check_firmware: warns about a firmware file dmesg reports as missing"
_t_contains "$out" "Downloading BCM99999-nonexistent.hcd" \
"check_firmware: applies the download fix for missing firmware"
_t_contains "$(_t_fixes)" \
"download_called https://github.com/winterheart/broadcom-bt-firmware/raw/master/brcm/BCM99999-nonexistent.hcd /usr/lib/firmware/brcm/BCM99999-nonexistent.hcd" \
"check_firmware: builds the upstream URL and destination path for the download"
# A firmware file that IS present under /usr/lib/firmware is skipped. Which
# files exist varies by host, so this case is driven by whatever is really
# there and self-skips when the directory has none.
bt_reset
present_fw="$(find /usr/lib/firmware/brcm -name '*.hcd' -printf '%f\n' 2>/dev/null | head -1)"
if [[ -n $present_fw ]]; then
_dmesg_out "bluetooth hci0: Direct firmware load for brcm/${present_fw} failed"
out="$(check_firmware 2>&1)"
_t_contains "$out" "Firmware brcm/${present_fw} already installed" \
"check_firmware: skips a firmware file that is already installed"
_t_eq "" "$(_t_fixes)" \
"check_firmware: applies no fix when the firmware is already installed"
else
_t_pass "check_firmware: SKIP already-installed case (no .hcd under /usr/lib/firmware/brcm)"
fi
# Several missing files in one dmesg dump are each handled, and duplicates
# collapse: the lib pipes through `sort -u`.
bt_reset
_dmesg_out "bluetooth hci0: Direct firmware load for brcm/BCM111.hcd failed
bluetooth hci0: Direct firmware load for brcm/BCM222.hcd failed
bluetooth hci0: Direct firmware load for brcm/BCM111.hcd failed"
out="$(
eval '_download_firmware() { _record_download "$@"; }'
check_firmware 2>&1
)"
_t_eq "2" "$(grep -c 'download_called' "${DEV}/fixes")" \
"check_firmware: de-duplicates repeated firmware names via sort -u"
_t_contains "$(_t_fixes)" "brcm/BCM111.hcd" "check_firmware: handles the first missing file"
_t_contains "$(_t_fixes)" "brcm/BCM222.hcd" "check_firmware: handles the second missing file"
# --- _download_firmware -----------------------------------------------------
# wget succeeding is enough: curl is never reached.
bt_reset
dest="${TEST_TMPDIR}/fw/BCM.hcd"
rm -rf "${TEST_TMPDIR}/fw"
# Real call shapes: wget -q "$url" -O "$dest" and curl -sL "$url" -o "$dest",
# so the destination is the 4th argument to each.
_t_stub_writes wget 4 "fw-from-wget"
_t_stub_writes curl 4 "fw-from-curl"
_download_firmware "https://example.invalid/BCM.hcd" "$dest"
_t_eq "fw-from-wget" "$(cat "$dest")" \
"_download_firmware: fetches with wget and writes the destination file"
_t_lacks "$(_t_calls)" "curl " \
"_download_firmware: does not fall back to curl when wget succeeds"
_t_pass "_download_firmware: creates the destination directory (write above succeeded)"
# wget failing falls back to curl.
bt_reset
dest="${TEST_TMPDIR}/fw2/BCM.hcd"
rm -rf "${TEST_TMPDIR}/fw2"
_t_stub wget 'exit 1'
_t_stub_writes curl 4 "fw-from-curl"
_download_firmware "https://example.invalid/BCM.hcd" "$dest"
_t_eq "fw-from-curl" "$(cat "$dest")" \
"_download_firmware: falls back to curl when wget fails"
echo
echo "bt_adapter (firmware): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,200 @@
#!/usr/bin/env bash
# Tests for lib/bt_adapter.sh: check_adapter_stuck, _reload_btusb,
# _services_resolved, _full_adapter_reset_and_connect and _verify_audio_sink.
# Split from test_bt_adapter.sh for the 250-line cap.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=bt_harness.sh
. "${SCRIPT_DIR}/bt_harness.sh"
# shellcheck source=../bt_adapter.sh
. "${FIXES_DIR}/lib/bt_adapter.sh"
# bt_adapter.sh calls _run_as_user and _restart_pipewire_stack, which are
# defined in bt_audio.sh. fix_bluetooth.sh sources both libs, so sourcing
# bt_audio.sh here reproduces the real resolution order rather than stubbing
# the two helpers out.
# shellcheck source=../bt_audio.sh
. "${FIXES_DIR}/lib/bt_audio.sh"
# _btctl_list TEXT — stub bluetoothctl so `_btctl list` emits TEXT.
_btctl_list() {
printf '%s\n' "$1" >"${DEV}/btctl_out"
_t_stub_cat bluetoothctl btctl_out
}
# _lsusb_line TEXT — stub lsusb to emit TEXT.
_lsusb_line() {
printf '%s\n' "$1" >"${DEV}/lsusb_out"
_t_stub_cat lsusb lsusb_out
}
# _record_reload ARGS... — stand-in for the real btusb reloader.
_record_reload() {
printf 'reload_called %s\n' "$*" >>"${DEV}/fixes"
}
# --- check_adapter_stuck ----------------------------------------------------
# A responsive adapter short-circuits before any USB work.
bt_reset
_btctl_list "Controller AA:BB:CC:11:22:33 kuhy-pc [default]"
out="$(check_adapter_stuck 2>&1)"
_t_contains "$out" "Adapter is responsive" \
"check_adapter_stuck: reports a responsive adapter"
_t_eq "" "$(_t_fixes)" "check_adapter_stuck: applies no fix when the adapter responds"
# Unresponsive adapter, and lsusb sees no bluetooth dongle at all.
bt_reset
_btctl_list "No default controller available"
_t_stub lsusb 'echo "Bus 001 Device 002: ID 046d:c077 Logitech, Inc. Mouse"'
out="$(check_adapter_stuck 2>&1)"
_t_contains "$out" "not responding" \
"check_adapter_stuck: warns when bluetoothctl sees no controller"
_t_contains "$out" "No USB Bluetooth adapter found" \
"check_adapter_stuck: reports a missing dongle when lsusb has no bluetooth line"
# Unresponsive adapter with a bluetooth dongle present and usbreset available:
# the USB reset path runs.
bt_reset
_btctl_list "No default controller available"
_lsusb_line "Bus 001 Device 004: ID 0a12:0001 Cambridge Silicon Radio Bluetooth dongle"
out="$(check_adapter_stuck 2>&1)"
_t_contains "$out" "USB-resetting Bluetooth adapter (0a12:0001)" \
"check_adapter_stuck: USB-resets the adapter when usbreset is available"
_t_contains "$(_t_calls)" "usbreset 0a12:0001" \
"check_adapter_stuck: passes the parsed USB ID to usbreset"
# Same, but usbreset is NOT installed: the btusb reload fallback runs. This
# host really has /usr/bin/usbreset, and a prepended stub dir cannot hide a
# real binary, so _t_hide rebuilds PATH without it while keeping grep/head
# (which this very branch uses) reachable.
bt_reset
_btctl_list "No default controller available"
_lsusb_line "Bus 001 Device 004: ID 0a12:0001 Cambridge Silicon Radio Bluetooth dongle"
_t_unstub usbreset
_t_hide usbreset
out="$(
eval '_reload_btusb() { _record_reload "$@"; }'
check_adapter_stuck 2>&1
)"
_t_full_path
_t_contains "$out" "Falling back to btusb module reload" \
"check_adapter_stuck: falls back to a btusb reload when usbreset is absent"
_t_contains "$(_t_fixes)" "reload_called" \
"check_adapter_stuck: runs the btusb reload fix when usbreset is absent"
# A bluetooth line whose ID does not parse leaves usb_id empty, which also
# takes the btusb reload fallback.
bt_reset
_btctl_list "No default controller available"
_lsusb_line "Bus 001 Device 004: Bluetooth dongle with no parseable id"
out="$(
eval '_reload_btusb() { _record_reload "$@"; }'
check_adapter_stuck 2>&1
)"
_t_contains "$(_t_fixes)" "reload_called" \
"check_adapter_stuck: falls back to a btusb reload when the USB ID does not parse"
# --- _reload_btusb ----------------------------------------------------------
bt_reset
_reload_btusb
_t_contains "$(_t_calls)" "modprobe -r btusb" "_reload_btusb: unloads the btusb module"
_t_contains "$(_t_calls)" "modprobe btusb" "_reload_btusb: loads btusb again"
# --- _services_resolved -----------------------------------------------------
bt_reset
_t_stub dbus-send 'echo " variant boolean true"'
if _services_resolved "AA:BB:CC:DD:EE:FF"; then
_t_pass "_services_resolved: true when the property reads boolean true"
else
_t_fail "_services_resolved: expected success on boolean true"
fi
_t_contains "$(_t_calls)" "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF" \
"_services_resolved: builds the dbus object path from the MAC"
bt_reset
_t_stub dbus-send 'echo " variant boolean false"'
if _services_resolved "AA:BB:CC:DD:EE:FF"; then
_t_fail "_services_resolved: expected failure on boolean false"
else
_t_pass "_services_resolved: false when the property reads boolean false"
fi
bt_reset
_t_stub dbus-send 'exit 1'
if _services_resolved "AA:BB:CC:DD:EE:FF"; then
_t_fail "_services_resolved: expected failure when dbus-send fails"
else
_t_pass "_services_resolved: false when dbus-send itself fails"
fi
# --- _full_adapter_reset_and_connect ----------------------------------------
#
# The real body sleeps 1 + 2 + 5 + 3 + 3 + 20 = 34 seconds. `sleep` is stubbed
# to return instantly so the suite stays fast; the calls are still recorded,
# so the ordering assertions below are on the real sequence.
bt_reset
_t_stub sleep 'exit 0'
_t_stub bluetoothctl 'cat >/dev/null; exit 0'
out="$(_full_adapter_reset_and_connect "AA:BB:CC:DD:EE:FF" 2>&1)"
calls="$(_t_calls)"
_t_contains "$out" "Performing full adapter reset" \
"_full_adapter_reset_and_connect: announces the reset"
_t_contains "$calls" "modprobe -r btusb" \
"_full_adapter_reset_and_connect: unloads btusb"
_t_contains "$calls" "modprobe btusb" \
"_full_adapter_reset_and_connect: reloads btusb"
_t_contains "$calls" "systemctl restart bluetooth.service" \
"_full_adapter_reset_and_connect: restarts bluetooth.service"
_t_contains "$out" "Reconnecting to AA:BB:CC:DD:EE:FF" \
"_full_adapter_reset_and_connect: announces the reconnect"
_t_contains "$calls" "systemctl --user restart pipewire pipewire-pulse wireplumber" \
"_full_adapter_reset_and_connect: restarts the pipewire stack via _run_as_user"
# --- _verify_audio_sink -----------------------------------------------------
# pactl absent: the function returns success without probing anything. This
# host really has pactl, so _t_hide removes it from PATH outright.
bt_reset
_t_unstub pactl
_t_hide pactl
if _verify_audio_sink "AA:BB:CC:DD:EE:FF"; then
_t_pass "_verify_audio_sink: returns success when pactl is not installed"
else
_t_fail "_verify_audio_sink: expected success when pactl is absent"
fi
_t_full_path
# The card shows up on the first probe.
bt_reset
_t_stub sleep 'exit 0'
_t_stub pactl 'echo "42 bluez_card.AA_BB_CC_DD_EE_FF module-bluez5-device.c"'
out="$(_verify_audio_sink "AA:BB:CC:DD:EE:FF" 2>&1)"
_t_contains "$out" "Bluetooth audio card detected" \
"_verify_audio_sink: reports the card once PipeWire lists it"
_t_eq "0" "$(_t_calls | grep -c '^sleep')" \
"_verify_audio_sink: does not sleep when the card is present on the first probe"
# The card never appears: five probes, then a warning and a non-zero return.
bt_reset
_t_stub sleep 'exit 0'
_t_stub pactl 'echo "42 alsa_card.pci-0000_00_1f.3 module-alsa-card.c"'
if out="$(_verify_audio_sink "AA:BB:CC:DD:EE:FF" 2>&1)"; then
_t_fail "_verify_audio_sink: expected a non-zero return when the card never appears"
else
_t_pass "_verify_audio_sink: returns non-zero when the card never appears"
fi
_t_contains "$out" "not found in PipeWire" \
"_verify_audio_sink: warns when the card never appears"
_t_eq "5" "$(_t_calls | grep -c '^sleep')" \
"_verify_audio_sink: retries five times before giving up"
echo
echo "bt_adapter (reset/probe): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,153 @@
#!/usr/bin/env bash
# Tests for lib/bt_audio.sh: check_pipewire_health, _run_as_user,
# _restart_pipewire_stack and set_audio_profile.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=bt_harness.sh
. "${SCRIPT_DIR}/bt_harness.sh"
# shellcheck source=../bt_audio.sh
. "${FIXES_DIR}/lib/bt_audio.sh"
# _stub_out NAME TEXT — stub NAME to print TEXT (kept out of a quoted string
# so no $ needs to survive quoting).
_stub_out() {
printf '%s\n' "$2" >"${DEV}/out_$1"
local body
body="cat \"\${LIB_TEST_DEV}/out_$1\""
_t_stub "$1" "$body"
}
# _record_restart ARGS... — stand-in for the real pipewire restarter.
_record_restart() {
printf 'restart_called %s\n' "$*" >>"${DEV}/fixes"
}
# --- check_pipewire_health --------------------------------------------------
# wpctl absent: the check is skipped. This host really has wpctl, so _t_hide
# removes it from PATH rather than relying on a stub dir that cannot mask it.
bt_reset
_t_unstub wpctl
_t_hide wpctl
out="$(check_pipewire_health 2>&1)"
_t_full_path
_t_contains "$out" "wpctl not found" \
"check_pipewire_health: skips the check when wpctl is not installed"
_t_eq "" "$(_t_fixes)" "check_pipewire_health: applies no fix when wpctl is absent"
# wpctl answers promptly: PipeWire is healthy. This case only passes because
# the timeout now runs INSIDE _run_as_user -- `timeout 3 _run_as_user ...`
# could never reach the stub, since timeout cannot invoke a shell function.
bt_reset
_t_stub wpctl 'exit 0'
_t_stub timeout 'shift; exec "$@"'
out="$(check_pipewire_health 2>&1)"
_t_contains "$out" "PipeWire is responsive" \
"check_pipewire_health: reports a responsive PipeWire"
_t_eq "" "$(_t_fixes)" "check_pipewire_health: applies no fix when PipeWire responds"
# wpctl fails (as a timeout would): the restart fix runs.
bt_reset
_t_stub wpctl 'exit 1'
out="$(
eval '_restart_pipewire_stack() { _record_restart "$@"; }'
check_pipewire_health 2>&1
)"
_t_contains "$out" "appears hung" \
"check_pipewire_health: warns when wpctl does not answer"
_t_contains "$out" "Restarting PipeWire + WirePlumber audio stack" \
"check_pipewire_health: applies the audio-stack restart fix"
_t_contains "$(_t_fixes)" "restart_called" \
"check_pipewire_health: calls the restart helper"
# --- _run_as_user -----------------------------------------------------------
bt_reset
_t_stub id 'echo 1000'
out="$(SUDO_USER="kuhy" _run_as_user echo hello 2>&1)"
_t_contains "$(_t_calls)" "sudo -u kuhy" \
"_run_as_user: runs the command as SUDO_USER when it is set"
_t_contains "$out" "hello" "_run_as_user: passes the command through to be run"
bt_reset
_t_stub id 'echo 1000'
_t_reset_calls
(
unset SUDO_USER
USER="kuhy" _run_as_user echo hi >/dev/null 2>&1
)
_t_contains "$(_t_calls)" "sudo -u kuhy" \
"_run_as_user: falls back to USER when SUDO_USER is unset"
# --- _restart_pipewire_stack ------------------------------------------------
bt_reset
_t_stub sleep 'exit 0'
out="$(_restart_pipewire_stack 2>&1)"
_t_contains "$(_t_calls)" "systemctl --user restart pipewire pipewire-pulse wireplumber" \
"_restart_pipewire_stack: restarts pipewire, pipewire-pulse and wireplumber"
_t_contains "$out" "Waiting for audio stack to initialize" \
"_restart_pipewire_stack: waits for the stack to come back"
# --- set_audio_profile ------------------------------------------------------
bt_reset
TARGET_MAC=""
out="$(set_audio_profile 2>&1)"
_t_eq "" "$out" "set_audio_profile: does nothing when TARGET_MAC is empty"
# pactl absent: returns before any probing. The host has a real pactl, so it
# has to leave PATH entirely.
bt_reset
TARGET_MAC="AA:BB:CC:DD:EE:FF"
_t_unstub pactl
_t_hide pactl
out="$(set_audio_profile 2>&1)"
_t_full_path
_t_eq "" "$out" "set_audio_profile: does nothing when pactl is not installed"
# No card for this device: the function reports and returns.
bt_reset
TARGET_MAC="AA:BB:CC:DD:EE:FF"
_t_stub sleep 'exit 0'
_stub_out pactl "Card #1
Name: alsa_card.pci-0000_00_1f.3
Active Profile: output:analog-stereo"
out="$(set_audio_profile 2>&1)"
_t_contains "$out" "No PipeWire audio card found" \
"set_audio_profile: reports when the device has no PipeWire card"
# SBC-XQ active: the profile is switched to plain a2dp-sink.
bt_reset
TARGET_MAC="AA:BB:CC:DD:EE:FF"
_t_stub sleep 'exit 0'
_stub_out pactl "Card #2
Name: bluez_card.AA_BB_CC_DD_EE_FF
Active Profile: a2dp-sink-sbc_xq"
out="$(set_audio_profile 2>&1)"
_t_contains "$out" "SBC-XQ codec active" \
"set_audio_profile: warns when the SBC-XQ codec is active"
_t_contains "$out" "Switching to standard SBC codec" \
"set_audio_profile: applies the codec-switch fix"
_t_contains "$(_t_calls)" \
"pactl set-card-profile bluez_card.AA_BB_CC_DD_EE_FF a2dp-sink" \
"set_audio_profile: switches the card to a2dp-sink"
# A healthy non-SBC-XQ profile is reported and left alone.
bt_reset
TARGET_MAC="AA:BB:CC:DD:EE:FF"
_t_stub sleep 'exit 0'
_stub_out pactl "Card #2
Name: bluez_card.AA_BB_CC_DD_EE_FF
Active Profile: a2dp-sink"
out="$(set_audio_profile 2>&1)"
_t_contains "$out" "Audio profile: a2dp-sink" \
"set_audio_profile: reports a healthy active profile"
_t_lacks "$out" "Switching to standard SBC codec" \
"set_audio_profile: applies no fix for a healthy profile"
echo
echo "bt_audio (pipewire): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
# Tests for lib/bt_audio.sh: connect_device and _check_connection_health.
# Split from test_bt_audio.sh for the 250-line cap.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=bt_harness.sh
. "${SCRIPT_DIR}/bt_harness.sh"
# bt_audio.sh calls _services_resolved, _verify_audio_sink and
# _full_adapter_reset_and_connect, which live in bt_adapter.sh.
# fix_bluetooth.sh sources both libs, so sourcing both here reproduces the
# real resolution order instead of stubbing those helpers out.
# shellcheck source=../bt_adapter.sh
. "${FIXES_DIR}/lib/bt_adapter.sh"
# shellcheck source=../bt_audio.sh
. "${FIXES_DIR}/lib/bt_audio.sh"
# _btctl_script — stub bluetoothctl with a body read from stdin. The stub
# itself reads its command from stdin too, exactly as the real tool does when
# driven by _btctl.
_btctl_script() {
_t_stub_stdin bluetoothctl
}
# The connect paths sleep 15-20s at a time; the stub keeps the suite fast
# while the calls stay recorded.
_no_sleep() {
_t_stub sleep 'exit 0'
}
# --- connect_device ---------------------------------------------------------
bt_reset
TARGET_MAC=""
out="$(connect_device 2>&1)"
_t_eq "" "$out" "connect_device: does nothing when TARGET_MAC is empty"
# Already connected: reports and returns without scanning.
bt_reset
_no_sleep
TARGET_MAC="AA:BB:CC:DD:EE:FF"
printf 'Device AA:BB:CC:DD:EE:FF\n\tConnected: yes\n' >"${DEV}/btctl_info"
_btctl_script <<'STUB_BODY'
read -r cmd rest
[[ "$cmd" == "info" ]] && cat "${LIB_TEST_DEV}/btctl_info"
# Real bluetoothctl consumes its whole stdin. Draining it here keeps the
# writing block from taking SIGPIPE partway through, which would silently
# stop it executing (and reading) the rest of its lines.
cat >/dev/null
exit 0
STUB_BODY
out="$(connect_device 2>&1)"
_t_contains "$out" "already connected" \
"connect_device: reports a device that is already connected"
_t_lacks "$out" "Scanning for" \
"connect_device: does not scan when the device is already connected"
# Paired but not connected: the direct-connect attempt runs and succeeds.
bt_reset
_no_sleep
TARGET_MAC="AA:BB:CC:DD:EE:FF"
printf 'Device AA:BB:CC:DD:EE:FF\n\tPaired: yes\n\tConnected: no\n' >"${DEV}/btctl_info"
_btctl_script <<'STUB_BODY'
read -r cmd rest
[[ "$cmd" == "info" ]] && cat "${LIB_TEST_DEV}/btctl_info"
# Real bluetoothctl consumes its whole stdin. Draining it here keeps the
# writing block from taking SIGPIPE partway through, which would silently
# stop it executing (and reading) the rest of its lines.
cat >/dev/null
exit 0
STUB_BODY
out="$(
eval '_check_connection_health() { return 0; }'
connect_device 2>&1
)"
_t_contains "$out" "already paired. Trying direct connect" \
"connect_device: tries a direct connect for an already-paired device"
_t_lacks "$out" "Scanning for" \
"connect_device: does not scan when the direct connect succeeds"
# Direct connect fails, and the rescan does not find the device.
bt_reset
_no_sleep
TARGET_MAC="AA:BB:CC:DD:EE:FF"
printf 'Device AA:BB:CC:DD:EE:FF\n\tPaired: yes\n\tConnected: no\n' >"${DEV}/btctl_info"
_btctl_script <<'STUB_BODY'
read -r cmd rest
[[ "$cmd" == "info" ]] && cat "${LIB_TEST_DEV}/btctl_info"
# Real bluetoothctl consumes its whole stdin. Draining it here keeps the
# writing block from taking SIGPIPE partway through, which would silently
# stop it executing (and reading) the rest of its lines.
cat >/dev/null
exit 0
STUB_BODY
if out="$(
eval '_check_connection_health() { return 1; }'
connect_device 2>&1
)"; then
_t_fail "connect_device: expected failure when the device is never found"
else
_t_pass "connect_device: returns non-zero when the device is never found"
fi
_t_contains "$out" "Removing stale pairing for fresh start" \
"connect_device: removes the stale pairing after a failed direct connect"
_t_contains "$out" "Scanning for AA:BB:CC:DD:EE:FF" \
"connect_device: falls back to a scan after a failed direct connect"
_t_contains "$out" "not found during scan" \
"connect_device: reports a device that never appears in the scan"
# Unpaired device that IS found by the scan: pair, trust, connect all run.
bt_reset
_no_sleep
TARGET_MAC="AA:BB:CC:DD:EE:FF"
_btctl_script <<'STUB_BODY'
read -r cmd rest
case "$cmd" in
info) printf "Device AA:BB:CC:DD:EE:FF\n\tPaired: no\n\tConnected: no\n" ;;
devices) echo "Device AA:BB:CC:DD:EE:FF JBL Charge 5" ;;
esac
cat >/dev/null
exit 0
STUB_BODY
out="$(
eval '_check_connection_health() { return 0; }'
connect_device 2>&1
)"
_t_contains "$out" "Device found during scan" \
"connect_device: reports the device once the scan finds it"
_t_contains "$out" "Pairing..." "connect_device: pairs a device found by the scan"
_t_contains "$out" "Trusting..." "connect_device: trusts the device so it auto-reconnects"
_t_contains "$out" "Connecting..." "connect_device: connects after pairing and trusting"
# Found by the scan, but the connection never becomes healthy.
bt_reset
_no_sleep
TARGET_MAC="AA:BB:CC:DD:EE:FF"
_btctl_script <<'STUB_BODY'
read -r cmd rest
case "$cmd" in
info) printf "Device AA:BB:CC:DD:EE:FF\n\tPaired: no\n\tConnected: no\n" ;;
devices) echo "Device AA:BB:CC:DD:EE:FF JBL Charge 5" ;;
esac
cat >/dev/null
exit 0
STUB_BODY
if out="$(
eval '_check_connection_health() { return 1; }'
connect_device 2>&1
)"; then
_t_fail "connect_device: expected failure when the connection stays unhealthy"
else
_t_pass "connect_device: returns non-zero when the connection stays unhealthy"
fi
_t_contains "$out" "Connection to AA:BB:CC:DD:EE:FF failed" \
"connect_device: reports the failure after pairing and connecting"
echo
echo "bt_audio (connect): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,122 @@
#!/usr/bin/env bash
# Tests for lib/bt_audio.sh: _check_connection_health.
# Split from test_bt_audio.sh for the 250-line cap.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=bt_harness.sh
. "${SCRIPT_DIR}/bt_harness.sh"
# _check_connection_health calls _services_resolved, _verify_audio_sink and
# _full_adapter_reset_and_connect, all defined in bt_adapter.sh, which
# fix_bluetooth.sh also sources.
# shellcheck source=../bt_adapter.sh
. "${FIXES_DIR}/lib/bt_adapter.sh"
# shellcheck source=../bt_audio.sh
. "${FIXES_DIR}/lib/bt_audio.sh"
# _record_reset ARGS... — stand-in for the real full-adapter reset.
_record_reset() {
printf 'reset_called %s\n' "$*" >>"${DEV}/fixes"
}
# _info_says TEXT — stub bluetoothctl so `_btctl info` returns TEXT.
_info_says() {
printf '%s\n' "$1" >"${DEV}/btctl_info"
_t_stub_stdin bluetoothctl <<'STUB_BODY'
read -r cmd rest
[[ "$cmd" == "info" ]] && cat "${LIB_TEST_DEV}/btctl_info"
# Real bluetoothctl consumes its whole stdin. Draining it here keeps the
# writing block from taking SIGPIPE partway through, which would silently
# stop it executing (and reading) the rest of its lines.
cat >/dev/null
exit 0
STUB_BODY
}
# Not connected at all: fails immediately, without probing services.
bt_reset
_t_stub sleep 'exit 0'
_info_says "Device AA:BB:CC:DD:EE:FF
Connected: no"
if _check_connection_health "AA:BB:CC:DD:EE:FF" >/dev/null 2>&1; then
_t_fail "_check_connection_health: expected failure when not connected"
else
_t_pass "_check_connection_health: fails when the device is not connected"
fi
_t_lacks "$(_t_calls)" "dbus-send" \
"_check_connection_health: does not probe services when not connected"
# Connected with services resolved on the first probe: healthy.
bt_reset
_t_stub sleep 'exit 0'
_info_says "Device AA:BB:CC:DD:EE:FF
Connected: yes"
_t_stub dbus-send 'echo " variant boolean true"'
_t_stub pactl 'echo "42 bluez_card.AA_BB_CC_DD_EE_FF module-bluez5-device.c"'
if out="$(_check_connection_health "AA:BB:CC:DD:EE:FF" 2>&1)"; then
_t_pass "_check_connection_health: succeeds when connected with services resolved"
else
_t_fail "_check_connection_health: expected success when services resolve"
fi
_t_contains "$out" "with A2DP services resolved" \
"_check_connection_health: reports resolved A2DP services"
_t_lacks "$out" "Full adapter reset" \
"_check_connection_health: does not reset the adapter when services resolve"
# Connected but services never resolve: three probes, then the full reset,
# and after the reset they resolve.
bt_reset
_t_stub sleep 'exit 0'
_info_says "Device AA:BB:CC:DD:EE:FF
Connected: yes"
: >"${DEV}/dbus_calls"
_t_stub_stdin dbus-send <<'STUB_BODY'
n=$(cat "${LIB_TEST_DEV}/dbus_calls" 2>/dev/null || echo 0)
n=$((n + 1))
echo "$n" >"${LIB_TEST_DEV}/dbus_calls"
if ((n > 3)); then
echo " variant boolean true"
else
echo " variant boolean false"
fi
exit 0
STUB_BODY
_t_stub pactl 'echo "42 bluez_card.AA_BB_CC_DD_EE_FF module-bluez5-device.c"'
if out="$(
eval '_full_adapter_reset_and_connect() { _record_reset "$@"; }'
_check_connection_health "AA:BB:CC:DD:EE:FF" 2>&1
)"; then
_t_pass "_check_connection_health: succeeds once services resolve after a reset"
else
_t_fail "_check_connection_health: expected success after the adapter reset"
fi
_t_contains "$out" "services not resolved (stale HCI link state)" \
"_check_connection_health: warns about a stale HCI link state"
_t_contains "$out" "Full adapter reset to fix stale link" \
"_check_connection_health: applies the full adapter reset fix"
_t_contains "$out" "resolved after reset" \
"_check_connection_health: reports services resolving after the reset"
_t_contains "$(_t_fixes)" "reset_called AA:BB:CC:DD:EE:FF" \
"_check_connection_health: passes the MAC to the adapter reset"
# Services never resolve, even after the reset: the function fails.
bt_reset
_t_stub sleep 'exit 0'
_info_says "Device AA:BB:CC:DD:EE:FF
Connected: yes"
_t_stub dbus-send 'echo " variant boolean false"'
if out="$(
eval '_full_adapter_reset_and_connect() { _record_reset "$@"; }'
_check_connection_health "AA:BB:CC:DD:EE:FF" 2>&1
)"; then
_t_fail "_check_connection_health: expected failure when services never resolve"
else
_t_pass "_check_connection_health: fails when services never resolve after a reset"
fi
_t_contains "$(_t_fixes)" "reset_called" \
"_check_connection_health: still attempts the reset before giving up"
echo
echo "bt_audio (health): ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -29,13 +29,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# _lsusb_line TEXT — stub lsusb to emit a single line of TEXT.
_lsusb_line() {
printf '%s\n' "$1" >"${DEV}/lsusb_out"
local body
body="$(
cat <<'LSUSB_BODY'
cat "${LIB_TEST_DEV}/lsusb_out"
LSUSB_BODY
)"
_t_stub lsusb "$body"
_t_stub_cat lsusb lsusb_out
}
# No bluetooth device in lsusb at all: the function returns before any lookup.

View File

@ -0,0 +1,110 @@
#!/usr/bin/env bash
# Tests for lib/ubuntu_perf_more.sh: fix_journal, fix_snap_startup and run_undo.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=ubuntu_perf_harness.sh
. "${SCRIPT_DIR}/ubuntu_perf_harness.sh"
# shellcheck source=../ubuntu_perf_more.sh
. "${FIXES_DIR}/lib/ubuntu_perf_more.sh"
# --- fix_journal ------------------------------------------------------------
# First run: the drop-in does not exist, so it is written and journald
# restarted. JOURNALD_CONF_DIR points into the tmpdir, so /etc is untouched.
ubuntu_reset
fix_journal
dropin="${JOURNALD_CONF_DIR}/size-limit.conf"
_t_contains "$(cat "$dropin" 2>/dev/null)" "SystemMaxUse=300M" \
"fix_journal: writes the 300M size cap into the journald drop-in"
_t_contains "$(cat "$dropin" 2>/dev/null)" "[Journal]" \
"fix_journal: writes a valid [Journal] section header"
_t_contains "$(_t_calls)" "journalctl --vacuum-size=300M" \
"fix_journal: vacuums the existing journal down to the cap"
_t_contains "$(_t_calls)" "systemctl restart systemd-journald" \
"fix_journal: restarts journald so the cap takes effect"
_t_contains "$(_t_undo)" "rm -f /etc/systemd/journald.conf.d/size-limit.conf" \
"fix_journal: records how to remove the drop-in in the undo script"
_t_contains "$(_t_undo)" "systemctl restart systemd-journald" \
"fix_journal: records the journald restart in the undo script"
# Second run with the cap already in place: nothing is rewritten.
ubuntu_reset
mkdir -p "${JOURNALD_CONF_DIR}"
printf '[Journal]\nSystemMaxUse=300M\n' >"${JOURNALD_CONF_DIR}/size-limit.conf"
out="$(fix_journal 2>&1)"
_t_contains "$out" "already configured" \
"fix_journal: skips when the size cap is already configured"
_t_eq "" "$(_t_calls)" "fix_journal: runs no command when the cap already exists"
_t_eq "" "$(_t_undo)" "fix_journal: adds no undo step when it changed nothing"
# A drop-in that exists but caps a DIFFERENT size is rewritten.
ubuntu_reset
mkdir -p "${JOURNALD_CONF_DIR}"
printf '[Journal]\nSystemMaxUse=1G\n' >"${JOURNALD_CONF_DIR}/size-limit.conf"
fix_journal
_t_contains "$(cat "${JOURNALD_CONF_DIR}/size-limit.conf")" "SystemMaxUse=300M" \
"fix_journal: rewrites a drop-in that caps a different size"
# --- fix_snap_startup -------------------------------------------------------
# The timer is enabled: it gets disabled and stopped, and an undo recorded.
ubuntu_reset
_t_stub systemctl 'exit 0'
fix_snap_startup
_t_contains "$(_t_calls)" "systemctl disable snapd.snap-repair.timer" \
"fix_snap_startup: disables the snap repair timer when it is enabled"
_t_contains "$(_t_calls)" "systemctl stop snapd.snap-repair.timer" \
"fix_snap_startup: stops the snap repair timer as well as disabling it"
_t_contains "$(_t_undo)" "systemctl enable snapd.snap-repair.timer" \
"fix_snap_startup: records how to re-enable the timer in the undo script"
# Already disabled: nothing to do.
ubuntu_reset
_t_stub systemctl 'exit 1'
out="$(fix_snap_startup 2>&1)"
_t_contains "$out" "already disabled" \
"fix_snap_startup: reports a timer that is already disabled"
_t_lacks "$(_t_calls)" "systemctl disable" \
"fix_snap_startup: does not re-disable an already-disabled timer"
_t_eq "" "$(_t_undo)" "fix_snap_startup: adds no undo step when it changed nothing"
# --- run_undo ---------------------------------------------------------------
#
# run_undo ends in `exit`, so each case runs it in a subshell -- a command
# substitution already provides one, and the exit only ends that subshell.
# UNDO_DIR points into the tmpdir, so the real /root is never read.
ubuntu_reset
out="$( (run_undo) 2>&1)"
rc=$?
_t_eq "1" "$rc" "run_undo: exits non-zero when no undo script exists"
_t_contains "$out" "No undo script found" \
"run_undo: reports that no undo script was found"
ubuntu_reset
cat >"${UNDO_DIR}/undo_ubuntu_performance_20260101_000000.sh" <<'UNDO'
#!/bin/bash
echo "undo script ran"
UNDO
out="$( (run_undo) 2>&1)"
rc=$?
_t_eq "0" "$rc" "run_undo: exits 0 after running the undo script"
_t_contains "$out" "undo script ran" "run_undo: actually executes the undo script"
_t_contains "$out" "All changes reversed" "run_undo: reports success"
_t_contains "$out" "Reboot recommended" "run_undo: recommends a reboot afterwards"
# With several undo scripts present, the most recent one is chosen.
ubuntu_reset
echo 'echo "older"' >"${UNDO_DIR}/undo_ubuntu_performance_20260101_000000.sh"
sleep 0.01
echo 'echo "newest"' >"${UNDO_DIR}/undo_ubuntu_performance_20260601_120000.sh"
touch -d '2026-01-01' "${UNDO_DIR}/undo_ubuntu_performance_20260101_000000.sh"
out="$( (run_undo) 2>&1)"
_t_contains "$out" "newest" "run_undo: picks the most recent undo script"
_t_lacks "$out" "older" "run_undo: does not run an older undo script"
echo
echo "ubuntu_perf_more: ${PASS} passed, ${FAIL} failed"
((FAIL == 0))

View File

@ -0,0 +1,64 @@
#!/usr/bin/env bash
# lib/tests/ubuntu_perf_harness.sh — shared setup for the ubuntu performance
# lib tests (ubuntu_perf_more.sh, ubuntu_perf_fixes.sh).
#
# Sourced, not executed. Builds on lib_test_core.sh and adds what these libs
# read from their entry script, fix_ubuntu_performance.sh:
#
# * UNDO_SCRIPT, pointed into the throwaway tmpdir, and add_undo which
# appends to it -- both live in the entry script, not in any lib;
# * the real log_*/has_cmd helpers, via scripts/lib/common.sh.
#
# JOURNALD_CONF_DIR and UNDO_DIR are the overrides ubuntu_perf_more.sh exposes
# so its two absolute write targets (/etc/systemd/journald.conf.d and /root)
# stay out of reach. run_all.sh runs UN-jailed in ci_mirror.sh and in CI, so a
# bind mount would protect only the coverage run.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FIXES_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
REPO_ROOT="$(cd "${FIXES_DIR}/../../../.." && pwd)"
# shellcheck source=lib_test_core.sh
. "${SCRIPT_DIR}/lib_test_core.sh"
# shellcheck source=../../../../lib/common.sh
. "${REPO_ROOT}/linux_configuration/scripts/lib/common.sh"
# --- globals and helpers owned by fix_ubuntu_performance.sh -----------------
# Read by the libs under test, never by this harness, so static analysis
# cannot see the use; export makes the intent explicit.
export UNDO_SCRIPT="${TEST_TMPDIR}/undo.sh"
export JOURNALD_CONF_DIR="${TEST_TMPDIR}/journald.conf.d"
export UNDO_DIR="${TEST_TMPDIR}/undo_dir"
# Verbatim from fix_ubuntu_performance.sh.
add_undo() {
echo "$1" >>"$UNDO_SCRIPT"
}
_ubuntu_default_stubs() {
local tool
for tool in systemctl journalctl snap apt-get update-grub sysctl \
swapoff swapon; do
_t_stub "$tool" 'exit 0'
done
}
# ubuntu_reset — start a test group from "nothing has happened yet".
ubuntu_reset() {
_t_reset_calls
rm -rf "${JOURNALD_CONF_DIR}" "${UNDO_DIR}"
mkdir -p "${JOURNALD_CONF_DIR}" "${UNDO_DIR}"
: >"$UNDO_SCRIPT"
_t_full_path
_ubuntu_default_stubs
}
# _t_undo — the undo script's contents this round.
_t_undo() {
cat "$UNDO_SCRIPT" 2>/dev/null || true
}
ubuntu_reset

View File

@ -9,8 +9,10 @@
# Fix 6: Journal vacuum + permanent size cap
# ===================================================================
fix_journal() {
# Create permanent size cap via drop-in
local dropin_dir="/etc/systemd/journald.conf.d"
# Create permanent size cap via drop-in. JOURNALD_CONF_DIR defaults to the
# real path and is only overridden by the test suite, which must not write
# to /etc: lib/tests/run_all.sh runs un-jailed in ci_mirror.sh and in CI.
local dropin_dir="${JOURNALD_CONF_DIR:-/etc/systemd/journald.conf.d}"
local dropin_file="$dropin_dir/size-limit.conf"
if [[ -f $dropin_file ]] && grep -q 'SystemMaxUse=300M' "$dropin_file"; then
@ -61,10 +63,10 @@ fix_snap_startup() {
run_undo() {
local latest_undo
# shellcheck disable=SC2012
latest_undo=$(ls -1t /root/undo_ubuntu_performance_*.sh 2>/dev/null | head -1)
latest_undo=$(ls -1t "${UNDO_DIR:-/root}"/undo_ubuntu_performance_*.sh 2>/dev/null | head -1)
if [[ -z ${latest_undo:-} ]]; then
log_error "No undo script found in /root/"
log_error "No undo script found in ${UNDO_DIR:-/root}/"
exit 1
fi

View File

@ -66,6 +66,27 @@ def traced_paths(trace_dir: Path, subject: str) -> list[Path]:
return found
# A line holding only a group's closing brace plus an operator: `} |`,
# `} >>file`, `} <in`, `} &>log`. kcov instruments these, but bash attributes
# no statement to them -- each command INSIDE the group is attributed to its
# own line, and a pipe's right-hand side to its own line, leaving the brace
# line with nothing. Anchoring on a leading `}` is what keeps this safe: a
# one-liner `{ echo a; } >file` begins with `{` and is a real statement, and a
# bare `}` closing a function carries no operator.
_CLOSING_BRACE_OP = re.compile(r"^\s*\}\s*(\||>>?|<|&>)")
# An assignment whose value opens a multi-line array literal, e.g.
# `local -a candidates=(` or `FILES=(`. bash reports the WHOLE assignment at
# this opening line and never emits the element lines or the closing paren, so
# those are data. Symmetric with the multi-line-quote case: the opening line
# is the statement, everything up to the closing paren is not.
_ARRAY_OPEN = re.compile(
r"^\s*(?:local\s+|declare\s+|readonly\s+|export\s+)*"
r"(?:-[a-zA-Z]+\s+)*"
r"[A-Za-z_][A-Za-z0-9_]*\+?=\(\s*(?:#.*)?$"
)
def continuation_lines(source: Path) -> set[int]:
"""Return lines that are *inside* a multi-line quoted argument.
@ -75,35 +96,71 @@ def continuation_lines(source: Path) -> set[int]:
them as executable at all, which is the correct reading: they are data
inside an argument, not statements.
Detected by tracking quote state across the file: any line that *begins*
while a quote opened on an earlier line is still open is a continuation.
Only the opening line of such a construct is a statement.
Two shapes qualify:
* a line that *begins* while a quote opened on an earlier line is still
open -- the continuation of a multi-line quoted argument. Only the
opening line of such a construct is a statement.
* a line holding just a group's closing brace and an operator (``} |``,
``} >>file``). See ``_CLOSING_BRACE_OP``.
* the element lines and closing paren of a multi-line array literal.
See ``_ARRAY_OPEN``.
"""
inside: set[int] = set()
quote: str | None = None
in_array = False
for number, raw in enumerate(
source.read_text(encoding="utf-8", errors="replace").splitlines(), start=1
):
if quote is not None:
if quote is not None or in_array:
inside.add(number)
index = 0
while index < len(raw):
char = raw[index]
if quote is None:
if char == "#":
# A comment outside quotes ends the line's significance.
break
if char == "\\":
index += 2
continue
if char in ("'", '"'):
quote = char
elif char == quote:
quote = None
elif quote == '"' and char == "\\":
# Only double quotes honour backslash escapes; inside single
# quotes a backslash is a literal character.
starts_open = quote is None and not in_array and bool(_ARRAY_OPEN.match(raw))
quote = _quote_after(raw, quote)
if in_array and quote is None and _closes_array(raw):
in_array = False
elif starts_open:
in_array = True
if quote is None and not in_array and _CLOSING_BRACE_OP.match(raw):
inside.add(number)
return inside
def _closes_array(raw: str) -> bool:
"""Return True when ``raw`` closes a multi-line array literal.
Only a ``)`` that is not itself inside quotes counts, so an element like
``"a(b)"`` does not end the literal. Quote state is recomputed from the
start of the line for each candidate rather than pattern-matched.
"""
for index, char in enumerate(raw):
if char == ")" and _quote_after(raw[:index], None) is None:
return True
return False
def _quote_after(raw: str, quote: str | None) -> str | None:
"""Return the open-quote state at the end of ``raw``, given its state at the start.
``None`` means no quote is open. Escapes are honoured outside quotes and
inside double quotes, but not inside single quotes, which take a
backslash literally.
"""
index = 0
while index < len(raw):
char = raw[index]
if quote is None:
if char == "#":
# A comment outside quotes ends the line's significance.
break
if char == "\\":
index += 2
continue
index += 1
return inside
if char in ("'", '"'):
quote = char
elif char == quote:
quote = None
elif quote == '"' and char == "\\":
index += 2
continue
index += 1
return quote

View File

@ -75,19 +75,14 @@ linux_configuration/scripts/single_use/features/lib/wg_keys.sh
linux_configuration/scripts/single_use/features/lib/wg_sshd.sh
linux_configuration/scripts/single_use/fixes/lib/arch_cpu.sh
linux_configuration/scripts/single_use/fixes/lib/arch_hardware.sh
linux_configuration/scripts/single_use/fixes/lib/arch_perf_fixes.sh
linux_configuration/scripts/single_use/fixes/lib/arch_perf_probes.sh
linux_configuration/scripts/single_use/fixes/lib/arch_perf_report.sh
linux_configuration/scripts/single_use/fixes/lib/arch_sysctl.sh
linux_configuration/scripts/single_use/fixes/lib/bt_adapter.sh
linux_configuration/scripts/single_use/fixes/lib/bt_audio.sh
linux_configuration/scripts/single_use/fixes/lib/hosts_guard_migrate.sh
linux_configuration/scripts/single_use/fixes/lib/hosts_guard_rollback.sh
linux_configuration/scripts/single_use/fixes/lib/nvidia_config.sh
linux_configuration/scripts/single_use/fixes/lib/pacman_hook_stall_setup.sh
linux_configuration/scripts/single_use/fixes/lib/thorium_repairs.sh
linux_configuration/scripts/single_use/fixes/lib/ubuntu_perf_fixes.sh
linux_configuration/scripts/single_use/fixes/lib/ubuntu_perf_more.sh
linux_configuration/scripts/single_use/fresh-install/lib/packages.sh
linux_configuration/scripts/single_use/lib/joplin_server.sh
linux_configuration/scripts/single_use/misc/testsAndMisc-bash/lib/clean_audio_filters.sh

View File

@ -79,6 +79,76 @@ def test_multiline_double_quote_marks_inner_lines(
assert mod.continuation_lines(src) == {2, 3}
def test_closing_brace_with_pipe_is_a_continuation(
mod: ModuleType, tmp_path: Path
) -> None:
"""`} |` carries no statement: bash attributes each part to its own line."""
src = _write(
tmp_path,
"a.sh",
"{\n\techo a\n\techo b\n} |\n\tconsumer\n",
)
assert mod.continuation_lines(src) == {4}
def test_closing_brace_with_redirect_is_a_continuation(
mod: ModuleType, tmp_path: Path
) -> None:
"""The arch_perf_report.sh shape: a group appended to a report file."""
src = _write(
tmp_path,
"a.sh",
'{\n\techo a\n} >>"$REPORT_FILE"\necho after\n',
)
assert mod.continuation_lines(src) == {3}
def test_multiline_array_marks_elements_and_paren(
mod: ModuleType, tmp_path: Path
) -> None:
"""bash reports the whole assignment at the opening line; elements are data."""
src = _write(
tmp_path,
"a.sh",
'local -a c=(\n\t"one"\n\t"two"\n)\nfor i in "${c[@]}"; do :; done\n',
)
assert mod.continuation_lines(src) == {2, 3, 4}
def test_single_line_array_is_a_statement(mod: ModuleType, tmp_path: Path) -> None:
"""`x=(a b)` closes on its own line and stays a statement."""
src = _write(tmp_path, "a.sh", "x=(a b)\necho after\n")
assert mod.continuation_lines(src) == set()
def test_array_element_containing_a_paren_does_not_close_it(
mod: ModuleType, tmp_path: Path
) -> None:
"""A `)` inside quotes must not end the literal early."""
src = _write(tmp_path, "a.sh", 'x=(\n\t"a(b)"\n\t"c"\n)\necho after\n')
assert mod.continuation_lines(src) == {2, 3, 4}
def test_command_substitution_is_not_an_array(mod: ModuleType, tmp_path: Path) -> None:
"""`x=$(cmd` is a substitution, not an array literal, and must not match."""
src = _write(tmp_path, "a.sh", "x=$(echo hi)\necho after\n")
assert mod.continuation_lines(src) == set()
def test_bare_closing_brace_is_a_statement(mod: ModuleType, tmp_path: Path) -> None:
"""A `}` closing a function has no operator and must stay in the count."""
src = _write(tmp_path, "a.sh", "f() {\n\techo a\n}\nf\n")
assert mod.continuation_lines(src) == set()
def test_single_line_group_with_redirect_is_a_statement(
mod: ModuleType, tmp_path: Path
) -> None:
"""`{ echo a; } >file` begins with `{`, so the whole line is a statement."""
src = _write(tmp_path, "a.sh", '{ echo a; } >"$out"\necho after\n')
assert mod.continuation_lines(src) == set()
def test_comment_outside_quotes_ends_the_line(mod: ModuleType, tmp_path: Path) -> None:
"""An apostrophe inside a comment must not open a quote state."""
src = _write(tmp_path, "a.sh", "# don't be fooled\necho after\n")