Commit Graph

92 Commits

Author SHA1 Message Date
071963b92b Fix: stop the Flutter SDK reading your own repo as itself inside git hooks
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
`git commit`/`git push` export GIT_DIR to every hook they run, and the
flutter tool shells out to git to identify its own SDK. `git -C
"$FLUTTER_ROOT" rev-parse HEAD` in bin/internal/shared.sh does not beat an
inherited GIT_DIR -- `-C` only changes directory, GIT_DIR overrides
repository discovery outright:

    $ git -C /opt/flutter rev-parse HEAD
    058e0af2c2...                                  <- Flutter's HEAD
    $ GIT_DIR=~/diet-guard/.git git -C /opt/flutter rev-parse HEAD
    84bd550331...                                  <- diet-guard's HEAD

So inside a hook, flutter reports the project as the SDK:

    Flutter 3.47.0-0.1.pre • channel main • https://github.com/kuhyx/diet-guard

pub then resolves the SDK as 0.0.0-unknown and every version constraint
becomes unsatisfiable. flutter also writes that into its own version cache,
so the wrong answer outlives the hook and follows the next caller into an
unrelated repository -- which is why the identical command passes when you
re-run it by hand and fails again on the next push.

diet-guard's pre-push gate hit this today. Clearing the variables per call in
each hook works, and screen-locker and diet-guard now do, but only for as
long as every future hook author remembers -- deployment hygiene, not a fix.
This installs a wrapper ahead of /usr/bin on PATH that strips them for every
caller in every repo, covering both flutter and dart. It removes its own
directory from PATH before exec so the Flutter entry point's internal `which
flutter` cannot loop back into it, and it verifies itself by running flutter
against a throwaway poisoned GIT_DIR and failing unless the real SDK comes
back.

Not patching bin/internal/shared.sh: that file belongs to the flutter-bin
package, so the next update would silently restore the bug. Upstream already
unsets these variables in content_aware_hash.sh and update_engine_version.sh,
just not in the version path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 15:39:33 +02:00
d91c0ab0e9 fix(i3): repair the dead idle-inhibitor autostart and make it a singleton
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
The i3 `exec` line pointed at
/home/kuchy/linux-configuration/scripts/utils/turn_off_auto_idle_screen_shutdown.sh
- a typo'd home ("kuchy") *and* a path that stopped existing when the repo
was reorganised in db6276b. The exec has been failing silently at every
login ever since, so the idle inhibitor was simply not running: a controller
was connected with no "idle-off" lock held, meaning the screen could blank
and lock during controller gaming, which is exactly what the line exists to
prevent.

Point it at the script's real location.

Also make --watch-controller a singleton. It is a long-lived watcher started
from an i3 `exec`, and i3 re-runs those on every `i3-msg restart`, so each
restart would leave another watcher holding a redundant inhibitor for the
rest of the session. One flock, held for the life of the watcher.

Verified: the watcher now holds
  idle-off 1000 kuhy <pid> systemd-inhibit idle "game controller connected"
and a second invocation declines instead of stacking a second inhibitor.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-25 19:57:57 +02:00
4f2c82fee7 Add overnight power-save to night-lockdown; harden dnsmasq with a watchdog
Some checks failed
Pre-commit checks / pre-commit (push) Has been cancelled
Shell tests / shell-tests (push) Has been cancelled
Shell tests / arch-tests (push) Has been cancelled
Caps CPU (amd-pstate-epp) and GPU (nvidia-smi power limit) during the
existing night-lockdown window instead of migrating services to a
Raspberry Pi (tried, abandoned after SSH auth failed). A more aggressive
GPU PCI-unbind option is built but left disabled by default.

Also fixes an unrelated live incident found while testing: dnsmasq (this
PC's LAN DHCP/DNS server) had died with zero error logged, breaking WiFi
for every device on the network. Added a watchdog timer mirroring the
existing shutdown-timer-monitor-watchdog pattern, and whitelisted the
Tapo smart plug app so the overnight power reading is checkable during
the phone's curfew window.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 11:58:37 +02:00
5d4d3b9e24 night-lockdown: stop firing the morning alarm on a fixed hour
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
The unlock script started morning-routine.service on every staggered trigger
(05:00/05:15/05:30/06:00/07:00) on alarm days. That was a workaround for the
always-on lockdown removing the hibernate/resume event the alarm used to ride
on — reasonable when nothing else could fire it.

Something else fires it now. wake-alarm-trigger.timer ticks every minute and
starts morning-routine.service at the time the phone synced, with a catch-up
window for a suspended or just-booted machine. Keeping both meant two
independent triggers, one of which ignores the phone entirely.

That is not hypothetical: on 2026-07-20 the phone was set to 08:00 and the
alarm went off at 07:00, started here, with no wake-alarm-trigger "Firing" line
in the journal at all. The 08:00 fire then landed as a no-op because this
07:00 run had left morning-routine.service still active.

Drop maybe_start_morning_alarm() and both call sites, plus the config that
went dead with it (ALARM_DAYS_DOW, MORNING_ROUTINE_UNIT, the alarm_started_date
marker). MIN_WAKE_AFTER_LOCKDOWN_HOURS stays — the wake-floor trigger uses it.
The lockdown's actual job — console/GUI restore, unmute, unmasking the login
surface — is untouched.

The only starters of morning-routine.service left are wake-alarm-trigger.timer
(primary) and the system-sleep hook (resume backstop).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 08:50:45 +02:00
836f4ef2de Add network diagnostics: duty-cycle and line-speed probes
Diagnosing "Steam downloads are slow" kept pointing at the ISP because
every averaged measurement showed a steady ~170 Mbps. Sampling at 1s
instead of 5s showed that plateau does not exist: the link alternates
between ~450 Mbps bursts and multi-second stalls. Effective rate is
burst x duty_cycle, and only the second factor was wrong.

steam-download-duty.sh reports those two factors separately, which is
what the Steam UI cannot do. line-speed-probe.sh separates burst from
sustained throughput, because a single stream tops out near 180 Mbps on
this line and reads convincingly as ISP shaping when it is not — a
many-connection swarm reaches 986 Mbps with zero retransmits.

Arithmetic is extracted into pure helpers with main() behind a
BASH_SOURCE guard so the bats suite can source them without starting a
measurement. install.sh installs bats and links both scripts onto PATH.

Note: no CI workflow runs .sh/.bats tests, including the four shell
tests that predate this one, so the suite is manual-only for now.
2026-07-19 18:46:18 +02:00
937c597c80 remove(digital-wellbeing): delete unusable focus-mode daemon entirely
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
Steam/browser mutual-exclusion daemon was unusable in its current state.
Removed all code, install tooling, and every reference across
install_core_system.sh, check_and_enable_services.sh, the security
hardening test suite, and CLAUDE.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19 13:15:04 +02:00
88eda8dc51 fix(night-lockdown): schedule a dynamic wake-floor trigger for any shutdown time
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
The alarm floor (lockdown-entry + 8h) from the previous commit still relied
on the fixed 05:00/05:15/05:30/06:00/07:00 unlock triggers to ever re-check
it. Shutdown time is configurable (/etc/shutdown-schedule.conf, changed by
the screen_locker sick-day feature) and can vary night to night, so a late
enough lockdown (e.g. 23:30) pushes the floor past every remaining trigger
(07:30 > 07:00) and the alarm would silently never fire that morning.

Enter script now schedules a transient systemd-run --on-calendar one-shot
timer at exactly lockdown-entry + MIN_WAKE_AFTER_LOCKDOWN_HOURS, computed
from the real lockdown timestamp rather than assumed shutdown hours. It
re-runs the idempotent, self-dedup'd unlock script, guaranteeing the alarm
gets a correctly-timed chance regardless of what time lockdown started.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S4YWZhDcEUMUi8cyw9AzTR
2026-07-18 06:51:26 +02:00
e393207e3a fix(night-lockdown): close console-blank gap, recover DP link, floor wake alarm
The 23:00 lockdown -> 05:00 unlock cycle exposed three live bugs: a visible
console-text flash before the screen went black (blank_console only ran once
systemctl stop lightdm.service fully returned, leaving a gap), DP-0 needing a
manual xrandr/replug after wake, and the morning alarm firing only 6h after a
late lockdown entry instead of waiting a full 8h.

- Blank the console continuously in a background poller for the whole GUI
  teardown instead of a single after-the-fact call.
- Retry autorandr --change against a saved profile after lightdm restarts.
- Stamp lockdown-entry time and gate the alarm on entry + 8h, decoupled from
  the console/GUI-restore idempotency so it can fire on a later staggered
  trigger instead of only the first one.
- Add DRY_RUN NOTE banners so a clean dry run is never mistaken for proof the
  console-blank and autorandr fixes work for real (they need a live cycle).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S4YWZhDcEUMUi8cyw9AzTR
2026-07-18 06:44:17 +02:00
e0f62d699a fix(wellbeing): split focus_mode_daemon to satisfy the 500-line limit
focus_mode_daemon.py has been 509 lines since 22e22c1, over the repo's
cap. It went unnoticed because the Python tests workflow only triggers on
python_pkg/** changes, so that commit never ran CI; the next commit to
touch python_pkg/ exposed it and turned main red.

Extract configuration, logging, notification, /proc process inspection and
the killers into _focus_mode_lib.py, leaving the daemon its policy: the
whitelist, the FocusMode state machine, and main(). log/notify move with
the process code that calls them, so the dependency runs one way and there
is no cycle. The helper is underscore-prefixed and registered in pylint's
init-hook path, mirroring the existing usage_report.py / _usage_report_*.py
sibling-import precedent.

The daemon runs from a symlink in /usr/local/bin, so a sibling import only
works if Python resolves that symlink before setting sys.path[0]; verified
that it does, and the installer symlinks rather than copies, so the sibling
travels with it. Confirmed against the running service: restarts clean and
resumes enforcing, process detection unchanged, status output matches the
pre-split version.

Structural only; no behaviour change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RG3eEn8rwZbcXaJrKJxdv8
2026-07-17 17:36:30 +02:00
28779586eb fix(wellbeing): symlink focus-mode-daemon so edits actually deploy
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
install_focus_mode_daemon.sh copied the script to /usr/local/bin, so the
deployed daemon went stale the instant the repo file was edited: what you
run stops matching what you read, with nothing to tell you. That is not
hypothetical - the zombie-detection fix in 22e22c1 sat in the repo while
a months-old copy at /usr/local/bin/focus-mode-daemon went on entering
GAMING mode and killing browsers. It only surfaced because the deployed
copy was checked by hand.

Link instead of copy, so editing the repo file IS deploying it. Also
chmod +x the source, since a symlink takes its executability from the
target rather than from an install mode.

uninstall now guards with [[ -e || -L ]] rather than [[ -f ]]: both -f
and -e follow the link and report false when the target is gone, which
is exactly the case (repo moved or deleted) where a stale link most
needs clearing.

The link resolves into the user's checkout, so /usr/local/bin/... is only
as trustworthy as that path. Fine here - focus-mode runs as a systemd
*user* service, crossing no privilege boundary. Not a pattern to copy for
anything root runs.

Verified: stat -L reports the same inode (92274745) for the deployed path
and the repo file; appending a marker to the repo file makes it appear at
/usr/local/bin/focus-mode-daemon immediately, with no reinstall; a link
to a missing target is now removed by uninstall where [[ -f ]] skipped it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rN2usTS3pYLJqeVg2ZpgR
2026-07-17 14:02:33 +02:00
22e22c16a7 fix(wellbeing): stop focus mode reading zombie processes as running Steam
Focus mode flapped in and out of GAMING mode every few seconds and killed
browsers while no Steam was running. The pattern matching was not at
fault: the daemon was correctly seeing a process named "steam". That
process was a root-owned zombie.

A total gaming block on 2026-07-04 purged the Steam client and it was
never reinstalled, but steam-backlog-enforcer kept trying to launch it
through an orphaned /usr/local/bin/steam wrapper still pointing at the
deleted /usr/bin/steam. Each launch died on exec and, never being reaped,
lingered as a dead process that still carried the name "steam" - which
this daemon counted as a live Steam.

get_running_processes() now reads /proc/*/stat rather than /proc/*/comm
and skips state Z. Both cost one read per PID, so the poll loop stays
fork-free, but stat also carries the process state. _parse_stat() uses
rpartition(')') because a process name can itself contain spaces and
')', which naive whitespace splitting would corrupt. Names are truncated
to 15 chars in stat exactly as in comm, so the existing patterns match
unchanged.

Verified against the live zombie, before the enforcer was fixed:
  zombies on system now              : ['steam']
  OLD (/proc/*/comm) sees 'steam'    : True
  NEW (zombie-filtered) sees 'steam' : False
  dropped by filter                  : ['steam']
and non-regression on real processes: a synthetic live 'steam' and a
'steam_app_29687' game both still return True. It skips zombies, not
Steam. Running `focus-mode-daemon` now reports "Browser detected -
entering BROWSING mode" with no GAMING flapping.

The zombie source is fixed separately in steam-backlog-enforcer d54df3a;
this is the durable guard against any future one.

Note: install_focus_mode_daemon.sh copies rather than symlinks, so
/usr/local/bin/focus-mode-daemon was a stale copy without this fix.
Reinstalled. Editing this file alone never changes what runs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rN2usTS3pYLJqeVg2ZpgR
2026-07-17 13:55:24 +02:00
3ebb56ccbb feat(shutdown): night lockdown instead of power-off, so servers stay up
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
The digital-wellbeing curfew powered the PC off at 21:00, which also took
down every service this machine hosts (Gitea, the Caddy TLS edge, SyncYomi,
the personal site, Open WebUI, Joplin, dufs, ollama, dnsmasq, wg-quick,
sshd). Keep the curfew's lockout, drop the power-off: the machine now stays
on with the GUI torn down, the TTY login surface masked, the console blanked
and the RGB killed, and restores itself at 05:00.

The fortress still owns the schedule (immutable config, ratchet, monitor,
watchdog); only its terminal action is swapped for night-lockdown-enter.sh.
The reversal deliberately lives outside the fortress so a bug in the lock
path can never take the recovery path down with it.

Verified in production overnight: lightdm down 21:00:04 -> 05:00:00 while
all 7 containers stayed "Up 14 hours" and kept serving; ticks idempotent all
night; 05:00 unlock fired.

Notable fixes found along the way:
- Wake alarm regression: it only ever fired on resume-from-hibernate, so an
  always-on machine silently killed it. The unlock now re-fires
  morning-routine.service on alarm days (the Mon/Fri/Sat/Sun gate lived in
  the removed rtcwake branch, not in the alarm).
- Morning boundary -le -> -lt, so 05:00 no longer races the unlock.
- Mask getty@ only; autovt@ is an alias of it and masking it errors.
- Persist LOCKED before the session-killing teardown, else a kill mid-lock
  leaves state=UNLOCKED and the unlock no-ops, stranding the machine.
- Blank the console without DPMS: FB_BLANK_POWERDOWN drops the DisplayPort
  link and the GPU never re-trains it (DP-0 needed a physical re-plug).
- RGB: openrgb-git 0.9.2148's CLI returns before detection finishes, so every
  call silently no-op'd while exiting 0. Stable openrgb 1.0rc3 fixes it. Use
  static+black, not "off" (the ZOTAC has no Off mode; the ASRock ignores it).
- Validate the generated config with bash -n: its heredoc must stay unquoted,
  so a stray backtick executes and corrupts the file.

Thu-Sun 22->21 aligns the source with the canonical schedule screen_locker's
sick-day feature ratcheted in on 2026-07-03; the ratchet only permits
same/stricter, so the script was otherwise un-re-runnable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dpu8SqqBVm97tCuTGE3nCs
2026-07-17 09:09:54 +02:00
9c2abe2520 fix(wellbeing): clear every remaining error/warning; drop thesis_tracker
Three of the four remaining items were scripts hardcoding assumptions that
stopped being true — not real drift.

hosts (phantom warning): check_hosts looked for 10-unlock-etc-hosts.hook /
90-relock-etc-hosts.hook, gone since the guard migrated to guard-lib's generic
unlock-all/relock-all hooks. Match what pacman_wrapper.sh already treats as
authoritative (legacy pair still accepted).

focus_mode (never installable): install_focus_mode_daemon.sh calls
`systemctl --user`, but the checker invokes it via `sudo -u <user>` from root —
sudo changes the UID but grants no session, so XDG_RUNTIME_DIR /
DBUS_SESSION_BUS_ADDRESS were unset and it died at daemon-reload on every
automated run. Derive them from the effective UID. Now enabled+active.

compulsive_blocker (discord never limited): REAL_BINARIES hardcoded
/opt/discord/Discord — another discord package's layout. This one ships only
/usr/bin/discord, a bootstrap that downloads the app into ~/.config/discord/
and execs ~/.config/discord/Discord (a version symlink its updater maintains),
so the `[[ -x $real_binary ]]` gate failed forever. Exec the preserved LAUNCHER
(/usr/bin/discord.orig) so Discord's bootstrap/self-update still runs. Two
supporting fixes: the gate skips -x when the exec target IS the wrapper's own
.orig (the wrap creates it — chicken-and-egg), and PROCESS_MATCH is added
because the launcher exec()s away, so pgrep -f on '.orig' matches nothing and
auto-close/kill/running-state would have silently no-opped.

vbox_hosts: skipped -> n/a with a reason. VirtualBox is absent AND blocked by
pacman policy ("can bypass /etc/hosts restrictions"), so the check is not
applicable, not ducked. Installing it to satisfy a hosts check would open the
hole that check exists to close.

Also removed thesis_tracker (unused; unit not-found, script never installed).

Verified: every service ok, vbox_hosts n/a, zero errors, zero warnings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JsCs1GUyiinA7bg68YvAh1
2026-07-17 08:58:43 +02:00
cc2fcc44d3 fix(checker): stop reporting healthy services as errors; drop thesis_tracker
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
check_and_enable_services.sh was lying about two things and tracking a third
the author no longer uses.

1. workout_locker: paths still pointed at python_pkg/screen_locker/, which
   stopped existing when screen-locker was extracted to its own repo
   (~/screen-locker). The service was installed, enabled and active the whole
   time, but the checker reported a red error and its "fix" silently did
   nothing. Now resolves ~/screen-locker via SUDO_USER + getent (the script
   re-execs under sudo, so $HOME is /root).

2. User-service queries could never work: `sudo -u <user> systemctl --user`
   has no XDG_RUNTIME_DIR/DBUS_SESSION_BUS_ADDRESS, so it always failed with
   "Failed to connect to user scope bus" and reported EVERY user service as
   not-enabled. Added user_systemctl() using
   `systemctl --user --machine=<user>@.host` (systemd's own suggested fix) and
   rerouted all 6 call sites (focus-mode, thorium, workout-locker).

3. Removed thesis_tracker entirely — not used; unit not-found, script never
   installed. Help list renumbered.

focus_mode and guest_mode_removal keep reporting error: those are GENUINE
(focus-mode.service is not-found; the guest-mode policies are absent).

Verified: ground truth (as kuhy) workout-locker.service = enabled+active.
Before: checker said "not enabled". After: workout_locker ok, all 3 checks ✓.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JsCs1GUyiinA7bg68YvAh1
2026-07-17 08:32:55 +02:00
779ace0c87 fix(hosts-guard): stop setup aborting silently, so the guards actually enable
setup_hosts_guard.sh died partway on every run under `set -euo pipefail`,
which is why hosts-guard.path / hosts-bind-mount.service / nsswitch-guard.path
sat installed-but-disabled since 2026-02-02 and resolved-guard.path was never
installed at all — /etc/hosts had no watcher to restore it if tampered.

Two aborts, both silent:

1. `local_dot=$(grep -E '^\s*DNSOverTLS\s*=' ... | tail -1 | sed ...)` — grep
   exits 1 when the key is absent, pipefail propagates, the assignment returns
   1, set -e kills the script. DNSOverTLS is absent from a default
   resolved.conf, so this fired on EVERY run, right before resolved-guard.path
   was enabled. The fix-if-missing branch below it was unreachable because
   detecting "missing" aborted first. Same trap on the ReadEtcHosts probe.
   check_and_enable_services.sh already guarded its copy with `|| true`.

2. `systemctl restart systemd-resolved` — resolved is MASKED here (dnsmasq
   serves DNS), so the restart failed and aborted the script on its last step,
   after everything was already configured. Now skipped with a note.

Before: exit 1, resolved-guard disabled, nsswitch-guard start-limit-hit.
After: exit 0; hosts-guard.path, hosts-bind-mount.service, nsswitch-guard.path
and resolved-guard.path all enabled+active. DNS still resolves; getent ahosts
on doubleclick/googlesyndication/facebook returns 0.0.0.0; /etc/hosts still
immutable at 176888 lines.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JsCs1GUyiinA7bg68YvAh1
2026-07-17 08:25:51 +02:00
aba288d418 fix(maintenance): make repair failures loud instead of silently exiting 0
Both tools swallowed failures. execute_with_log appended one line to a log
nobody reads and returned 0, so the systemd oneshot reported SUCCESS.
check_and_enable_services printed one err line among ~100 and exited 0.
That is why the 2026-05-15 reorg silently killed the pacman-wrapper and
hosts self-repair for five months with no visible symptom: check_hosts
detected the disabled hosts guards on every single run, could not find
setup_hosts_guard.sh at the stale $CONFIG_DIR/hosts path, and still exited 0.

Driver — any failure now surfaces four ways:
  1. journal at ERROR priority (logger -p user.err)
  2. the systemd unit FAILS (exit 1) -> systemctl --failed / red timer
  3. a critical desktop notification that never auto-dismisses
  4. /var/lib/periodic-system-maintenance/LAST_RUN_FAILED breadcrumb
It also collects ALL failures rather than aborting on the first.

check_and_enable_services — a missing repair script means this tool cannot
do its job, so all 12 "script not found" sites now route through
err_missing_script(): journal ERROR priority, a terminal banner, and exit 2.
Healthy runs still exit 0 and clear the breadcrumb.

Verified: driver fed nonexistent paths -> exit 1, all 3 failures on stderr,
breadcrumb written, 3 journal ERROR entries. Live regenerate + real run ->
rc=0, all steps ok, no breadcrumb. Checker --status -> rc=0, no banner.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JsCs1GUyiinA7bg68YvAh1
2026-07-17 08:17:51 +02:00
daa712a122 fix(hosts): stop chattr +i'ing install.sh and generate_hosts_file.sh sources
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Immutable git-tracked files break git tooling. The pre-push ci-mirror gate
runs `pre-commit run --all-files`; end-of-file-fixer opens every file rb+
and dies with "PermissionError: Operation not permitted", so no push from a
normal checkout could ever succeed — every push had to be routed through a
throwaway worktree (a fresh checkout gets new, non-immutable inodes). The
same immutability also breaks pre-commit's unstaged-changes stash: the
`git checkout -- .` unlink fails, the restore never runs, and unrelated
unstaged edits are silently reverted.

Enforcement does not depend on these sources being locked: /etc/hosts is
itself chattr +i, hosts-guard.path watches and re-enforces it via
enforce-hosts.sh against the locked-hosts canonical snapshot, and
hosts-bind-mount.service pins it. Editing the sources changes nothing until
install.sh is re-run as root, which regenerates the guarded artifacts.

Companion to 6e3d61d (same fix for setup_midnight_shutdown.sh).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JsCs1GUyiinA7bg68YvAh1
2026-07-17 08:06:46 +02:00
6e3d61daa2 fix(shutdown): stop chattr +i'ing this script's own git-tracked source
An immutable tracked file with uncommitted edits breaks every commit/push:
pre-commit clears unstaged changes with `git checkout -- .`, that unlink
fails ("Operation not permitted"), the context manager aborts, and the
restore never runs — silently reverting the user's OTHER unstaged edits
(seen twice today; an unrelated i3/config WIP had to be recovered from
pre-commit's rescue patch).

Enforcement is unaffected and does not depend on the source being locked:
/etc/shutdown-schedule.conf stays chattr +i, guard-lib keeps a canonical
snapshot + path watcher that re-enforces it, the monitor service protects
the timer, and screen_locker's ratchet only accepts same-or-stricter
values. Editing this source changes nothing until setup is re-run as root,
which rewrites the guarded config anyway.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JsCs1GUyiinA7bg68YvAh1
2026-07-17 07:55:07 +02:00
2a304691cb fix(pacman): wrap makepkg so an orphaned db.lck can't hang makepkg -i
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
Vendored makepkg's run_pacman() waits on /var/lib/pacman/db.lck existence
with no timeout BEFORE invoking pacman, so an orphaned lock hangs
`makepkg -i` forever ("Pacman is currently in use, please wait...") and
the pacman wrapper's stale-lock cleanup never gets a turn. Wrap makepkg
(mirroring the pacman-wrapper pattern) to clear an orphaned lock up front.

- Extract stale-lock logic into shared pacman_lock_lib.sh; pacman_wrapper
  sources it after integrity verification and it is in the SHA256 manifest
- makepkg_wrapper: pre-flight clear for -i/--install; bypass on FAKEROOTKEY
  and non-install; FAIL OPEN if the lib is missing (never brick makepkg)
- Cross-user pacman_process_running() pgrep guard: unprivileged makepkg can
  detect a root pacman its own fuser cannot see (avoids removing a live lock)
- Upgrade survival: rewrap hook (Install/Upgrade only) + check_makepkg_wrapper
  drift verifier + both wrappers wired into the hourly periodic driver
- Fix reorg path bugs: stale ~/linux-configuration periodic path,
  $CONFIG_DIR/hosts -> scripts/periodic_background/hosts, test WRAPPER_DIR;
  refresh .orig only when target isn't already our symlink (no exec loop)
- Tests: test_makepkg_wrapper.sh (18) incl. hook Operation validity; add
  lib-integrity coverage to test_pacman_wrapper_security.sh (also path-fixed)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JsCs1GUyiinA7bg68YvAh1
2026-07-17 07:46:31 +02:00
0bdaecd281 Add personal website deploy + move Gitea to a subdomain
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Serve the personal website (extracted to github.com/kuhyx/personal-website)
at the root kuhy.duckdns.org behind the shared gitea-caddy edge, moving Gitea
to gitea.kuhy.duckdns.org.

- setup_gitea.sh: relocate Gitea to gitea.kuhy.duckdns.org and refactor the
  shared Caddyfile into per-service sites/*.caddy imports (fixes the latent
  bug where re-running dropped the dufs/syncyomi blocks).
- setup_personal_website.sh (new): idempotent setup/status/help; migrates
  existing Caddy blocks to snippets, relocates Gitea, builds ~/personal-website,
  serves dist/ from a loopback caddy (admin off) on 127.0.0.1:8088 fronted on
  the root domain, reuses the DuckDNS/firewall edge.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KG7yQj4hP8DDpasK2e4cn7
2026-07-13 19:10:48 +02:00
59430f91a1 Add setup_syncyomi.sh: self-hosted SyncYomi manga sync
Stands up SyncYomi (ghcr.io/syncyomi/syncyomi:v1.1.11) in Docker behind
the existing shared gitea-caddy edge at kuhy-sync.duckdns.org, so
TachiyomiSY syncs its library from a mobile network. Follows the
setup_dufs_cloud.sh pattern: loopback-bound container, one appended Caddy
site block (auto Let's Encrypt), the shared DuckDNS updater extended, and
80/443 opened via setup_wireguard_ssh.sh. Auto-generates stored 0600
credentials, onboards the first account, and mints/reuses an API key over
the local REST API, printing host + key. Idempotent setup/status/help.

Verified live: container up (restart=unless-stopped), external HTTPS
reachable, and a real phone sync landed a 13.9 MB sync_data row.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CbvNNUYcdNtg5NjAhYc12E
2026-07-13 17:20:02 +02:00
b500b5daba Extract dufs cloud (web + app + scripts) to github.com/kuhyx/dufs-cloud
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Move cloud_gallery/, the Flutter dufs_client app, and the dufs/cloud setup
scripts into a new public repo (with full git history), leaving pointers here.
The live media-cloud-sync systemd units were re-pointed to ~/dufs-cloud/scripts/.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0126QvdMrv2WNeUVShFiLTc3
2026-07-12 18:38:37 +02:00
dfd0e2d70a import_media_archives.sh: fold Downloads media_archive zips into the cloud
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
New reusable utility that extracts each media_archive_*.zip snapshot, MOVEs its
media into ~/cloud/Media/YYYY/MM via sync_media_to_cloud.sh (dedup across the
overlapping snapshots), verifies staging drained, then deletes the zip — only
after its media is confirmed in the cloud. Staging lives on the cloud
filesystem so moves are atomic renames.

Ran over ~/Downloads/media_archive_archive: 44 zips / 27 GB → 44 imported +
deleted, 0 kept. The two 13.7 GB near-duplicate snapshots collapsed (2412
duplicates dropped). Cloud Media 4.9 GB → 19 GB (2949 files); Downloads
reclaimed 27 GB; empty archive dir removed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0126QvdMrv2WNeUVShFiLTc3
2026-07-12 17:43:23 +02:00
76d4e8e0cf cloud_gallery: React media-gallery SPA served by dufs (Phase 3)
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Replace dufs's plain file list with a React 19 + Vite + TypeScript SPA served
same-origin by dufs, so the cloud URL becomes a real gallery behind the existing
auth: thumbnail grid, image lightbox (zoom + keyboard nav), inline video, drag/
pick upload, download, confirm-guarded delete, and a simple .txt/.md editor.

Serving architecture (de-risked against the real dufs 0.46.0): --assets does not
override the UI, so dufs `render-spa` serves the app shell, the SPA lists dirs
via WebDAV PROPFIND (render-flag-immune) and streams files via GET (Range for
video seeking), with HashRouter so navigation stays at "/". Verified render-spa
leaves KeePass file GET/PUT/?hash intact (Phase 1 unaffected).

Adds generate_thumbnails.sh (ImageMagick images + ffmpeg video posters →
~/cloud/.thumbs, idempotent) and setup_cloud_gallery.sh (build + deploy the SPA
into the cloud root, enable render-spa, wire thumbnail refresh into the Phase-2
media sync). setup_dufs_cloud.sh now emits render-spa only when the SPA is
deployed, so a fresh dufs keeps its default listing.

Verified: pnpm build + lint (strictTypeChecked) clean; 38 vitest tests, coverage
92.8% stmts / 96% lines (dufs-client 100%); local dufs --render-spa serves shell
+ assets + thumbnails + PROPFIND (all 200). Live deploy left for the user (needs
sudo; enables render-spa on the public service). Note: host ffmpeg is broken
(libvpx.so.11) so video posters are skipped until it's fixed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0126QvdMrv2WNeUVShFiLTc3
2026-07-12 06:05:52 +02:00
095587c0de linux_configuration: move Downloads media into the dufs cloud (browsable)
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Phase 2 of the cloud roadmap. sync_media_to_cloud.sh MOVES organized images and
videos out of ~/Downloads into ~/cloud/Media/YYYY/MM (by mtime), unzipped and
browsable via the dufs URL — no duplication, the cloud folder becomes the single
storage. Move is crash-safe (mv: atomic on same fs, copy-then-unlink across fs);
files modified in the last 2 min are skipped (in-progress downloads); identical
files are de-duplicated and name clashes get a numeric suffix.

setup_media_cloud_sync.sh installs a oneshot service + 30-min catch-up timer +
a ~/Downloads path watcher, plus a drop-in ordering the existing media-organizer
after the cloud sync so media is moved before it would be zipped.

Verified: shellcheck clean; 12-assertion MOVE suite on throwaway dirs; real
move of a PNG into ~/cloud/Media fetched via the live URL (HTTP 200 image/png).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0126QvdMrv2WNeUVShFiLTc3
2026-07-12 05:19:31 +02:00
0902a5e1f4 linux_configuration: unified multi-device KeePass sync over dufs
Add "one vault, synced everywhere" for PC + Ubuntu laptop + phone, with an
identical flow and no stored master password. keepass-open prompts the master
password (in memory only), folds in strays, pulls+merges the cloud copy over
WebDAV, opens KeePassXC on ~/Keepass/Passwords.kdbx, and publishes edits on
close. Safety rests on `keepassxc-cli merge` (entry-level union) plus a dufs
?hash compare-and-swap on upload, so concurrent edits merge instead of clobber.

The consolidator enforces exactly one vault per machine: it folds a stray only
if it opens with the same master password, backs up first, never removes the
canonical, and auto-excludes the dufs serve-path (the remote store) — a
data-safety fix after the first real run tried to delete ~/cloud/Keepass.

Only the dufs *server* password (not the vault key) is cached in the keyring.
Single cross-distro installer, no role flag; the phone uses KeePassDX natively.

Verified: shellcheck clean; 8 (reconcile) + 14 (consolidator) + 8 (installer)
assertions on throwaway vaults; real PC apply with live WebDAV GET=200 and
?hash==sha256; a clean keepass-open run ("no strays / already in sync").

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0126QvdMrv2WNeUVShFiLTc3
2026-07-12 05:00:27 +02:00
20bc1aeb02 linux_configuration: self-hosted dufs cloud storage + KeePass WebDAV auto-sync
Add setup_dufs_cloud.sh: a self-sustaining installer that stands up dufs
(single Rust binary; web UI + built-in WebDAV) on 127.0.0.1:5000 behind the
existing Caddy + DuckDNS exposure stack at a new subdomain, so files are
reachable from mobile network over HTTPS. An event-driven systemd path unit
mirrors ~/Keepass/Passwords.kdbx into the served folder on every change, so
KeePassDX syncs the vault natively over WebDAV.

Paranoid secret handling for the gitignored .dufs_cloud.conf (plaintext web
password): ignored at repo-root + linux_configuration + **/ globs; a new
check-no-dufs-conf pre-commit hook blocks it even against `git add -f`; the
installer refuses to write it unless git check-ignore confirms it is ignored;
the password is hashed via `openssl passwd -6 -stdin` (never in argv); and a
cloud-root guard forbids serving home/.ssh/.config/.gnupg/the repo/root.

Verified: dufs auth (401/200) + WebDAV (207) against the real v0.46.0 binary,
idempotent Caddy/DuckDNS/unit-render logic, and a live phone-on-cellular test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0126QvdMrv2WNeUVShFiLTc3
2026-07-12 03:40:54 +02:00
a456314f1a Add local-LLM setup script (ollama-cuda + qwen3 + Open WebUI)
setup_local_llm.sh: idempotent Bash installer for a self-hosted local LLM
stack tuned for the RTX 3090 (24GB) — installs ollama-cuda, writes a
systemd drop-in enabling flash attention + Q8_0 KV-cache quantisation,
pulls the model, creates a custom Ollama model with a developer system
prompt, and launches Open WebUI via Docker.

Verification: bash -n and shellcheck -x clean (see evidence artifact).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RRCdR4D8SaVrN2xraMQxM
2026-07-11 00:16:24 +02:00
7b4a08f482 feat(digital-wellbeing): time-boxed shutdown overrides + drift-proof i3blocks deploy
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
Add a self-expiring override system so specific late-night live events
(2026 World Cup matches) can be watched without the auto-shutdown killing
the PC, without weakening the permanent schedule ratchet:

- shutdown-override-manager.sh (add/list/remove): add is friction-gated
  (typed confirmation phrase + 30s delay, max 12h, max 3 windows) and
  writes absolute-epoch windows to /etc/shutdown-schedule-overrides.conf.
- day-specific-shutdown-check.sh now skips the shutdown decision inside an
  active window (pruning expired entries) and gained a DRY_RUN guard around
  rtcwake/poweroff/hibernate for safe testing.

i3blocks shutdown_countdown.sh: show the exact next-shutdown clock time
(not a relative countdown), show the overridden end time in green when an
override is active or will rescue the upcoming shutdown, and make the
skip-dates check fork-free (builtin read loop) so the hot path spawns no
external processes.

install.sh: deploy i3blocks by symlinking each repo file into
~/.config/i3blocks instead of cp -r (the source of silent drift), cd to
the script dir so it runs from anywhere, and chmod +x only *.sh so the
config file stays 0644.

Repair the previously-dead i3blocks regression suite (stale path), update
the shutdown assertion to the new absolute-time output, add hermetic
override coverage, and keep the <=1-exec fork-count guarantee.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmwYH5RfThZGkVD2jE61Da
2026-07-10 21:57:05 +02:00
343d38eaf8 feat: add Pi-hole-like LAN DNS blocking served from the PC (dnsmasq)
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
setup_dns_blocker.sh turns this PC into a DNS server that serves the
identical /etc/hosts blocklist to the whole LAN with no per-device app,
by feeding generate_hosts_file.sh output into dnsmasq via addn-hosts
(same StevenBlack variant + custom entries + unblocks). Adds status/
refresh subcommands, a daily refresh timer, Restart=always, and logging
to /var/log/dns-blocker/.

Because the ISP router cannot advertise a custom DNS server, a dhcp/
dhcp-off mode makes the PC the LAN DHCP server (static IP via nmcli with
a gateway-ping self-check and safe, always-online rollback), handing out
itself as the DNS server so every device is blocked automatically.

setup_wireguard_ssh.sh gains an allow-dns subcommand that opens DNS (53,
LAN saddr) and DHCP (67) in the single-owner nftables ruleset. The DHCP
accept rule is placed before 'ct state invalid drop' because the
0.0.0.0->255.255.255.255 DHCP broadcast is classified INVALID and was
otherwise dropped. Firewall detection now reads the actual loaded ruleset
(a ruleset can be loaded while nftables.service reads inactive) and avoids
a grep -q/pipefail SIGPIPE false-negative.

Verified end-to-end: Pixel-6a leased 192.168.1.82 with DNS 192.168.1.43;
youtube.com blocked, legit sites resolve. Regression tests added.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018pqSnrLt8QoWup7n2Ymk77
2026-07-10 19:02:46 +02:00
66c4698194 feat: migrate hosts-guard and shutdown-schedule-guard to guard-lib
Some checks failed
Pre-commit checks / pre-commit (push) Has been cancelled
Replaces the bespoke chattr/bind-mount/systemd-watcher implementations for
/etc/hosts and /etc/shutdown-schedule.conf with the new shared guard-lib
(~/guard-lib, guardctl), so screen-locker and steam-backlog-enforcer's new
block-gaming feature stop maintaining parallel copies of the same
tamper-resistance mechanism.

- pacman_wrapper.sh: pre/post hook fallbacks now call guard-lib's generic
  unlock-all/relock-all scripts (covers every registered guard instance,
  not just /etc/hosts)
- setup_midnight_shutdown.sh: installs/updates its guarded config via
  guardctl file-guard instead of hand-rolled chattr + systemd unit
  generation; the schedule ratchet logic (block-if-more-lenient) stays
  bespoke since guardctl's generic unlock can't represent it
- new hosts/guard/plugins/nsswitch-plugin.sh, resolved-plugin.sh

Also fixes, at user's request even though pre-existing: 3 shellcheck
SC2329 false positives in pacman_wrapper.sh (functions invoked indirectly
by name, not actually dead) and 1 SC2001 style warning (echo|sed VM-name
extraction replaced with parameter expansion, verified equivalent output).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFNiYQQgSLAkiBXswyimPq
2026-07-04 11:54:08 +02:00
ea94435c4f Add self-hosted Gitea deployment, mirroring all GitHub repos publicly
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Deploys Gitea+Caddy (auto-HTTPS via Let's Encrypt) at kuhy.duckdns.org,
extends setup_wireguard_ssh.sh with an allow-web firewall subcommand, and
mirrors all 21 GitHub repos (5 private) via Gitea's native pull-mirror.
Runs containers with host networking to work around a discovered bug where
this host's nftables forward-chain silently blocks Docker bridge egress.

Adds a self-hosted-service-exposure skill capturing the reusable pattern
and gotchas for future public-facing deployments.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C5jnu99ZuENSkuFQKLcSdh
2026-07-04 07:45:00 +02:00
12fe41049f fix: shutdown timer crashing on every fire due to heredoc escaping bug
The hibernate-on-alarm-night case block in create_shutdown_check_script()
escaped $ as \$ for an unquoted heredoc, but the heredoc is opened with the
quoted delimiter <<'EOF', so the backslashes were written literally into
the deployed check script. Every timer fire since commit 0d54c5d hit a bash
syntax error and exited before evaluating the shutdown window, so the PC
never auto-shut-down (confirmed failing at 23:00/23:01 last night and 07:01
this morning). Also fixed an off-by-one (seq ... 24 -> 23) that was emitting
invalid OnCalendar=24:00:00 entries systemd had to ignore.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGHLfbAPmak6HtGJby57eo
2026-06-22 07:09:55 +02:00
66272dc95a feat: add self-hosted WireGuard+SSH remote access from Android, across networks
Lets SSH terminal access reach this PC from a phone on a different network
(mobile data vs home broadband), using only FOSS/free software: self-hosted
WireGuard (no relay/coordination server), DuckDNS for the dynamic public IP,
and a default-drop nftables firewall so sshd is never exposed to the WAN
directly -- only the WireGuard UDP port is forwarded, SSH is reachable only
through the tunnel or LAN.

Verified fully end-to-end (phone on mobile data, real handshake + SSH login).
Several bugs only surfaced through live execution and were fixed in place:
a DNS=1.1.1.1 line that broke all phone DNS once the tunnel was active, a
require_root/sudo arg-forwarding bug, hostname/dig not being installed on a
minimal Arch system, a bash RETURN-trap scoping bug, and a DuckDNS cron-dedup
that would have deleted an unrelated pre-existing Joplin DuckDNS cron entry.

Also whitelists the WireGuard/F-Droid/ConnectBot apps (plus the todo app) in
phone_focus_mode's WHITELIST so the GPS-based focus daemon doesn't disable
them. Adds "iif" (nftables keyword) to the codespell ignore-list since it
was flagged as a false-positive typo of "if".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TUSBRyujRMuGiUitGP8gET
2026-06-21 20:07:13 +02:00
615183556d style: apply prettier formatting to evidence JSON and dwm/gaming READMEs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-14 07:22:04 +02:00
038e08d2be feat: split oversized modules for 500-line limit, fix kasa coverage gap
Split diet_guard/_gatelock.py, wake_alarm/_alarm.py, and the
usage_report.py/_usage_report_parsing.py pair into focused
sub-modules so every Python file is <= 500 lines, satisfying
test_file_length.py. Install python-kasa into .venv (declared in
requirements but missing after the 3.13->3.14 venv upgrade),
fixing 8 failing smart_plug tests and restoring 100% coverage.

Also includes prior in-progress work from the working tree: the
wake_alarm Progress/View/Hardware field-grouping refactor,
brother_printer query module + tests, diet_guard foodbank/state/cli
updates, new shared coerce/logging_setup helpers, morning_routine
orchestrator tweaks, dwm window-manager config, gaming scripts, and
misc maintenance/digital-wellbeing script updates.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-14 07:19:37 +02:00
8fdbfd8411 remove: uninstall unused ffmpeg screen-replay feature
Deleted screen_replay.sh (x11grab ring-buffer) and kill_stale_recorders.sh
(stale-ffmpeg killer). Removed autostart exec and Mod+Shift+F12 binding from
i3/config; removed replay startup from dwm-session. Both scripts archived in
testsAndMisc-archive.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-06 10:44:36 +02:00
2e1e370c0f refactor: extract all inline Python from shell scripts into proper .py files
Move every multi-line python heredoc/`-c` block into a dedicated .py file so
ruff, mypy, pylint, bandit, and pytest can apply to it:
- linux_configuration/zsh/calc-live.zsh → python_pkg/live_calc/calc_eval.py (100% branch cov, 46 tests)
- meta/scripts/check_ai_evidence.sh → meta/scripts/validate_evidence.py
- meta/scripts/check_agent_contract.sh → meta/scripts/validate_contract.py
- phone_focus_mode/lib/monitor.sh → phone_focus_mode/lib/monitor_report.py
- phone_focus_mode/deploy.sh → phone_focus_mode/strip_workout_hosts.py
- linux_configuration/.../analyze_repo.sh → fast_count.py

Also: add zsh-syntax pre-commit hook (zsh -n); exclude zsh from shellcheck;
add tests for all 4 non-python_pkg helpers; update CLAUDE.md Shell Style with
the no-inline-Python rule.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-06 10:31:48 +02:00
fcd3f7ed2f perf(idle-off): replace controller-watch fork storm with a single systemd-inhibit
turn_off_auto_idle_screen_shutdown.sh --watch-controller forked 4 xset +
1 xdotool per joystick event (blocking on a dd read, debounced by sleep
0.3) — ~21 procs/s while a controller was connected during gaming. The
xset poking was redundant: startup already disables DPMS/blanking.

Replace reset_idle_activity / watch_js_device / the polling watcher with
one long-lived `systemd-inhibit --what=idle:sleep` held only while a
/dev/input/js* device is present, re-evaluated on udev input add/remove
events (event-driven; 30s presence-poll fallback). EXIT+INT/TERM traps
release the inhibitor on every termination path.

Verified live: subtree stays {systemd-inhibit, udevadm} with zero
dd/xset/xdotool; exactly one inhibitor held; clean release on SIGTERM,
no orphans. Takes that loop from ~21 forks/s to 0.

Behavior change: keeps the session awake while a controller is connected
(not only during active input).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 18:14:07 +02:00
20d5d1f89b fix(usage_report): stop charging atop's HZ field as CPU; bundle since-last-report mode
atop's `-P PRC` output inserts the clock-tick rate (HZ=100) between the
`state` and `utime` columns. Both the Python parser and the native C
aggregator read that constant as utime for every record, charging a flat
1 CPU-second per record — so cpu_seconds collapsed to pid_count and
short-lived fork-storm commands (xset, dd, chronyc) topped the CPU table
(xset showed 67h). The old test fixtures lacked the HZ field, so code and
tests agreed on the bug.

- _parse_prc / atop_agg.c: read utime/stime past the HZ field (after+2/+3,
  tokens[10]/[11]); bump the length guards accordingly
- restore C/atop_agg (deleted in 89b4f59) under linux_configuration/C/,
  where the build path resolves; corrected test fixtures to include HZ
- _atop_agg_binary: fall back to the Python parser when the C source tree
  is gone instead of trusting an orphaned cached binary
- add regression tests proving HZ is not summed as CPU
- bundle the in-progress since-last-report multi-day aggregation (segments,
  -b/-e bounding, persisted state, window merging) and its tests/conftest
- meta: gate linux_configuration/tests in pytest_changed_packages.py

Verified by running usage_report.py --date 20260604: Top CPU now led by
SkyrimSE; xset/dd/chronyc fall to ~0. C unit tests + full pytest suite green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 18:13:47 +02:00
dcbfbc3ca4 feat(phone): automate BL-9000 fresh-phone recovery after factory reset
- batch3_bloatware_uninstall.sh: rewrite with 42 confirmed BL-9000 packages
  (39 Blackview OEM + Chrome, YouTube, YouTube Music); batch removal without
  reboots; --list dry-run; ADB_SERIAL/PHONE_IP support
- deploy.sh: ensure_magisk_hosts_module() auto-creates Magisk Systemless Hosts
  module dir+module.prop and reboots if absent/disabled — no manual Magisk UI
  interaction required
- deploy.sh: fetch_home_coords_from_phone() enables location and captures GPS
  fix; falls back to stub coords with clear next-step instruction on failure
- deploy.sh: --capture-coords action for post-WiFi GPS capture + daemon restart
- config.sh: add com.kuhy.workout_app and com.shazam.android to WHITELIST
- hosts scripts: broaden Facebook/Messenger unblocking to all subdomains
  (fbcdn.net, facebook.net, m.facebook.com)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 16:22:49 +02:00
0c1e395008 Split modules, fix tests, fix pre-commit batching
- steam_backlog_enforcer: extract _hltb_search.py and _scanning_confidence.py;
  split oversized test files into *_part2/3/4.py
- screen_locker: extract _early_bird.py and _window_setup.py from screen_lock.py;
  fix patch targets in tests (screen_lock.* -> _window_setup.*)
- wake_alarm: use shutil.which('xset') to avoid S607; add TestDisplayHelpers tests
- linux_configuration/usage_report: split into _parsing.py and _types.py;
  add bin/__init__.py (INP001); fix RUF002 (× -> x)
- pre-commit: add require_serial: true to pytest-coverage hook to prevent
  file batching across 24 CPU cores (was causing 12 parallel partial-coverage runs)
2026-05-22 22:48:28 +02:00
0d54c5d418 wake_alarm + midnight_shutdown: hibernate on alarm nights instead of poweroff
- install.sh: install sleep-hook.sh to systemd-sleep hooks (step 3) and
  shutdown-wrapper.sh to /usr/local/bin/shutdown (step 5)
- shutdown-wrapper.sh: new script that intercepts shutdown calls and
  redirects to rtcwake -m disk on alarm nights (Mon/Fri/Sat/Sun), pass-
  through for reboots and cancel commands
- sleep-hook.sh: new systemd-sleep hook that restarts wake-alarm.service
  for each logged-in user after hibernate resume
- setup_midnight_shutdown.sh: check wake-alarm day; if yes set RTC alarm
  and hibernate, otherwise fall back to systemctl poweroff
2026-05-22 16:01:04 +02:00
9e66638fda fix: sync test paths, drop stale assertions, fix coverage gap
- linux_configuration/tests: update script paths after periodic_background/
  reorganisation (hosts_file_monitor, makepkg_capped, music_parallelism,
  shutdown_timer_monitor, usage_monitoring_installer_efficiency)

- test_i3blocks_efficiency.sh: remove checks for HEARTBEAT_INTERVAL_S and
  WARP_POLL_INTERVAL_S constants that no longer exist

- test_pacman_wrapper_security.sh: remove tests 20-21 (builtin time helpers /
  external date calls) that are no longer applicable; update path

- generate_hosts_file.sh: add sed unblock rules for delio.com.pl and
  loverslab.com to stay consistent with install.sh whitelist

- steam_backlog_enforcer/scanning.py: remove unplayable_reason arg from
  logger.info call (too many format args); drop matching test assertion

- steam_backlog_enforcer/tests/test_protondb.py: add
  test_unplayable_reason_no_trending_tier to restore 100% branch coverage
  on protondb.py line 97 (was previously covered indirectly)
2026-05-16 15:46:02 +02:00
b96f6801b6 security: harden digital-wellbeing bypass vectors
- Screen locker: disable VT switching (Ctrl+Alt+Fn) via setxkbmap
  srvrkeys:none on startup; restore on close (production mode only).
  Gracefully skips if setxkbmap is not installed (shutil.which).
  Tests: 7 new tests, 100% branch coverage maintained.

- Midnight shutdown: restore real schedule values (Mon-Wed 21:00,
  Thu-Sun 22:00, morning end 05:00); re-enable the three commented-out
  leniency checks in check_schedule_protection(); self-lock script with
  chattr +i at end of enable_midnight_shutdown().

- Hosts install: add UNBLOCK_STATE_FILE tracking for whitelisted domains;
  check_unblock_entries_protection() blocks installation if the unblock
  list grows; save state after install; self-lock install.sh and
  generate_hosts_file.sh with chattr +i.
2026-05-16 15:41:40 +02:00
9a955bb424 move install_core_system.sh to linux_configuration/ root 2026-05-15 01:17:49 +02:00
765fa92543 Add install_core_system.sh; remove pc_startup and thesis_tracker
- Add linux_configuration/scripts/single_use/install_core_system.sh:
  unified installer for core modules (workout locker, hosts, shutdown
  timer) plus optional secondary modules (steam enforcer, pacman
  wrapper, i3 config, compulsive block, focus daemon)
- git rm pc_startup_visual_status.sh, setup_pc_startup_monitor.sh,
  thesis_work_tracker.sh, thesis_work_status.sh,
  setup_thesis_work_tracker.sh, README_THESIS_TRACKER.md,
  systemd/thesis-work-tracker@.service, and their two test files
- Remove now-dead setup_pc_startup_monitor.sh call from fresh-install/main.sh
2026-05-15 01:13:28 +02:00
db6276b3ff refactor(linux_configuration): move remaining dirs + scripts/ to meta/
- Move fresh-install/ → scripts/single_use/fresh-install/
- Move hosts/ → scripts/periodic_background/hosts/
- Move i3-configuration/ → scripts/periodic_background/i3-configuration/
- Delete linux_configuration/LaTeX/, nix-poc/, report/ (dead dirs)
- Move repo-root scripts/ → meta/scripts/
- Update root .pre-commit-config.yaml: scripts/ → meta/scripts/ (9 entries)
- Update run.sh ARTIFACT_INIT_SCRIPT to meta/scripts/
- Update fresh-install/main.sh: hosts/install.sh + i3-configuration/install.sh paths
- Update check_python_location.sh: add meta/scripts/ to exception list
- Fix midnight flakiness in test_recent_workout_returns_true: use timezone-aware
  local noon instead of now-1h to avoid SQL date() boundary issues
2026-05-15 00:53:01 +02:00
42a66a1419 refactor(linux_configuration/scripts): split all scripts into single_use/ and periodic_background/
- Move all linux_configuration scripts into two semantic categories:
  - single_use/: scripts run once manually (fresh install, fixes, setup)
  - periodic_background/: scripts run by systemd timers or daemons
- Preserve existing subdirectory structure within each category
- Fix lib/common.sh source paths for new directory depths
- Fix CONFIG_DIR depth in setup_periodic_system.sh and check_and_enable_services.sh
- Update all references in tests, fresh-install/main.sh, nix modules, and docs
- Fix check_polling_antipatterns.sh false positives (||, regex |, case patterns, jq strings)
- Fix pre-existing mypy exclusion path and type annotations for moved tools/ directory
- Rewrite check_polling_antipatterns.sh using awk (no bash regex loops); add require_serial: true
2026-05-15 00:32:35 +02:00
11c792ef3a fix(linux_configuration): harden polling/runtime scripts and add tests
- music_parallelism.sh + thesis_work_tracker.sh: tighter state-output and
  error paths; expanded regression tests.
- hosts-file-monitor.sh + shutdown-timer-monitor.sh: harden against partial
  failures, matching new test branches.
- i3blocks persist_common.sh helper improved (consumed by activitywatch /
  warp status blocks).
- setup_midnight_shutdown.sh + thesis_work_status.sh: state parsing tuned.
- pacman_blocked_keywords.txt: drop one obsolete entry.
- New test_thesis_work_status.sh regression script.

All six bash regression tests pass.
2026-05-14 19:55:42 +02:00