mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 00:06:27 +01:00
Compare commits
2 Commits
147ec3f690
...
28779586eb
| Author | SHA1 | Date | |
|---|---|---|---|
| 28779586eb | |||
| 22e22c16a7 |
@ -0,0 +1,56 @@
|
||||
{
|
||||
"intent": "Make editing focus_mode_daemon.py actually change what runs. The installer copied the script to /usr/local/bin/focus-mode-daemon, so the deployed daemon silently went stale the moment the repo file was edited - a fix for phantom Steam detection (commit 22e22c1) sat in the repo while a months-old copy kept killing browsers.",
|
||||
"scope": [
|
||||
"linux_configuration/scripts/periodic_background/digital_wellbeing/install_focus_mode_daemon.sh",
|
||||
"Non-goal: any change to focus_mode_daemon.py itself (done separately in 22e22c1).",
|
||||
"Non-goal: the other install scripts in this tree that may copy rather than link; not audited here."
|
||||
],
|
||||
"changes": [
|
||||
"install_daemon(): replaced `install -m 755 <src> <dst>` with `ln -sfn <src> <dst>`, so /usr/local/bin/focus-mode-daemon is a symlink into the checkout and editing the repo file IS deploying it.",
|
||||
"Added `chmod +x` on the source, since a symlink takes its executability from the target rather than from an install mode.",
|
||||
"uninstall_daemon(): widened the removal guard from `[[ -f ]]` to `[[ -e || -L ]]`. -f and -e both follow symlinks and report false for a link whose target is gone, which is exactly the case (repo moved or deleted) where a stale link most needs clearing.",
|
||||
"Documented in-comment why a link and not a copy, and noted that the target lives in the user's checkout - acceptable because focus-mode runs as a systemd *user* service and so crosses no privilege boundary."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "./install_focus_mode_daemon.sh install",
|
||||
"result": "pass",
|
||||
"evidence": "'Linking /usr/local/bin/focus-mode-daemon -> /home/kuhy/testsAndMisc/.../focus_mode_daemon.py'. ls -la confirms lrwxrwxrwx pointing at the checkout; before the change it was '-rwxr-xr-x root root 15760' (a copy)."
|
||||
},
|
||||
{
|
||||
"command": "stat -L -c '%i %n' /usr/local/bin/focus-mode-daemon focus_mode_daemon.py",
|
||||
"result": "pass",
|
||||
"evidence": "Both report inode 92274745 - the deployed command IS the repo file. (Note: plain `stat` without -L reports the symlink's own inode and appears to disagree; -L is required.)"
|
||||
},
|
||||
{
|
||||
"command": "staleness canary: append a marker to the repo file, grep the deployed path, revert",
|
||||
"result": "pass",
|
||||
"evidence": "grep -c marker /usr/local/bin/focus-mode-daemon -> 1 immediately after the edit, 0 after revert; git diff --stat clean afterwards. Proves an edit deploys with no reinstall step."
|
||||
},
|
||||
{
|
||||
"command": "focus-mode-daemon (deployed command, 8s)",
|
||||
"result": "pass",
|
||||
"evidence": "'Focus Mode Daemon starting...' then 'Browser detected - entering BROWSING mode'. Runs correctly through the symlink."
|
||||
},
|
||||
{
|
||||
"command": "dangling-link guard check",
|
||||
"result": "pass",
|
||||
"evidence": "For a link to a nonexistent target: [[ -f ]] is false (old code would leave the stale link behind), [[ -e || -L ]] is true (now removed)."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <changed files> (in a clean worktree)",
|
||||
"result": "pass",
|
||||
"evidence": "Run from a temporary git worktree because the main tree carries unrelated uncommitted brother_printer work whose tests fail."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"/usr/local/bin/focus-mode-daemon now resolves into a user-writable checkout, so anything invoking it as root would execute user-writable code. Acceptable here: focus-mode runs as a systemd user service. Do not copy this pattern for anything root runs.",
|
||||
"The link breaks if the repo is moved, renamed, or deleted; re-run the installer after any such move. Uninstall now clears a dangling link rather than skipping it.",
|
||||
"Running the installer to verify also enabled and started focus-mode.service, which had not previously been running. User confirmed on 2026-07-17 to leave it enabled."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert this commit and re-run ./install_focus_mode_daemon.sh install to return to a copied binary.",
|
||||
"After rollback, remember the staleness footgun is back: every future edit to focus_mode_daemon.py requires re-running the installer before the change takes effect.",
|
||||
"Verify with: ls -la /usr/local/bin/focus-mode-daemon (expect a regular file, not a symlink)."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
{
|
||||
"intent": "Stop focus mode from entering GAMING mode and killing browsers when no Steam is running. The daemon was flapping in and out of GAMING mode every few seconds against a Steam that had been uninstalled since 2026-07-04.",
|
||||
"scope": [
|
||||
"linux_configuration/scripts/periodic_background/digital_wellbeing/focus_mode_daemon.py",
|
||||
"Non-goal: the Steam/enforcer coexistence conflict. A healthy enforcer keeps a headless Steam alive permanently, which focus mode would correctly read as GAMING and lock browsers out for good. Only relevant if Steam is reinstalled, and needs its own decision (GAMING = client alive vs GAMING = a game actually running).",
|
||||
"Non-goal: reinstalling Steam. User chose to leave it uninstalled.",
|
||||
"Companion fix in the separate steam-backlog-enforcer repo (commit d54df3a) removes the zombie source itself."
|
||||
],
|
||||
"changes": [
|
||||
"get_running_processes() reads /proc/*/stat instead of /proc/*/comm and skips processes in state Z (zombie). Both cost one read per PID, so the poll loop stays fork-free, but stat also carries the process state.",
|
||||
"Added _parse_stat(), which extracts (name, state) using rpartition(')') because a process name may itself contain spaces and ')' - splitting on whitespace would corrupt such names. Names are truncated to 15 chars in stat exactly as in comm, so STEAM_PATTERNS and STEAM_GAME_PREFIX match unchanged.",
|
||||
"Added the ZOMBIE_STATE constant.",
|
||||
"Root cause: a total gaming block on 2026-07-04 purged the Steam client; the enforcer kept trying to launch it via an orphaned /usr/local/bin/steam wrapper pointing at the deleted /usr/bin/steam. Each failed launch left an unreaped zombie still named 'steam', which this daemon counted as a running Steam."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "probe get_running_processes() against live /proc while a real steam zombie was present",
|
||||
"result": "pass",
|
||||
"evidence": "zombies on system now: ['steam'] | OLD (/proc/*/comm) sees 'steam': True | NEW (zombie-filtered) sees 'steam': False | is_steam_running(NEW): False | dropped by filter: ['steam']. Reproduced across 6 consecutive polls."
|
||||
},
|
||||
{
|
||||
"command": "non-regression: synthetic non-zombie process sets through is_steam_running()",
|
||||
"result": "pass",
|
||||
"evidence": "synthetic live 'steam' -> True; synthetic game 'steam_app_29687' -> True. Proves the filter skips zombies, not Steam."
|
||||
},
|
||||
{
|
||||
"command": "focus-mode-daemon (the deployed command, run for 12s)",
|
||||
"result": "pass",
|
||||
"evidence": "'Focus Mode Daemon starting...' then 'Browser detected - entering BROWSING mode'. No 'Steam detected - entering GAMING mode' lines at all; browsers untouched. Before the fix the same command flapped GAMING on/off every ~15s."
|
||||
},
|
||||
{
|
||||
"command": "sudo install -m 755 focus_mode_daemon.py /usr/local/bin/focus-mode-daemon; diff -q",
|
||||
"result": "pass",
|
||||
"evidence": "Deployed copy was STALE (grep -c ZOMBIE_STATE = 0) because install_focus_mode_daemon.sh copies rather than symlinks. Reinstalled; deployed file now byte-identical to source."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <this file + focus_mode_daemon.py> (in a clean worktree)",
|
||||
"result": "pass",
|
||||
"evidence": "Run from a temporary git worktree because the main tree carries unrelated uncommitted brother_printer work whose tests fail; with brother_printer at its committed state the suite is 340 passed."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Reading /proc/*/stat instead of /proc/*/comm is a wider parse surface; mitigated by rpartition(')') handling names containing ')' or spaces, which naive whitespace splitting would break.",
|
||||
"A process that is genuinely running is never skipped - only state Z is filtered - so real Steam and real games are still detected.",
|
||||
"install_focus_mode_daemon.sh copies rather than symlinks, so editing the repo file alone does not change what runs. Any future change must be re-installed to /usr/local/bin/focus-mode-daemon.",
|
||||
"The removed /usr/local/bin/steam wrapper carried GPU workaround flags: exec /usr/bin/steam -cef-disable-gpu -cef-disable-gpu-compositing \"$@\" . Restore them if a Steam reinstall brings back GPU trouble."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit, then re-run: sudo install -m 755 focus_mode_daemon.py /usr/local/bin/focus-mode-daemon (reverting the repo file alone does NOT change the deployed daemon).",
|
||||
"After rollback, expect focus mode to once again count zombie processes as running; verify with the probe that /proc/*/comm-based detection returns True for a 'steam' zombie.",
|
||||
"The enforcer fix (steam-backlog-enforcer d54df3a) is independent and removes the zombie source, so rolling this back alone should not resurrect the symptom unless the enforcer is also reverted."
|
||||
]
|
||||
}
|
||||
@ -34,6 +34,9 @@ WHITELIST_FILE = STATE_DIR / "whitelist"
|
||||
POLL_INTERVAL = 2 # seconds between process checks
|
||||
DEFAULT_WHITELIST_MINUTES = 5
|
||||
|
||||
# /proc/PID/stat state character for a dead-but-unreaped process.
|
||||
ZOMBIE_STATE = "Z"
|
||||
|
||||
# Process patterns
|
||||
STEAM_PATTERNS = frozenset(
|
||||
[
|
||||
@ -161,18 +164,53 @@ def notify(title: str, message: str, urgency: str = "normal") -> None:
|
||||
)
|
||||
|
||||
|
||||
def _parse_stat(stat_line: str) -> tuple[str, str] | None:
|
||||
"""Extract the (name, state) pair from a /proc/PID/stat line.
|
||||
|
||||
The stat format is ``pid (comm) state ...``. The comm field may itself
|
||||
contain spaces and ')' characters, so the name is everything between the
|
||||
first '(' and the *last* ')' - splitting on whitespace would corrupt any
|
||||
process whose name embeds either.
|
||||
|
||||
Args:
|
||||
stat_line: Raw contents of a /proc/PID/stat file.
|
||||
|
||||
Returns:
|
||||
A (name, state) tuple, or None if the line is malformed.
|
||||
"""
|
||||
open_paren = stat_line.find("(")
|
||||
before_close, sep, after_close = stat_line.rpartition(")")
|
||||
if open_paren == -1 or not sep:
|
||||
return None
|
||||
state_fields = after_close.split()
|
||||
if not state_fields:
|
||||
return None
|
||||
return before_close[open_paren + 1 :], state_fields[0]
|
||||
|
||||
|
||||
def get_running_processes() -> set[str]:
|
||||
"""Get set of currently running process names by reading /proc directly.
|
||||
|
||||
Reads /proc/*/comm to avoid forking a subprocess on every poll cycle.
|
||||
Reads /proc/*/stat rather than /proc/*/comm: both cost one read per PID
|
||||
(so the poll loop stays fork-free), but stat also carries the process
|
||||
state. That distinction matters because a dead process keeps its name
|
||||
until the parent reaps it, so a crashed "steam" lingers as a zombie and
|
||||
would otherwise be counted as a running Steam. Zombies are skipped.
|
||||
|
||||
Names are truncated to 15 characters here exactly as they are in
|
||||
/proc/*/comm, so the module's process patterns match unchanged.
|
||||
"""
|
||||
processes: set[str] = set()
|
||||
try:
|
||||
for comm_path in Path("/proc").glob("*/comm"):
|
||||
for stat_path in Path("/proc").glob("*/stat"):
|
||||
with contextlib.suppress(OSError):
|
||||
proc_name = comm_path.read_text().strip().lower()
|
||||
if proc_name:
|
||||
processes.add(proc_name)
|
||||
parsed = _parse_stat(stat_path.read_text())
|
||||
if parsed is None:
|
||||
continue
|
||||
proc_name, state = parsed
|
||||
if state == ZOMBIE_STATE or not proc_name:
|
||||
continue
|
||||
processes.add(proc_name.lower())
|
||||
except OSError as exc:
|
||||
log(f"Error reading /proc: {exc}")
|
||||
return processes
|
||||
|
||||
@ -73,12 +73,21 @@ install_daemon() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Install the daemon script
|
||||
msg "Installing daemon script to $INSTALL_PATH"
|
||||
# Symlink rather than copy. A copy goes stale the instant the repo file is
|
||||
# edited, so the daemon being run silently stops matching the daemon being
|
||||
# read - which is exactly how a fix for phantom Steam detection sat in the
|
||||
# repo while the months-old copy at $INSTALL_PATH went on killing browsers.
|
||||
# A link means editing the repo file IS deploying it.
|
||||
#
|
||||
# The target lives in the user's checkout, so $INSTALL_PATH is only as
|
||||
# trustworthy as that path. That is fine here: focus-mode runs as a systemd
|
||||
# *user* service, so no privilege boundary is crossed.
|
||||
chmod +x "$DAEMON_SCRIPT"
|
||||
msg "Linking $INSTALL_PATH -> $DAEMON_SCRIPT"
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
install -m 755 "$DAEMON_SCRIPT" "$INSTALL_PATH"
|
||||
ln -sfn "$DAEMON_SCRIPT" "$INSTALL_PATH"
|
||||
else
|
||||
sudo install -m 755 "$DAEMON_SCRIPT" "$INSTALL_PATH"
|
||||
sudo ln -sfn "$DAEMON_SCRIPT" "$INSTALL_PATH"
|
||||
fi
|
||||
|
||||
# Create systemd user directory
|
||||
@ -159,8 +168,11 @@ uninstall_daemon() {
|
||||
# Reload daemon
|
||||
systemctl --user daemon-reload 2>/dev/null || true
|
||||
|
||||
# Remove installed script
|
||||
if [[ -f "$INSTALL_PATH" ]]; then
|
||||
# Remove installed script. -L as well as -e: $INSTALL_PATH is a symlink into
|
||||
# the checkout, and -e alone reports false for one whose target is gone -
|
||||
# exactly the case (repo moved or deleted) where the stale link most needs
|
||||
# clearing.
|
||||
if [[ -e "$INSTALL_PATH" || -L "$INSTALL_PATH" ]]; then
|
||||
msg "Removing daemon script..."
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
rm -f "$INSTALL_PATH"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user