Compare commits

...

18 Commits

Author SHA1 Message Date
6b92d87174 Delete the completed next-session handoff
Some checks failed
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
Both tasks it describes are done, verified live and pushed: manual picks can
be abandoned at any age with the cap at 2 (737b492), and every file in the
repo is under 250 lines (dd480f3, 2ff39ed). A finished task file is deleted,
not left behind.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 16:09:48 +02:00
2ff39edca4 Bring _web_dataset.py under the 250-line cap — cap campaign complete
_web_dataset.py  436 -> 178  + _web_models, _web_games, _web_pace

The six dataclasses (WebGame, WebStateInfo, WebDefaults, DefaultSummary,
PaceVsHLTB, WebDataset) are used by BOTH the parent and the helpers, so they
go to their own leaf model module that both import. Leaving them in the
parent is what created a circular import and broke ./run.sh on the previous
attempt.

All public names plus the seven private helpers tests reach for are
re-exported from _web_dataset via __all__, so import paths are unchanged.
Test patch targets split per class: TestBuildWebDataset, TestDatasetToPayload
and TestDatasetEndpoint still patch load_snapshot on _web_dataset (that
function did not move) while their cache patches move to _web_games.

`bash scripts/check_file_length.sh --all` now exits 0 — no file in the repo
is over 250 lines. 1344 tests, 100.00% coverage. Verified live: ./run.sh
status works and build_web_dataset projects all 958 games with pace and
summary sections intact; service at 0 restarts.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 16:08:12 +02:00
dd480f3208 Bring _stats.py and scanning.py under the 250-line cap
Leaf-set extraction only, so every new import is one-way and no cycle is
possible:

  _stats.py    523 -> 233   + _stats_types (the shared _GameTimes dataclass,
                              imported by parent and helpers alike),
                              _stats_gathering, _stats_display
  scanning.py  521 -> 248   + _scanning_candidates, _scanning_assign,
                              _scanning_tampering

_GameTimes and the four moved scanning helpers are re-exported from their
original modules via __all__ (mypy --no-implicit-reexport needs them listed),
so callers and tests keep their existing import paths.

Test patch targets were retargeted per file from the pytest failure list —
the target is the module whose source now contains the function under test.
Note TestPrintScenario and TestDoCheck did NOT move, so they keep the
original target while the rest of their files change.

1344 tests, 100.00% coverage. ./run.sh status and ./run.sh stats verified
against the live install; service at 0 restarts.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 16:00:54 +02:00
965abcaeaa Adopt the four markdown namespaces and gate them
Renames this repo's markdown onto README.md / CLAUDE*.md / DOCS*.md /
TODO*.md so a future session can tell a live task from a finished
record without reading the file to find out.

TODO files carry the literal "REMOVE ME AFTER FINISH" and are deleted
when the work lands. Enforced by the md-naming pre-commit hook and CI
workflow, both delegating to the shared gate in kuhyx/utils so this
repo's idea of a valid name cannot drift from every other repo's.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A47aX5DJwmA3QFn3pkEWi7
2026-08-24 15:54:34 +02:00
737b49246c Allow abandoning a manual pick at any time; cap picks at 2
The 4-day grace window left kuhy stuck: three picks locked in, the window
closed on two of them, so nothing could be abandoned and no new pick could
be added.

- abandon-pick now works however old the pick is. MANUAL_GRACE_DAYS,
  manual_pick_grace_remaining() and can_abandon_manual_pick() are deleted;
  abandon_manual_pick()'s existence check is the single remaining guard
  (the previous post-guard and its "race" test became unreachable).
- Config.max_manual_picks 3 -> 2. kuhy's config.json does not set the key,
  so the default change is sufficient.
- status/lock/MCP surfaces report informational age ("picked N day(s) ago",
  age_days) instead of a grace countdown. Note this is a sign flip, not a
  rename: age is now - started, where grace was deadline - now.

Verified live: abandoned Montaro (495890) and Battle Bruise (618510), both
previously refused as EXPIRED; pick-manual 3164500 now reaches its confirm
prompt at 1/2 slots used. 1344 tests, 100.00% coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 15:41:32 +02:00
0f25fba476 Bring the HLTB modules under the 250-line cap
_hltb_search sheds name matching (_hltb_matching) and the search request
itself (_hltb_search_api); _hltb_detail sheds page parsing
(_hltb_page_parse) and completionist/DLC extraction (_hltb_comp_extract).

Every extraction is a leaf set -- functions that call nothing else in their
module -- so each import stays one-way and no cycle is possible. Choosing
boundaries any other way is what made the earlier scanning/_stats attempt
fail, and those two are deliberately left for a later pass.

1347 tests, 100.00% coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 15:23:13 +02:00
8f010cfe46 Point the iptables tests at the module that now holds the code
aecfd1a moved _block_store_iptables into _store_iptables but left its tests
patching store_blocker.socket, which no longer exists there. My mistake: I
read a --no-cov run as green when it was not, and committed 3 failures.

1347 tests, 100.00% coverage, verified with the coverage run this time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 15:07:58 +02:00
aecfd1a3a0 Split store_blocker along its one-way call boundaries
Extract only functions that call nothing else in the module: the iptables/DNS
layer and the /etc/hosts protection helpers. A two-way split here does not
work -- block_store calls _reblock_hosts while _unblock_hosts calls
is_store_blocked, so cutting between them makes the import circular. Choosing
the leaf set instead keeps every import one-way and needed almost no test
churn, where the earlier attempt cascaded into a dozen patch-target fixes.

1347 tests, 100% coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 15:06:15 +02:00
d8ebbf978b Split _actions, _whitelist, _cmd_done and hltb under the cap
Each keeps its name and serves the moved names through a module __getattr__
(PEP 562) rather than a top-level re-export: every child imports back from
its parent, so a plain import would be circular. The lookup goes through
importlib.import_module, which is a call rather than an import statement,
so it needs no linter suppression. Return type is a _Reexport alias -- mypy
rejects `object` as not callable at the call sites, ruff rejects a bare Any.

Also fixes two leaks where tests wrote to the user's real config, both
caused by a redirected constant moving to a new module while conftest kept
patching the old one:

- APPROVED_EXCEPTIONS_FILE / EXCEPTION_AUDIT_LOG moved to _whitelist_locking;
  the suite had appended 27 fixture entries to the live exception_audit.log.
- _OWNED_IDS_CACHE_FILE was never redirected at all: it is derived from
  CONFIG_DIR at import time, so it captured the real path before the fixture
  could patch it, and the suite overwrote the user's owned-games cache.

Both are now verified by md5summing ~/.config/steam_backlog_enforcer before
and after a full run, which is the only check that actually catches this --
the tests pass either way.

1347 tests, 100.00% coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 14:55:57 +02:00
07e6e15b6e Split steam_api and _scanning_confidence under the cap
steam_api becomes a thin re-export over _steam_models (dataclasses) and
_steam_api_client (HTTP). Inverting it that way rather than moving the
client out and importing it back matters: _steam_api_client needs GameInfo,
so a re-export from the old module would have been a cycle. 47 call sites
import from steam_api and none of them change.

_scanning_confidence sheds the poll backfill/reporting pair into
_polls_reporting, and re-exports both.

Test patch targets follow the code: the tests for _report_poll_confidence
now patch _polls_reporting._echo, because that is where the name is bound.
Patching the re-exporting module intercepts nothing, and the test then
fails on an empty output list rather than an import error, which is why
these are worth being careful about.

1347 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 14:25:43 +02:00
9a2dd4fb73 Bring every test file under the 250-line cap
The pre-push ci-mirror runs the file-length gate over the whole tree, not
the diff, so ~30 files left it red and no push could land. This clears the
test half: 18 modules split into 60, plus the docstrings pylint wants on
every class and test method.

Splits are by responsibility, never mechanical partN names -- files are
named for the first class or test they contain (test_stats_sum_hours,
test_store_blocker_unblock_store, ...). Where a file was a single oversized
class, its test methods are partitioned into sibling classes instead, with
fixtures and helper classes copied into every part: a method-level split
that drops an autouse fixture fails at runtime, not at import, so it is easy
to miss.

test_polls_tracking_part2 keeps its name only because it still holds one
indivisible class; the rest of the partN files are gone.

1347 tests pass, unchanged in count and name from before the split -- the
splitter was checked by diffing test-function names, since a test silently
lost in a partition looks identical to one that never existed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 14:16:08 +02:00
919ecdfd62 Re-arm the no-library warning before install_game's early return
The one-shot latch that stops the "Steam library not initialised" warning
repeating every 3s was only cleared *after* the is_game_installed() early
return. So once Steam was signed in and a game was installed, the latch
stayed set: if the library later vanished the warning would never fire
again, and the outage would be silent.

Clear it at the top instead, before any return. Found by writing the test
for the latch's debug branch, which was the last uncovered code in the
package.

Coverage is now 100.00% (1347 tests) under .ci-mirror-venv, which is the
gate CI actually runs -- system python3 has mcp 2.0 against a pinned mcp<2,
so test_mcp*.py cannot collect there and coverage reads low.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 14:04:54 +02:00
21fe2f7742 Stop the enforcer launching Steam and notifications as root
The enforce service runs as root (no User=) but sets DISPLAY=:0, so any GUI
it starts lands on the desktop session. Two resolvers disagreed about who to
drop privileges to:

  library_hider._resolve_desktop_user()  read STEAM_ENFORCER_DESKTOP_USER
  game_install._get_real_user()          read only SUDO_USER or USER

systemd sets neither of the latter, so _get_real_user() returned None under
the service and every `geteuid() == 0 and real_user and ...` guard fell
through to running as root. Steam answered with a zenity modal ("Cannot run
as root user", /usr/lib/steam/steam:261) on screen.

Confirmed from the live process tree: root `bash /usr/lib/steam/steam
-cef-disable-gpu ... steam://install/618510` with a root zenity child. It
never reached the journal, because that text goes to zenity and _run_as_user
sends child output to DEVNULL.

- _desktop_env: add resolve_desktop_user/desktop_uid/desktop_user_cmd. Only
  the argv builder is shared, never the spawn call: tests/_no_subprocess.py
  patches subprocess per module by name, so a spawn site in an unpatched
  module could fire a real `sudo -u kuhy steam`.
- game_install._get_real_user: delegate to the shared resolver. This alone
  also fixes the root `steam -silent` in _ensure_steam_running and the
  no-op os.chown on new appmanifests.
- _trigger_steam_install / enforcer.send_notification: drop privileges.
  send_notification had no DBUS_SESSION_BUS_ADDRESS, so it silently reached
  nobody for all six of its callers.
- _run_as_user: fail closed. Running unchanged as root when no desktop user
  resolves is what put the modal on screen; refuse and log instead.

Also stop the retry storm behind it. steamapps does not exist (Steam has
never completed sign-in), so is_game_installed() was always False and the
loop re-triggered every allowed game every pass: 1656 attempts in 30
minutes, service RSS 1.5 GB (peak 4.3 GB), a FileNotFoundError traceback
each time. Guard install_game and _reinstall_missing_allowed on
steam_library_ready() -- a missing library means no install can succeed by
any route, so this is a correctness check rather than a tuned retry limit.

The module splits here are forced by the pre-commit 250-line gate, which
blocks any commit touching an over-cap file: game_install, library_hider and
_enforce_loop were already over before this change. They are split by
responsibility (_cdp transport, _steam_launch lifecycle, _steam_process
spawning, _steam_errors, _steam_client, _game_names, game_uninstall,
_enforce_steps, _owned_apps_cache, _echo, _protected_apps). game_install and
library_hider re-export their old public names, so the 15 modules that
import from them are untouched by this commit.

Verified as real root under the unit's environment: argv is now
`sudo -u kuhy env DISPLAY=:0 ... xdg-open steam://install/...` for both the
installer and notify-send; three enforce passes spawn no process and log
once; _run_as_user refuses with no desktop user. After restart: 0 retries,
0 tracebacks, 0 root-owned files under ~/.local/share/Steam, RSS 342 MB.

1311 tests pass. _desktop_env and _steam_state at 100% branch coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016A1EYiv7e7HGhET84oa9M3
2026-08-24 13:55:44 +02:00
2ad87524e4 Stop a non-interactive install aborting on the service prompt
The systemd-service question was a bare `read -rp`. Under `set -euo pipefail`
a read that hits EOF returns non-zero, so every caller without a TTY --
install_core_system.sh, CI, `vm run` -- aborted the installer with exit 1 at
that line, after the Python deps were already in place. That made the module
permanently un-installable from its documented install path.

It now defaults to "n" when stdin is not a terminal and says how to add the
service later; STEAM_ENFORCER_INSTALL_SERVICE=y opts in non-interactively.
The interactive path is unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PJrqKERAo5QUeEHWS5Asgp
2026-08-24 13:04:00 +02:00
740ec43767 Add a continuation prompt for the 250-line cap refactor
Captures the state at b5b4b35 (39 files over the cap, 1324 tests at 100%,
pylint 8.69) plus the decisions already settled, so the next session does
not re-litigate scope or repeat the two approaches that failed here:
a mechanical line-moving extractor (349 F821s, reverted) and find/replace
on patch targets that misses patch.object and multi-line forms.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPpmMpTSkp8UziRc5u8B7P
2026-08-23 20:55:24 +02:00
b5b4b35c07 Split total-block, playtime and MCP by responsibility
Each of these was one file doing several jobs, so they are split along
what they actually do rather than at arbitrary line offsets:

- _total_block: the lock file and the status derived from it stay in
  _total_block; making Steam *not installed* moves to _total_block_purge,
  making it *unreachable* to _total_block_hosts / _total_block_iptables.
  The generic pacman verbs (owner, installed, remove) become _pacman,
  since nothing about them is total-block-specific. Domain and process
  name tables become data modules.
- _playtime: budget state and persistence (_playtime_state), pure
  transitions (_playtime_budget), cmdline process detection
  (_playtime_procs), the warn/cutoff/kill ladder (_playtime_cutoff),
  desktop notifications (_playtime_notify), process-tree walking and
  killing (_playtime_kill), mountinfo parsing (_playtime_mountinfo) and
  the shared privileged-command helper (_playtime_run).
- _mcp: read-only tools (_mcp_query) split from mutating ones
  (_mcp_actions, _mcp_gaming_time), so "what can this server change?" is
  answerable from one file. _mcp keeps the server object and entry point.

No re-export shims: callers import from the module that defines the name.
That keeps a stale patch target loud (AttributeError) instead of letting
it pass while intercepting nothing.

`ruff check --select F821,F401` is run after every extraction -- an earlier
mechanical attempt moved functions without the module-level names they
referenced, which imported fine and only failed when called (349 errors),
so it was reverted and redone by hand.

The autouse fixtures in conftest are now imported by name and held by
__all__; ruff --unsafe-fixes had deleted them as unused, since pytest
resolves fixtures by name.

1324 tests pass at 100.00% coverage in the clean venv; `main status` is
byte-identical to a worktree at HEAD. 49 -> 39 files over the cap.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPpmMpTSkp8UziRc5u8B7P
2026-08-23 20:52:08 +02:00
45ff4eb7c2 Split main.py (1076 lines) into a main/ package
main.py became main/ with __main__.py, so the invocation string baked into
run.sh and the systemd unit (`python -m steam_backlog_enforcer.main`) stays
byte-identical and nothing needs redeploying. Commands are grouped into
sibling modules (status, install, picks, abandon, misc), with _shared.py as
a leaf holding the lock helpers and constants both need, and _registry.py
holding the command tables. main/__init__.py keeps every public and private
name importable, so `from steam_backlog_enforcer.main import X` is unchanged.

The subtle part is patch targets. The test suite builds them as
f"{PKG}.{name}", so a grep for the literal module path found nothing -- but
once a command moves to a submodule it resolves its dependencies from that
module's globals, and patching the main package's re-export silently stops
biting. Measured which of the 36 patched symbols moved: 8 could have passed
vacuously. Rather than repair PKG per class, the five test_main*.py files
(all cap violators anyway) were regrouped to mirror the production modules,
so each file has exactly one correct PKG. Verified by mutation: breaking a
line in status/misc/picks/_shared each makes the corresponding tests fail.

test_web_server.py patched main_mod.serve, which no longer intercepts
cmd_serve; repointed at main.misc and confirmed it fails when the call is
removed. Added tests for the __main__ shim, which coverage would otherwise
report at 0% under fail_under = 100.

Shared test builders live in tests/_main_helpers.py, reachable because the
Phase 0 name-tests-test exclude allows tests/_*.py.

1290 tests pass; every main/ module reports 100% coverage; `main`, `status`,
`bogus` and `--status` produce byte-identical output and exit codes to
pre-refactor. 55 -> 49 files over the cap.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPpmMpTSkp8UziRc5u8B7P
2026-08-23 19:56:34 +02:00
10c33690b9 Add the 250-line file-length gate as a pre-commit hook
Vendors ~/utils/file_length into scripts/file_length so the gate is
reachable in CI: pre-commit's `entry:` is not shell-expanded and GitHub
runners have no ~/utils, so an external reference would pass locally and
silently skip on push. The existing pre-commit/action all-files job picks
the hook up with no workflow change.

The vendored copy is excluded from ruff/ruff-format/mypy/pylint and must
stay byte-identical to upstream -- ruff --unsafe-fixes otherwise rewrites
its print() calls to `pass` (T201/F841), which leaves the gate exiting 1
while reporting nothing.

Also:
- name-tests-test now exempts tests/_*.py, so the 35 test-file splits have
  a landing zone for shared helpers (it rejects any non-test_*.py module
  under tests/).
- pylint max-module-lines 1000 -> 250, so both limits agree.

Note: .git/hooks/pre-commit was never installed in this repo (only
pre-push), so no commit-stage hook had ever run. Installed via
`pre-commit install`.

55 files are currently over the cap; they are split in following commits.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPpmMpTSkp8UziRc5u8B7P
2026-08-23 19:27:09 +02:00
238 changed files with 23442 additions and 17161 deletions

38
.github/workflows/md-naming.yml vendored Normal file
View File

@ -0,0 +1,38 @@
name: md-naming
# The four markdown namespaces, enforced on push as well as at commit time.
# The local pre-commit hook can be skipped (a fresh clone that never ran
# `pre-commit install` has no hooks at all), so the convention needs a second
# gate that no one can forget to install.
#
# Deliberately a SEPARATE workflow from any release job: a badly named doc
# should fail lint, not block publishing an artifact.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
md-naming:
name: markdown naming convention
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate and its exemption list live in the shared utils repo so every
# repo enforces the same namespaces. Checking it out beats vendoring a
# copy here, which is exactly how a gate and a survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Enforce the naming convention
run: bash .utils/scripts/check_md_naming.sh --all
# Warns only: no machine can prove a task is finished, so an old TODO
# gets a nudge, never a failure.
- name: Warn about stale TODOs
run: PYTHONPATH=.utils python3 .utils/md_naming/stale.py

View File

@ -29,6 +29,7 @@ repos:
- id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
exclude: ^steam_backlog_enforcer/tests/_[a-z_]+\.py$
- id: check-ast
- id: check-builtin-literals
- id: check-docstring-first
@ -51,6 +52,11 @@ repos:
entry: '(?i)#\s*ruff:\s*noqa'
language: pygrep
types: [python]
- id: file-length
name: Files must be at most 250 lines
entry: bash scripts/check_file_length.sh
language: system
types: [text]
- id: requirements-sync
name: requirements.txt covers all package imports
entry: python3 scripts/check_requirements_sync.py
@ -65,9 +71,11 @@ repos:
rev: v0.15.2
hooks:
- id: ruff
exclude: ^scripts/file_length/
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
types_or: [python, pyi]
- id: ruff-format
exclude: ^scripts/file_length/
types_or: [python, pyi]
# ===========================================================================
@ -77,6 +85,7 @@ repos:
rev: v1.13.0
hooks:
- id: mypy
exclude: ^scripts/file_length/
args:
- --ignore-missing-imports
- --no-error-summary
@ -109,6 +118,7 @@ repos:
rev: v3.3.2
hooks:
- id: pylint
exclude: ^scripts/file_length/
args:
- --rcfile=pyproject.toml
- --fail-under=8.0
@ -182,3 +192,13 @@ repos:
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
language: system
types: [shell]
# Four markdown namespaces (README / CLAUDE* / DOCS* / TODO*), plus the
# rule that a TODO carries "REMOVE ME AFTER FINISH" and nothing else may.
# Shared gate in ~/utils owns the namespaces and the exemption list, so
# one repo's idea of a valid name cannot drift from every other repo's.
- id: md-naming
name: markdown naming convention
entry: scripts/check_md_naming.sh
language: system
files: \.(md|markdown)$

16
AGENTS.md Normal file
View File

@ -0,0 +1,16 @@
do NOT run tests unless specifically instructed to do so or before committing
If tests fail on the same issue twice in a row, STOP and ask the user how to proceed instead of continuing to fix and retry.
ALWAYS confirm that the feature you add / bug you fixed behaves as it should by running the program after your changes (not tests!) and inspecting output comparing it with what user wanted, after confirming by yourself ask user if the program behaves as they intended
After running tests fix all coverage gaps and issues, do not ignore unless specifically instructed to do so
@/home/kuhy/.claude/rules/typescript-5-es2022.instructions.md
# Steam Backlog Enforcer Notes
- Fixed in commit 8b7bdb6: conftest.py safety net redirects all filesystem paths (STEAMAPPS_PATH, CONFIG_DIR, STATE_FILE, etc.) to tmp_path. Tests are safe to run without asking about state.json first.
- The pre-commit `pytest-coverage` hook is currently broken (measures all of python_pkg at 100%, not just the changed subpackage). There's an in-progress fix via `scripts/pytest_changed_packages.py` + `.pre-commit-config.yaml` change that still needs lint fixes.
- Clearing `hltb_cache.json` alone is not enough for `run.sh`/`done` reassignment: `snapshot.json` also stores `completionist_hours`, and stale snapshot values can still drive reassignment decisions unless refreshed.
- After fixing Steam Backlog Enforcer logic, always run a live verification pass with `python_pkg/steam_backlog_enforcer/run.sh` (or equivalent command) before declaring the fix done.
- cmd_done completion path can pick next game from snapshot-only hours; keep it aligned with HLTB cache/refresh before pick_next_game to avoid prologue-derived stale times (e.g., A Space 0.56h while cache has ~20h).
- HLTB renames games (e.g., "Needy Streamer Overload" → "NEEDY GIRL OVERDOSE"). The old name lives in `game_alias`. Both `game_name` and `game_alias` must be checked when matching — fixed in `_pick_best_hltb_entry`.
- **ALWAYS clear HLTB cache and re-run `run.sh` after changing the HLTB picking/matching algorithm.** Delete `~/.config/steam_backlog_enforcer/hltb_cache.json` (entire file, not just one entry) so all games get re-matched with the new logic. Then run `./run.sh` to verify correct results. Stale cache entries from the old algorithm will persist and hide bugs otherwise.

View File

@ -1,16 +0,0 @@
do NOT run tests unless specifically instructed to do so or before committing
If tests fail on the same issue twice in a row, STOP and ask the user how to proceed instead of continuing to fix and retry.
ALWAYS confirm that the feature you add / bug you fixed behaves as it should by running the program after your changes (not tests!) and inspecting output comparing it with what user wanted, after confirming by yourself ask user if the program behaves as they intended
After running tests fix all coverage gaps and issues, do not ignore unless specifically instructed to do so
@/home/kuhy/.claude/rules/typescript-5-es2022.instructions.md
# Steam Backlog Enforcer Notes
- Fixed in commit 8b7bdb6: conftest.py safety net redirects all filesystem paths (STEAMAPPS_PATH, CONFIG_DIR, STATE_FILE, etc.) to tmp_path. Tests are safe to run without asking about state.json first.
- The pre-commit `pytest-coverage` hook is currently broken (measures all of python_pkg at 100%, not just the changed subpackage). There's an in-progress fix via `scripts/pytest_changed_packages.py` + `.pre-commit-config.yaml` change that still needs lint fixes.
- Clearing `hltb_cache.json` alone is not enough for `run.sh`/`done` reassignment: `snapshot.json` also stores `completionist_hours`, and stale snapshot values can still drive reassignment decisions unless refreshed.
- After fixing Steam Backlog Enforcer logic, always run a live verification pass with `python_pkg/steam_backlog_enforcer/run.sh` (or equivalent command) before declaring the fix done.
- cmd_done completion path can pick next game from snapshot-only hours; keep it aligned with HLTB cache/refresh before pick_next_game to avoid prologue-derived stale times (e.g., A Space 0.56h while cache has ~20h).
- HLTB renames games (e.g., "Needy Streamer Overload" → "NEEDY GIRL OVERDOSE"). The old name lives in `game_alias`. Both `game_name` and `game_alias` must be checked when matching — fixed in `_pick_best_hltb_entry`.
- **ALWAYS clear HLTB cache and re-run `run.sh` after changing the HLTB picking/matching algorithm.** Delete `~/.config/steam_backlog_enforcer/hltb_cache.json` (entire file, not just one entry) so all games get re-matched with the new logic. Then run `./run.sh` to verify correct results. Stale cache entries from the old algorithm will persist and hide bugs otherwise.

1
CLAUDE.md Symbolic link
View File

@ -0,0 +1 @@
AGENTS.md

View File

@ -1,54 +0,0 @@
# Design audit — steam-backlog-enforcer
Generated against safe-design-rules (anthonyhobday.com/sideprojects/saferules).
Report only — nothing in this repo was changed by the audit itself.
Scope: `web/` (Vite/TS, 22 files). Token entry point: `web/src/index.css`
`:root` (lines 1-18). Reviewed fully alongside `App.tsx`, `FilterPanel.tsx`,
`GameTable.tsx`, `SummaryCards.tsx`, `TimelineChart.tsx`, `index.html`.
## web/ (Vite/TS frontend)
### Violations
- **Rule 1 (near-black/near-white)** — `web/src/index.css:9` — `--heading: #ffffff` is pure white while every other neutral (`--bg:#0f1117`, `--panel:#161922`, `--border:#2a2f3a`) is deliberately muted → give `--heading` a near-white value with the same cool tint, e.g. `#eef2f6`.
- **Rule 2 (saturate neutrals)** — `web/src/index.css:9` — `--heading:#ffffff` has zero saturation, breaking the otherwise-consistent cool-tinted neutral family (`--bg`, `--panel`, `--panel-2`, `--card`, `--border`, `--muted` all carry a slight blue hue) → tint it to match (see Rule 1 fix).
- **Rule 4 (everything deliberate)** — `web/src/index.css:203` and `:489` — `.seg.active { color: #06121c }` and `.badge { color: #1a1205 }` are one-off hardcoded "ink" colors with no token, unrelated to any other value in the file → promote to `--on-accent`/`--on-warn` custom properties so the choice is traceable and reusable.
- **Rule 6 (letter-spacing/line-height by size)** — `web/src/index.css:37-44` — only `h1` (26px) gets a letter-spacing adjustment (`-0.4px`, line 39); none of the 13 smaller sizes in the file (10px badge line 487, 11px axis-label line 404, 12px `.seg`/`.ghost` lines 199/214, 13px `.hint`/table/`.field label` lines 83/127/440) get any compensating letter-spacing or line-height increase → add a small positive letter-spacing (~0.1-0.2px) to the ≤13px tier.
- **Rule 9 (distinct brightness values)** — `web/src/index.css:10,12` — using the HSB-brightness metric the rule's thresholds are defined in (max(R,G,B)/255, matching Rule 18), `--accent` (#66c0f4) is 95.7% and `--warn` (#f0a23b) is 94.1% — only 1.6 points apart; `--accent-2` (81.2%) and `--danger` (89.0%) are well clear of both, so this is narrowly an accent-vs-warn issue, not a whole-palette one → nudge `--warn` a few points darker (e.g. `#e8952e`, ≈89% brightness) so it doesn't sit this close to `--accent`. Low priority: the two colors aren't used adjacently in the current UI (accent = numeric totals, warn = the "slower than leisure" insight label and the "no data" badge).
- **Rule 11 (mathematically related measurements)** — `web/src/index.css` throughout — spacing/radius values are 24, 20, 18, 14, 12, 10, 9, 8, 7, 6, 5, 4, 2, 1px (e.g. panel padding 18px line 111, card padding 14px line 275, th padding 9px line 448, td padding 7px line 462, ghost padding 5px line 210) with no shared base unit; radii alone use four unrelated hardcoded values (4px line 56, 6px lines 168/196/211, 8px lines 188/256/274/321/435, plus the `--radius:10px` token line 14) → consolidate onto one scale (e.g. 4px base: 4/8/12/16/20/24) and derive radii from `--radius` and `--radius-sm`.
- **Rule 13 (12-column grid)** — `web/src/index.css:90` and `:263` — `.layout` uses a fixed `320px 1fr` split and `.cards` uses `repeat(4, 1fr)` / `repeat(2, 1fr)` (line 268), neither derived from a shared 12-column track → define one grid scale (e.g. a `--grid-12` template) both layouts pull from, for future 1/2/3/4-up flexibility.
- **Rule 20 (body text ≥16px)** — `web/src/index.css:28` — `body { font: 15px/1.5 var(--sans); }` is below the 16px floor, and most UI text sits well under that: `.hint`/`.field label`/table/`.parity` at 13px (lines 83, 127, 247, 440), `.seg`/`.ghost`/`.card-blurb` at 12px (lines 199, 214, 286), `.preset`/`.axis-label` at 11px (lines 310, 404), `.badge` at 10px (line 487) → raise body copy to 16px minimum; for the dense data-table cells where 13px is a deliberate density trade-off, note that explicitly rather than leaving it as the default scale.
- **Rule 22 (button padding: horizontal = 2× vertical)** — `web/src/index.css:195` — `.seg { padding: 6px 4px; }` has horizontal padding *less* than vertical (should be ~2× more, e.g. `6px 12px`) → `.ghost` at `web/src/index.css:210` (`padding: 5px 10px`) already gets this right and can be the reference.
- **Rule 24 (nest corners properly)** — `web/src/index.css:188-196` — `.segmented { border-radius: 8px; padding: 4px; }` containing `.seg { border-radius: 6px; }`; per the rule the nested radius should be outer − gap = 8 − 4 = 4px, not 6px → change `.seg` to `border-radius: 4px`.
- **Rule 26 (no shadows in dark interfaces)** — `web/src/index.css:17` declares `color-scheme: dark` (bg `#0f1117`); `web/src/index.css:279` — `.card.active { box-shadow: 0 0 0 1px var(--accent); }` is technically a shadow in a dark UI → replace with a non-shadow selection indicator, e.g. `outline: 1px solid var(--accent)` or a border-color swap, which reads identically without invoking box-shadow. (Low severity: this is a 0-blur selection ring, not an elevation shadow, but it's the literal case the rule flags.)
### Not applicable
- Rule 5 (optical alignment) — no icons or asymmetric shapes in the codebase whose bounding-box center would differ from its visual center.
- Rule 8 (everything aligns with something else) — no misalignment identifiable from CSS/JSX alone; needs a rendered pass to verify.
- Rule 12 (order by visual weight) — layout-level judgment call (sidebar vs. content ordering); no clear violation visible in source.
- Rule 14 (space between high-contrast points) — requires visual inspection of rendered edges, not determinable from source.
- Rule 16 (drop shadow blur ≈ 2× distance) — the only `box-shadow` in the file (line 279) has 0 offset/0 blur, so the ratio rule doesn't meaningfully apply.
- Rule 21 (line length ~70 chars) — no long-form paragraph content; all text is short UI labels/hints.
- Rule 28 (lower icon contrast paired with text) — no dedicated icon glyphs; the only icon-like characters are the sort arrows (`▲`/`▼` in `web/src/components/GameTable.tsx:115`), which inherit the same color as the adjacent header text rather than being a separate heavier element.
### Passing
- Rule 3 (high contrast for important elements) — `.seg.active` (`web/src/index.css:202-204`) pairs `background: var(--accent)` with `color: #06121c`, a very high-contrast combination for the primary interactive state.
- Rule 7 (border contrast with both surfaces) — in HSB brightness, `--border:#2a2f3a` (22.7%) sits clearly above `--bg` (9%) and `--panel` (13.3%) wherever it's used as a divider. Caveat: against `--card:#1b2838` (22.0%) the gap is only 0.7 points — e.g. `.card { border: 1px solid var(--border) }` at `web/src/index.css:273` — border is technically still lighter but not "clearly" so; if card borders read as blurry in practice, lighten `--border` or darken `--card` by a few points.
- Rule 10 (warm OR cool neutrals) — all neutrals (`--bg`, `--panel`, `--panel-2`, `--card`, `--border`, `--muted`) carry a consistent cool/blue tint.
- Rule 15 (closer elements lighter) — HSB brightness (max(R,G,B)/255) increases monotonically through the stack: `--bg`(9.0%) < `--panel`(13.3%) < `--panel-2`(18.8%) < `--card`(22.0%) < `--border`(22.7%) < `--muted`(63.1%) < `--text`(87.5%) < `--heading`(100%).
- Rule 17 (simple on complex / complex on simple) — every surface in `index.css` is a single flat color; no competing textures or gradients anywhere.
- Rule 18 (container brightness limits) — HSB brightness deltas between stacked containers (`--bg`9.0%→`--panel`13.3%→`--panel-2`18.8%→`--card`22.0%) are all under 6 points, well within the ~12% dark-mode ceiling.
- Rule 19 (outer padding ≥ inner padding) — `.panel` outer padding 18px (line 111) ≥ `.field` internal spacing 12px (line 122); `.summary`/`.table-wrap` outer padding 18px ≥ `.cards`/`.table-head` gaps of 12px (lines 264, 425).
- Rule 23 (two typefaces max) — exactly two font families defined, `--sans` and `--mono` (`web/src/index.css:15-16`), used consistently.
- Rule 25 (avoid adjacent hard divides) — no cases of two borders/background-transitions touching directly; dividers (`.field` border-top, `.presets` border-top) are always separated by padding from any other border.
- Rule 27 (don't mix depth techniques) — the app uses exactly one depth technique (flat 1px borders, plus the single Rule-26-flagged ring shadow) — no mixing of soft/hard/glow styles.
### Notes
- The whole surface has exactly one token file (`web/src/index.css` `:root`, lines 1-18) — good centralization, no per-component duplicate palettes found in `App.tsx`, `FilterPanel.tsx`, `GameTable.tsx`, `SummaryCards.tsx`, or `TimelineChart.tsx` (no inline `style=` usage in any `.tsx` file).
- `--accent-bg` is referenced with a fallback (`web/src/index.css:254`, `var(--accent-bg, rgba(102, 192, 244, 0.12))`) but never defined in `:root` — it always resolves to the fallback. Not one of the 28 rules, but worth fixing alongside Rule 11 token consolidation since it's effectively a phantom token.
- Several violations (Rule 11 spacing scale, Rule 24 corner nesting, Rule 22 button padding) share a root cause: values were chosen per-component rather than pulled from a shared scale. Fixing Rule 11 first (defining a spacing/radius scale) would make the Rule 22/24 fixes mechanical rather than case-by-case.
- `web/coverage/` and `web/dist/` contain generated/build CSS (`base.css`, `prettify.css`, `assets/index-*.css`) — excluded from this audit since they're build artifacts, not source.

View File

@ -94,3 +94,5 @@ A refactor without a gate silently regrows. Before this task is done:
## Verify
Run the suite, then run the enforcer entry point. Do NOT restart the systemd unit or Steam while a game is running — ask first.
REMOVE ME AFTER FINISH

View File

@ -33,7 +33,22 @@ else
fi
# Install systemd service (system-level, runs as root).
read -rp "Install systemd enforce service? [y/N] " ans
#
# Non-interactive callers (install_core_system.sh, CI, `vm run`) have no stdin,
# where a bare `read` fails and -- under `set -e` -- aborts this whole installer
# with exit 1 after the Python deps are already in place. That made the module
# permanently un-installable from the documented install path. Default to "no"
# when there is no terminal, and let STEAM_ENFORCER_INSTALL_SERVICE=y opt in.
ans="${STEAM_ENFORCER_INSTALL_SERVICE:-}"
if [[ -z $ans ]]; then
if [[ -t 0 ]]; then
read -rp "Install systemd enforce service? [y/N] " ans
else
ans="n"
echo "No terminal: skipping the systemd enforce service."
echo "(Install it later with: sudo STEAM_ENFORCER_INSTALL_SERVICE=y bash install.sh)"
fi
fi
if [[ "${ans,,}" == "y" ]]; then
if [[ $EUID -ne 0 ]]; then
echo "Error: systemd service install needs root. Re-run with sudo."

View File

@ -133,3 +133,5 @@ something the name does not.
4. Every suppression you added is listed in the final report with its
justification. If you could not reach 10.00 without a suppression the user
would not accept, say so and report the real number instead.
REMOVE ME AFTER FINISH

View File

@ -0,0 +1,184 @@
# Session prompt: continue the 250-line cap refactor
Paste everything below the line into a fresh Claude Code session started in
`~/steam-backlog-enforcer`.
---
Continue `refactor_claude_todo.md`: get every file in this repo under 250 lines
and take pylint to a clean 10.00, without weakening either gate.
Earlier sessions landed the gate and the three hardest modules. **Re-measure
before you start** — the numbers below were true at commit `b5b4b35`.
## State at handoff
```bash
bash scripts/check_file_length.sh --all # 39 files over the cap
.ci-mirror-venv/bin/python -m pytest steam_backlog_enforcer/tests/ -q
# 1324 pass, 100.00% coverage
~/.cache/pre-commit/repo01lfw04p/py_env-python3/bin/pylint \
--rcfile=pyproject.toml --jobs=4 steam_backlog_enforcer scripts | tail -2
# 8.69/10
```
Already done (do not redo):
- **The gate is live.** `scripts/file_length/` is a vendored copy of
`~/utils/file_length/`, wired as the `file-length` pre-commit hook. It is
excluded from ruff/mypy/pylint and must stay byte-identical to upstream.
`pre-commit install` has been run (it never had been — only `pre-push`).
- `main.py` → `main/` package; `_total_block`, `_playtime`, `_mcp` split.
- `pyproject.toml`: `max-module-lines = 250`.
## Decisions already made — do not re-ask
1. **All 39 files this campaign**, then pylint. Both in scope.
2. **Gate stays on**: every commit must bring the files it touches under the
cap. `--no-verify` is banned.
3. **Coverage must stay at exactly 100%.** No pragmas, no omits.
4. **Split by responsibility, never mechanically.** See below.
5. **No private re-export shims.** Callers import from the defining module.
6. At the very end: raise pylint `--fail-under` 8.0 → **10.0** in
`.pre-commit-config.yaml` (a deliberate deviation from
`prompts/pylint-to-ten.md`, which says leave it — a score with no gate
regrows exactly like file length does).
## How to split (this is the part that goes wrong)
A generic "move these top-level defs to a sibling module" extractor was tried
and **reverted**: it moved functions without the module-level names they
referenced, so the result imported fine and only failed when called —
`ruff check --select F821` found 349 undefined names.
Per file:
1. **Read it.** Name the 2-4 jobs it does; the existing `# ────` section
banners usually mark the real seams.
2. Give each job a module whose docstring says why it is separate. Keep the
dependency direction one-way, leaf modules (data tables, generic helpers)
at the bottom. Pass a dependency as a parameter when that removes a cycle.
3. **Never** `module_x_1.py` / `module_x_2.py`. Extract genuinely reusable
helpers under their own name (`_pacman.py` came out of `_total_block` this
way and is now shared).
4. `ruff check --select F821,F401 --no-fix <files>` after **every** extraction.
**F821 first, then autofix F401** — the reverse order deletes imports the
moved code still needs.
5. Repoint the matching test file (below), then commit.
### Test files are the real cost
Tests build patch targets as `f"{PKG}.{name}"`, so grepping for the literal
module path finds nothing. Once a function moves, it resolves its dependencies
from its *new* module's globals, and a patch aimed at the old module silently
stops intercepting.
For each split:
```bash
# which module actually defines each patched symbol
.ci-mirror-venv/bin/python - <<'PY'
import importlib, re, pathlib
mods = {m: importlib.import_module(f"steam_backlog_enforcer.{m}") for m in (...)}
src = pathlib.Path("steam_backlog_enforcer/tests/test_X.py").read_text()
for s in sorted(set(re.findall(r'f"\{PKG\}\.(\w+)"', src))):
print(s, [m for m, mod in mods.items() if s in vars(mod)])
PY
```
Then split the test file so each output has **one correct `PKG`**, and
**mutation-test** at least one assertion per new module — break a line in the
production module, confirm the right test fails, restore. A passing test after
a split proves nothing on its own. Watch for these forms, which a naive
find/replace misses: `patch.object(mod, "name")`, the multi-line
`patch.object(\n mod, "name")`, and dotted `f"{PKG}.subprocess.run"`.
### Two traps that already cost time
- **ruff `--fix --unsafe-fixes` deletes autouse fixture imports** (pytest
resolves fixtures by name, so they look unused). `conftest.py` holds them
with an explicit `__all__` — keep it that way when adding more.
- **`conftest.py` is the filesystem safety net.** When a path constant moves
to a new module, update the conftest patch target in the *same* edit, then
confirm no test writes outside `tmp_path`.
## Remaining work, highest ROI first
Production (15) — the todo ranks by lines x commits/yr, so start here:
| lines | file |
|---:|:---|
| 555 | `library_hider.py` |
| 553 | `game_install.py` |
| 521 | `scanning.py` |
| 588 | `_hltb_search.py` |
| 523 | `_stats.py` |
| 436 | `_web_dataset.py` |
| 410 | `_enforce_loop.py` |
| 399 | `store_blocker.py` |
| 384 | `hltb.py` |
| 373 | `_hltb_detail.py` |
| 333 | `_cmd_done.py` |
| 298 | `_whitelist.py` |
| 282 | `_actions.py` |
| 281 | `steam_api.py` |
| 253 | `_scanning_confidence.py` |
Test files (24), largest first: `test_stats.py` 1072, `test_web_dataset.py`
620, `test_hltb_detail.py` 592, `test_store_blocker.py` 470,
`test_library_hider.py` 468, `test_hltb.py` 447, `test_scanning.py` 444, then
17 more between 255 and 417. Split these to **~200 lines, not 249** — the
pylint phase adds a docstring to every test function and would push a 249-line
file back over.
Then **pylint 8.69 → 10.00** per `prompts/pylint-to-ten.md`. ~1600 findings,
of which 1061 are `missing-function-docstring` in `tests/`. Fix
`duplicate-code` (R0801) by extracting shared test helpers, never by adding
`ignore-imports`/`ignore-signatures`. R0801 is cross-module so it is invisible
to the staged-files hook — acceptance is a **full-tree** run.
## Commands
Keep every command under ~10s; nothing over 60s.
```bash
# scoped test run for the file you just touched (~0.3s)
python3 -m pytest steam_backlog_enforcer/tests/test_<area>*.py -q --no-cov
# acceptance: use the clean venv, NOT system python3 (see below)
.ci-mirror-venv/bin/python -m pytest steam_backlog_enforcer/tests/ -q # ~21s
# before each commit
pre-commit run --files $(git diff --cached --name-only | tr '\n' ' ')
```
**System `python3` has `mcp 2.0.0` but `requirements.txt` pins `mcp<2`**, so
`test_mcp*.py` fails to collect and coverage reports ~97%. That is a local
environment artifact, not a regression — use `.ci-mirror-venv/bin/python` for
anything coverage-related. Do not "fix" it by moving the pin.
Long jobs (`scripts/ci_mirror.sh`, full-suite runs) go in the background with
`run_in_background: true` rather than a long foreground timeout.
## Done condition
- `bash scripts/check_file_length.sh --all` → exit 0, and the todo's literal
`bash ~/utils/scripts/check_file_length.sh --all` → exit 0 (running both
catches drift between the vendored copy and upstream).
- `.ci-mirror-venv/bin/python -m pytest steam_backlog_enforcer/tests/ -q` →
green at exactly 100%.
- Full-tree pylint → **10.00/10**, with `--fail-under=10.0` committed.
- `pre-commit run --all-files` passes.
- A staged 251-line file still makes `git commit` fail.
- `./run.sh` runs and its output is unchanged. To prove a refactor is
behaviour-preserving despite live Steam state changing under you, compare
against a worktree at HEAD rather than an older captured baseline:
`git worktree add --detach /tmp/wt HEAD` and diff the two runs.
## Verify
Run the enforcer entry point, show the output, and confirm with the user.
**Do NOT restart the systemd unit or Steam** — a real total-block/manual-pick
lock may be active on this machine; ask first.
REMOVE ME AFTER FINISH

View File

@ -36,7 +36,10 @@ include = ["steam_backlog_enforcer*"]
[tool.ruff]
target-version = "py310"
include = ["*.py", "**/*.py"]
exclude = [".git", ".venv", "__pycache__", "build", "dist", ".eggs"]
# scripts/file_length is a VENDORED copy of ~/utils/file_length and must stay
# byte-identical to upstream; ruff --unsafe-fixes otherwise strips its print()
# calls (T201) and silently guts the gate's reporting.
exclude = [".git", ".venv", "__pycache__", "build", "dist", ".eggs", "scripts/file_length"]
[tool.ruff.lint]
select = ["ALL"]
@ -121,7 +124,7 @@ disable = []
[tool.pylint.design]
min-public-methods = 0
max-module-lines = 1000
max-module-lines = 250
max-attributes = 10
[tool.pylint.typecheck]

40
scripts/check_file_length.sh Executable file
View File

@ -0,0 +1,40 @@
#!/bin/bash
# ============================================================================
# Fail if any file exceeds the shared 250-line cap.
#
# A file that cannot be read in one piece forces re-reads and partial edits,
# which is the largest avoidable cost in an LLM-assisted workflow. The cap
# applies to code AND prose; generated files, markup and data are exempt.
#
# This is a VENDORED copy of ~/utils/file_length/. It is vendored rather than
# referenced because pre-commit's `entry:` is not shell-expanded and CI
# runners have no ~/utils -- an external reference would pass locally and
# silently skip on push.
#
# Usage:
# scripts/check_file_length.sh <file> [<file> ...] # pre-commit passes these
# scripts/check_file_length.sh --all # whole tree, from cwd
# ============================================================================
set -euo pipefail
SCRIPTS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPTS_ROOT
readonly CHECKER="$SCRIPTS_ROOT/file_length/check.py"
main() {
if [[ $# -eq 0 ]]; then
echo "Usage: $(basename "$0") <file>... | --all" >&2
exit 1
fi
if [[ ! -f "$CHECKER" ]]; then
echo "Error: checker not found at $CHECKER" >&2
exit 1
fi
PYTHONPATH="$SCRIPTS_ROOT${PYTHONPATH:+:$PYTHONPATH}" \
python3 "$CHECKER" "$@"
}
main "$@"

32
scripts/check_md_naming.sh Executable file
View File

@ -0,0 +1,32 @@
#!/bin/bash
# ============================================================================
# Fail if any markdown file breaks the shared naming convention.
#
# Thin delegate to the shared gate in ~/utils, which owns the four namespaces
# (README / CLAUDE* / DOCS* / TODO*), the "REMOVE ME AFTER FINISH" marker rule
# and the exemption list. Copying that logic here is what lets one repo's idea
# of a valid name drift from every other repo's -- so this script only locates
# the shared checker and forwards its arguments.
#
# Usage:
# scripts/check_md_naming.sh <file> [<file> ...] # pre-commit passes these
# scripts/check_md_naming.sh --all # whole tree, from cwd
# ============================================================================
set -euo pipefail
readonly SHARED_GATE="${UTILS_ROOT:-$HOME/utils}/scripts/check_md_naming.sh"
main() {
if [[ ! -x "$SHARED_GATE" ]]; then
echo "Error: shared markdown-naming gate not found at $SHARED_GATE" >&2
echo " Clone github.com/kuhyx/utils to ~/utils, or set" >&2
echo " UTILS_ROOT to where it lives." >&2
exit 1
fi
exec bash "$SHARED_GATE" "$@"
}
main "$@"

View File

@ -0,0 +1,5 @@
"""Shared 250-line file-length cap: config, gate, and survey."""
from file_length.config import MAX_LINES
__all__ = ["MAX_LINES"]

View File

@ -0,0 +1,201 @@
"""Exemption tables for the 250-line file-length cap.
The data half: which extensions are capped, and which paths are generated,
vendored, third-party or session artifacts. :mod:`file_length.exemptions`
holds the rules that read these, and :mod:`file_length.config` re-exports
both as the public surface.
Duplicating these lists in shell is what lets a gate and a survey silently
disagree, so they live here once.
"""
from __future__ import annotations
import re
#: Hard cap. Files above this fail the gate. Code and prose alike.
MAX_LINES = 250
#: Extensions the cap applies to: real programming languages plus prose.
#: Markup (.html/.css/.scss) is deliberately absent -- templates split into
#: partials, not functions, so a line cap does not express anything useful.
CAPPED_EXTENSIONS = {
# code
".py",
".dart",
".ts",
".tsx",
".js",
".jsx",
".sh",
".bash",
".zsh",
".c",
".h",
".cpp",
".cc",
".hpp",
".go",
".rs",
".java",
".kt",
".kts",
".swift",
".rb",
".lua",
".sql",
".vue",
".cs",
".php",
# prose
".md",
".markdown",
".txt",
".rst",
".tex",
".org",
}
#: Generated files: regenerated by a tool, so splitting them is meaningless
#: (the tool would just rewrite the original next run).
GENERATED_PATTERN = re.compile(
r"\.g\.dart$"
r"|\.freezed\.dart$"
r"|\.gr\.dart$"
r"|\.config\.dart$"
r"|\.mocks\.dart$"
r"|\.min\.(js|css)$"
r"|\.pb\.(go|py)$"
r"|_pb2(_grpc)?\.py$"
r"|\.generated\.ts$"
r"|\.d\.ts$"
r"|/l10n/generated/"
r"|/generated/"
)
#: A marker in the first few lines also marks a file generated. Covers tools
#: that do not use a distinguishing extension.
GENERATED_MARKERS = (
"GENERATED CODE - DO NOT MODIFY",
"@generated",
"DO NOT EDIT",
"Autogenerated",
"AUTOGENERATED",
"generated by",
)
#: Directory names never descended into: dependencies, build output, caches.
EXCLUDED_DIRS = frozenset(
{
".git",
"node_modules",
".dart_tool",
"build",
".venv",
"venv",
"env",
"site-packages",
"target",
"ephemeral",
"__pycache__",
".mypy_cache",
".pytest_cache",
".ruff_cache",
"dist",
".next",
"vendor",
"third_party",
"Pods",
".gradle",
".idea",
".cxx",
"coverage",
"htmlcov",
".tox",
"Library",
"Temp",
"obj",
".terraform",
".fvm",
".angular",
".cache",
".svelte-kit",
"migrations",
".ci-mirror-venv",
".hippo",
".build-deps",
# Where CI checks out the shared gate itself (kuhyx/utils). Without
# this, a repo's lint job fails on utils' own long files -- a gate
# that fails for reasons the repo being gated cannot fix.
".utils",
}
)
#: Third-party content living *inside* a repo you own, keyed by repo dir name.
#: Verified by git remote / vendor manifest, not guessed.
VENDORED_SUBPATHS = {
"mcp-servers": ("servers",),
"dufs-cloud": ("app/assets/pdfjs", "web/assets/pdfjs"),
".claude": (
"projects",
"shell-snapshots",
"cache",
"backups",
"todos",
"statsig",
"history",
"chrome",
"downloads",
"plugins",
"ide",
),
# Agent skill bundles vendored from Anthropic (todo: commit f91311f).
# A SKILL.md is a fixed-name file with frontmatter; detail belongs in a
# sibling references/ dir, so splitting one into SKILL.part2.md would
# break the format rather than improve readability.
"todo": (".agents/skills",),
}
#: Directory names that mark a vendored agent-skill tree wherever they appear.
#: Keyed by name rather than repo because these bundles get dropped into any
#: repo that wants them, not just the one they were first seen in.
VENDORED_ANYWHERE = ("/.agents/skills/", "/.claude/skills/")
#: Frozen records of past agent sessions: an implementation plan or an
#: append-only session log describes what was done at one moment. Splitting one
#: rewrites a historical record for no reading benefit -- nobody navigates them,
#: they are read whole or not at all. Same category as generated files.
#:
#: Deliberately NOT the whole of docs/superpowers/: `specs/` and `contracts/`
#: stay capped, because those are living documents that get re-read and edited.
SESSION_ARTIFACTS_ANYWHERE = (
"/docs/superpowers/plans/",
"/docs/superpowers/sessions/",
)
#: Whole repos under ~ that are third-party clones, not kuhy's work.
#: Verified 2026-08-14 by `git remote get-url origin` + commit authors.
THIRD_PARTY_REPOS = frozenset(
{
"StringTheory", # github.com/AnthonySf/TheStringTheory
"reaper-mcp", # github.com/TwelveTake-Studios/reaper-mcp
"freesound-mcp", # github.com/timjrobinson/FreesoundMCPServer
"llama_cpp_dart_local", # generated FFI bindings
"aseprite-mcp",
"Mapperatorinator", # github.com/OliBomby/Mapperatorinator
"aur",
"build-your-own-x",
"build_your_x",
"byox-ladder",
"warriorjs",
"untools",
"awesome-mcp-explorer",
"runnerup",
"depotdownloader",
"actions-runner",
}
)
#: A `.txt` whose mean line is shorter than this is data (a wordlist, a
#: coordinate dump), not prose, so the cap does not apply.
DATA_TXT_MAX_MEAN_LINE = 25

View File

@ -0,0 +1,183 @@
"""Gate: fail if any given file exceeds the 250-line cap.
Invoked by `scripts/check_file_length.sh`, which pre-commit calls with the
staged files. Exits 1 and lists every violation; exits 0 silently otherwise.
The check is deliberately deterministic code rather than a judgement call --
adjudication belongs in an exit code, not in a model.
"""
from __future__ import annotations
import argparse
import os
from pathlib import Path
import subprocess
import sys
if __package__ in (None, ""): # invoked as a plain script
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from file_length.config import (
CAPPED_EXTENSIONS,
EXCLUDED_DIRS,
MAX_LINES,
is_data_text,
is_generated,
is_session_artifact,
is_vendored,
)
def count_lines(path: Path) -> int | None:
"""Number of lines, or None if the file is binary or unreadable."""
try:
with path.open("rb") as handle:
first = handle.read(8192)
if b"\x00" in first:
return None
count = first.count(b"\n")
while chunk := handle.read(1 << 20):
count += chunk.count(b"\n")
if first and not first.endswith(b"\n") and count == 0:
count = 1
return count
except OSError:
return None
def absolutize(path: Path) -> Path:
"""`path` anchored at the cwd, without resolving symlinks.
The exemption rules are written against full paths ('/.claude/skills/'),
but pre-commit passes paths relative to the repo root ('skills/x.md') while
--all walks absolute ones. Matching a relative path against those rules
silently drops the repo-name context, so the same file passed the gate one
way and failed it the other.
Deliberately NOT `Path.resolve()`: build and asset dirs here are symlinks
out to ../testsAndMisc_builds/, and resolving would move those paths
outside the repo and change which exemptions match.
"""
return path if path.is_absolute() else Path.cwd() / path
def exempt_reason(path: Path, lines: int) -> str | None:
"""Why this file is not subject to the cap, or None if it is subject."""
if path.suffix.lower() not in CAPPED_EXTENSIONS:
return "not a capped extension"
if is_vendored(absolutize(path)):
return "vendored / third-party"
if is_session_artifact(absolutize(path)):
return "frozen session artifact"
if is_generated(path):
return "generated"
try:
size = path.stat().st_size
except OSError:
return "unreadable"
if is_data_text(path, lines, size):
return "data-ish text (wordlist)"
return None
def git_ignored(paths: list[Path], root: Path) -> set[Path]:
"""The subset of `paths` that git ignores, empty if root is not a repo.
Git-ignored files are build output or generated data the repo does not
own -- an app's own export (todo's BACKLOG.md), a log, a scratch dump.
They are rewritten wholesale by whatever produces them, so splitting one
is meaningless: the next run restores the original. Pre-commit never sees
them either (they cannot be staged), so skipping them makes --all agree
with the hook instead of failing on files no commit could ever fix.
"""
if not paths:
return set()
try:
result = subprocess.run(
["git", "-C", str(root), "check-ignore", "--stdin"],
input="\n".join(str(p) for p in paths),
capture_output=True,
text=True,
check=False,
)
except OSError: # git not installed
return set()
# 0 = some ignored, 1 = none ignored, 128 = not a repo.
if result.returncode not in (0, 1):
return set()
return {Path(line) for line in result.stdout.splitlines() if line}
def iter_all(root: Path):
"""Every file under root, skipping excluded and git-ignored files."""
found: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
dirnames[:] = [d for d in dirnames if d not in EXCLUDED_DIRS]
for name in filenames:
candidate = Path(dirpath) / name
if not candidate.is_symlink():
found.append(candidate)
ignored = git_ignored(found, root)
return [path for path in found if path not in ignored]
def main() -> int:
parser = argparse.ArgumentParser(
description=f"Fail if any file exceeds {MAX_LINES} lines."
)
parser.add_argument("paths", nargs="*", type=Path)
parser.add_argument(
"--all",
action="store_true",
help="check the whole tree under the current directory",
)
parser.add_argument(
"--explain", action="store_true", help="also report why files were skipped"
)
args = parser.parse_args()
if args.all:
targets = list(iter_all(Path.cwd()))
elif args.paths:
# Explicitly-named paths get the same git-ignore skip as --all, so
# naming a file directly cannot report a violation the hook never
# would. Without this the two modes disagree on exactly the files
# no commit could ever fix (todo's exported BACKLOG.md, logs).
existing = [p for p in args.paths if p.is_file()]
ignored = git_ignored(existing, Path.cwd())
targets = [p for p in existing if p not in ignored]
else:
parser.error("give file paths or --all")
violations: list[tuple[Path, int]] = []
for path in targets:
if not path.is_file():
continue
lines = count_lines(path)
if lines is None:
continue
reason = exempt_reason(path, lines)
if reason is not None:
if args.explain:
print(f" skip {path}: {reason}")
continue
if lines > MAX_LINES:
violations.append((path, lines))
if not violations:
return 0
print(
f"File-length gate FAILED: {len(violations)} file(s) over {MAX_LINES} lines\n",
file=sys.stderr,
)
for path, lines in sorted(violations, key=lambda item: -item[1]):
over = lines - MAX_LINES
print(f" {path}: {lines} lines (over by {over})", file=sys.stderr)
print("\nSplit them, or see refactor_claude_todo.md in this repo.", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,45 @@
"""Shared configuration for the 250-line file-length cap.
Single source of truth for the cap and its exemptions, imported by both the
pre-commit gate (`check.py`) and the survey. This module is the public
surface: :mod:`file_length._tables` holds the data, and
:mod:`file_length.exemptions` the rules that read it.
"""
from __future__ import annotations
from file_length._tables import (
CAPPED_EXTENSIONS,
DATA_TXT_MAX_MEAN_LINE,
EXCLUDED_DIRS,
GENERATED_MARKERS,
GENERATED_PATTERN,
MAX_LINES,
SESSION_ARTIFACTS_ANYWHERE,
THIRD_PARTY_REPOS,
VENDORED_ANYWHERE,
VENDORED_SUBPATHS,
)
from file_length.exemptions import (
is_data_text,
is_generated,
is_session_artifact,
is_vendored,
)
__all__ = [
"CAPPED_EXTENSIONS",
"DATA_TXT_MAX_MEAN_LINE",
"EXCLUDED_DIRS",
"GENERATED_MARKERS",
"GENERATED_PATTERN",
"MAX_LINES",
"SESSION_ARTIFACTS_ANYWHERE",
"THIRD_PARTY_REPOS",
"VENDORED_ANYWHERE",
"VENDORED_SUBPATHS",
"is_data_text",
"is_generated",
"is_session_artifact",
"is_vendored",
]

View File

@ -0,0 +1,82 @@
"""Predicates deciding whether a file is exempt from the 250-line cap.
Split from :mod:`file_length.config`, which holds the tables these read.
Keeping the rules separate from the data they consult means a new exemption
is a table entry, not a new branch, and the gate and the survey keep sharing
one definition of "exempt".
Re-exported from :mod:`file_length.config`, so existing
``from file_length.config import is_generated`` imports keep working.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from file_length._tables import (
DATA_TXT_MAX_MEAN_LINE,
EXCLUDED_DIRS,
GENERATED_MARKERS,
GENERATED_PATTERN,
SESSION_ARTIFACTS_ANYWHERE,
THIRD_PARTY_REPOS,
VENDORED_ANYWHERE,
VENDORED_SUBPATHS,
)
if TYPE_CHECKING:
from pathlib import Path
def is_generated(path: Path) -> bool:
"""True if the file is tool-generated and must not be split by hand."""
if GENERATED_PATTERN.search(path.as_posix()):
return True
try:
with path.open("r", encoding="utf-8", errors="replace") as handle:
head = "".join(next(handle, "") for _ in range(5))
except OSError:
return False
return any(marker in head for marker in GENERATED_MARKERS)
def is_data_text(path: Path, lines: int, size: int) -> bool:
"""True for wordlist-style .txt: many lines, very short ones."""
if path.suffix.lower() != ".txt" or lines <= 0:
return False
return (size / lines) < DATA_TXT_MAX_MEAN_LINE
def is_vendored(path: Path) -> bool:
"""True if the path sits under a known vendored subtree or excluded dir.
Callers must pass an absolute path (see `check.absolutize`). Every rule
below needs the repo-name context that a repo-relative path has already
thrown away: '/.claude/skills/' cannot match 'skills/x.md', so a relative
path would quietly skip the exemption instead of applying it.
"""
parts = path.parts
if any(part in EXCLUDED_DIRS for part in parts):
return True
posix = path.as_posix()
if any(marker in posix for marker in VENDORED_ANYWHERE):
return True
for repo, subs in VENDORED_SUBPATHS.items():
for sub in subs:
if f"/{repo}/{sub}/" in posix:
return True
return any(f"/{repo}/" in posix for repo in THIRD_PARTY_REPOS)
def is_session_artifact(path: Path) -> bool:
"""True for a frozen agent-session record (a plan or a session log).
Kept separate from `is_vendored` so the gate reports why a file is exempt:
these are kuhy's own files, not third-party code.
Callers must pass an absolute path (see `check.absolutize`), for the same
reason `is_vendored` does -- a repo-relative path has already dropped the
leading directory these markers match on.
"""
posix = path.as_posix()
return any(marker in posix for marker in SESSION_ARTIFACTS_ANYWHERE)

View File

@ -9,35 +9,24 @@ there is a single tested implementation of the underlying behaviour.
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any
from datetime import datetime, timezone
import importlib
from typing import TYPE_CHECKING, Any, TypeAlias
from steam_backlog_enforcer._allowed_games import (
active_manual_picks,
allowed_games,
)
from steam_backlog_enforcer._total_block import get_total_block_status
from steam_backlog_enforcer.game_install import get_installed_games, is_protected_app
# Marks these two as an intentional re-export (they're imported from
# _allowed_games above, not defined here) -- without this, mypy's
# --no-implicit-reexport flags every downstream `from _actions import
# active_manual_picks` as an error. Everything else in this file is
# accessible normally; this only needs to list names imported-then-reexported.
__all__ = [
"active_manual_picks",
"allowed_games",
]
from steam_backlog_enforcer.store_blocker import is_store_blocked
if TYPE_CHECKING:
from steam_backlog_enforcer.config import State
# Mistake-correction window: for this many days after a manual pick the user
# may still back out via ``abandon-pick``. Deliberately short — it exists to
# undo a wrong pick, not to serve as an escape hatch from the lock.
MANUAL_GRACE_DAYS = 4
# How long an abandoned pick stays out of the auto-assignment pool, so that
# ``scan`` does not immediately hand back the game the user just rejected.
ABANDON_COOLDOWN_DAYS = 30
@ -160,123 +149,30 @@ def apply_manual_pick(
return None
def manual_pick_grace_remaining(state: State, app_id: int) -> float | None:
"""Return days left in *app_id*'s grace window, or ``None``.
``None`` means "no grace window applies": *app_id* is not an active manual
pick, or its timestamp is missing/malformed. A value <= 0 means the window
has closed.
Args:
state: The loaded enforcer state.
app_id: The manually-picked app id to measure.
Returns:
Fractional days remaining before the pick can no longer be abandoned,
or ``None`` when the question does not apply.
"""
pick = find_manual_pick(state, app_id)
if pick is None or not pick.get("started_at"):
return None
try:
started = datetime.fromisoformat(pick["started_at"])
except ValueError:
return None
deadline = started + timedelta(days=MANUAL_GRACE_DAYS)
return (deadline - datetime.now(timezone.utc)).total_seconds() / 86400
def can_abandon_manual_pick(state: State, app_id: int) -> bool:
"""Return ``True`` if *app_id* is still inside its grace window.
Args:
state: The loaded enforcer state.
app_id: The manually-picked app id to check.
Returns:
Whether ``abandon_manual_pick`` would be accepted right now.
"""
remaining = manual_pick_grace_remaining(state, app_id)
return remaining is not None and remaining > 0
def abandon_manual_pick(state: State, app_id: int) -> bool:
"""Drop one manual pick and persist ``state``, if still inside its grace window.
Only the named pick is dropped: any other active pick keeps its own lock
and deadline. The abandoned app id goes onto the existing skip cooldown so
``scan`` will not hand the same game straight back. State-only: like
``apply_manual_pick`` this performs no uninstall/hide cascade, so the MCP
server can call it without touching the filesystem.
Args:
state: The enforcer state to mutate and save.
app_id: The manually-picked app id to back out of.
Returns:
``True`` if the pick was abandoned, ``False`` if its grace window has
closed (or it is not an active pick), in which case ``state`` is
untouched.
"""
if not can_abandon_manual_pick(state, app_id):
return False
state.skip_for_days(app_id, ABANDON_COOLDOWN_DAYS)
state.manual_picks = [
p for p in active_manual_picks(state) if p.get("app_id") != app_id
]
# The abandoned pick may also have been the current assignment; hand the
# assignment to a surviving pick so the enforcer keeps guarding it, or
# clear it so 'scan' can reassign.
if state.current_app_id == app_id:
survivor = state.manual_picks[-1] if state.manual_picks else None
state.current_app_id = survivor["app_id"] if survivor else None
state.current_game_name = survivor["game_name"] if survivor else ""
state.save()
return True
def status_payload(state: State) -> dict[str, Any]:
"""Build the structured status snapshot that ``cmd_status`` renders as text.
Pure data, no stdout — safe for the MCP server. Reads only ``State`` and the
stdout-free leaf helpers; never constructs ``Config`` and never exposes the
Steam API key.
Args:
state: The loaded enforcer state.
Returns:
A JSON-ready dict describing the current enforcement status.
"""
total_block = get_total_block_status()
installed = get_installed_games()
real_games = [(aid, name) for aid, name in installed if not is_protected_app(aid)]
assigned_installed = (
any(aid == state.current_app_id for aid, _ in installed)
if state.current_app_id
else None
)
return {
"current_app_id": state.current_app_id,
"current_game_name": state.current_game_name or None,
"finished_count": len(state.finished_app_ids),
"store_blocked": is_store_blocked(),
"installed_count": len(real_games),
"assigned_game_installed": assigned_installed,
"total_block": {
"active": total_block.active,
"days_remaining": round(total_block.days_remaining, 1),
"until": total_block.until.isoformat() if total_block.until else None,
},
"manual_pick_locked": is_manual_pick_locked(state),
"manual_picks": [
{
**pick,
"grace_days_left": manual_pick_grace_remaining(state, pick["app_id"]),
}
for pick in active_manual_picks(state)
],
_MOVED_TO_MANUAL_PICK_LIFECYCLE = frozenset(
{
"abandon_manual_pick",
"manual_pick_age_days",
"status_payload",
}
)
# Whatever the re-exported name turns out to be -- a function, a class or
# a constant. Aliased so the annotation is a name rather than a bare Any.
_Reexport: TypeAlias = Any
def __getattr__(name: str) -> _Reexport:
"""Re-export the names that moved to :mod:`_manual_pick_lifecycle`.
Deferred rather than imported at the top because _manual_pick_lifecycle imports
back from this module, so a module-level import would be circular.
"""
if name in _MOVED_TO_MANUAL_PICK_LIFECYCLE:
module = importlib.import_module(
"steam_backlog_enforcer._manual_pick_lifecycle",
)
return getattr(module, name)
msg = f"module {__name__!r} has no attribute {name!r}"
raise AttributeError(msg)

View File

@ -0,0 +1,95 @@
"""Chrome DevTools Protocol transport for Steam's embedded browser.
Modern Steam runs its UI in CEF, so collections can only be changed by
evaluating JS inside it. Split out of
:mod:`steam_backlog_enforcer.library_hider` to keep both files under the
250-line cap: this module is pure transport and knows nothing about
collections.
"""
from __future__ import annotations
import asyncio
import json
import logging
import requests
import websockets
logger = logging.getLogger(__name__)
# NOTE: was 8080, which collided with a different local service (Open WebUI)
# already bound to 0.0.0.0:8080. requests to 127.0.0.1:8080 resolved to that
# service instead of steamwebhelper's CDP endpoint (which only bound
# [::1]:8080), so CDP detection silently never worked. 9222 is the
# conventional Chrome DevTools debug port and was confirmed free.
_CDP_PORT = 9222
_CDP_TIMEOUT = 120
# ──────────────────────────────────────────────────────────────
# CDP (Chrome DevTools Protocol) helpers
# ──────────────────────────────────────────────────────────────
def _get_shared_js_ws_url() -> str | None:
"""Query the CDP HTTP endpoint and return the SharedJSContext WS URL."""
try:
resp = requests.get(f"http://127.0.0.1:{_CDP_PORT}/json", timeout=5)
targets = resp.json()
except (OSError, ValueError):
return None
for target in targets:
if target.get("title") == "SharedJSContext":
ws_url: str = target["webSocketDebuggerUrl"]
return ws_url
return None
async def _evaluate_js_async(ws_url: str, expression: str) -> dict:
"""Connect to a CDP WebSocket target and evaluate *expression*."""
async with websockets.connect(ws_url) as ws:
msg = json.dumps(
{
"id": 1,
"method": "Runtime.evaluate",
"params": {
"expression": expression,
"returnByValue": True,
"awaitPromise": True,
},
}
)
await ws.send(msg)
resp = await asyncio.wait_for(ws.recv(), timeout=_CDP_TIMEOUT)
return json.loads(resp)
def _evaluate_js(expression: str) -> dict:
"""Synchronous wrapper around :func:`_evaluate_js_async`."""
ws_url = _get_shared_js_ws_url()
if ws_url is None:
msg = "SharedJSContext not found on CDP port"
raise RuntimeError(msg)
return asyncio.run(_evaluate_js_async(ws_url, expression))
def _cdp_result_value(result: dict) -> str:
"""Extract the return value from a CDP Runtime.evaluate response."""
outer = result.get("result", {})
inner = outer.get("result", {})
if "exceptionDetails" in outer:
exc_details = outer["exceptionDetails"]
exc = exc_details.get("exception", {})
desc = (
inner.get("description")
or exc.get("description")
or exc_details.get("text")
or repr(exc_details)
)
logger.debug("CDP exception details: %s", exc_details)
msg = f"JS evaluation error: {desc}"
raise RuntimeError(msg)
value: str = inner.get("value", "")
return value

View File

@ -2,21 +2,14 @@
from __future__ import annotations
import importlib
import logging
import sys
from typing import TYPE_CHECKING, Any, TypeAlias
from steam_backlog_enforcer._actions import allowed_app_ids
from steam_backlog_enforcer._enforce_loop import get_all_owned_app_ids
from steam_backlog_enforcer.config import Config, State, load_snapshot
from steam_backlog_enforcer.enforcer import (
enforce_allowed_game,
send_notification,
)
from steam_backlog_enforcer.config import State, load_snapshot
from steam_backlog_enforcer.game_install import (
_echo,
install_game,
is_game_installed,
uninstall_other_games,
)
from steam_backlog_enforcer.hltb import (
fetch_hltb_confidence_cached,
@ -25,9 +18,9 @@ from steam_backlog_enforcer.hltb import (
load_hltb_polls_cache,
save_hltb_cache,
)
from steam_backlog_enforcer.library_hider import try_hide_other_games
from steam_backlog_enforcer.scanning import pick_next_game
from steam_backlog_enforcer.steam_api import GameInfo, SteamAPIClient
if TYPE_CHECKING:
from steam_backlog_enforcer.steam_api import GameInfo
_REASSIGN_REFRESH_LIMIT = 50
_SKIP_DAYS = 7
@ -181,153 +174,28 @@ def _refresh_uncached_shortlist_hours(
hltb_cache.update(refreshed)
def _finalize_completion(
config: Config,
state: State,
game_name: str,
app_id: int,
) -> None:
"""Mark game complete, pick next, hide non-assigned games, notify."""
_echo(f"\n COMPLETED: {game_name}!")
state.finished_app_ids.append(app_id)
snapshot_data = load_snapshot()
_echo("\nPicking next game...")
if not snapshot_data:
_echo(" No snapshot found. Run 'scan' first.")
state.current_app_id = None
state.current_game_name = ""
state.save()
return
games = [GameInfo.from_snapshot(d) for d in snapshot_data]
hltb_cache = load_hltb_cache()
skip = set(state.finished_app_ids) | state.active_skipped_ids()
_refresh_uncached_shortlist_hours(games, hltb_cache, skip)
_apply_cached_hours_to_games(games, hltb_cache)
pick_next_game(games, state, config, on_select=_prompt_keep_or_skip)
if state.current_app_id is None:
_echo(" No more games to assign!")
return
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f"\n Library hiding: skipped ({skipped})")
elif hidden > 0:
_echo(f"\n Library: hid {hidden} games")
if not is_game_installed(state.current_app_id):
logger.info(
"Assigned game still missing after library reconciliation; "
"re-triggering install"
)
_echo(
"\n Assigned game still missing after library reconciliation; "
"re-triggering install..."
)
_echo(f"\n Auto-installing {state.current_game_name}...")
install_game(
state.current_app_id,
state.current_game_name,
config.steam_id,
use_steam_protocol=True,
)
send_notification(
"Game Complete!",
f"Finished {game_name}! Now playing: {state.current_game_name}",
)
_echo(f"\nAll done! Go play {state.current_game_name}!")
_MOVED_TO_CMD_DONE_FINALIZE = frozenset(
{
"_enforce_on_done",
"_finalize_completion",
"cmd_done",
}
)
def _enforce_on_done(config: Config, state: State) -> None:
"""Run a single enforcement pass during the 'done' command.
# Whatever the re-exported name turns out to be -- a function, a class or
# a constant. Aliased so the annotation is a name rather than a bare Any.
_Reexport: TypeAlias = Any
Kills unauthorized game processes, uninstalls unauthorized games,
and ensures the assigned game is installed.
def __getattr__(name: str) -> _Reexport:
"""Re-export the names that moved to :mod:`_cmd_done_finalize`.
Deferred rather than imported at the top because _cmd_done_finalize imports
back from this module, so a module-level import would be circular.
"""
if state.current_app_id is None:
return
if config.kill_unauthorized_games:
violations = enforce_allowed_game(
allowed_app_ids(state),
kill_unauthorized=True,
)
for pid, app_id in violations:
_echo(f" Killed unauthorized game: AppID={app_id} (PID={pid})")
if config.uninstall_other_games:
count = uninstall_other_games(allowed_app_ids(state))
if count:
_echo(f" Uninstalled {count} unauthorized game(s)")
if not is_game_installed(state.current_app_id):
_echo(f" Re-installing {state.current_game_name}...")
install_game(
state.current_app_id,
state.current_game_name,
config.steam_id,
use_steam_protocol=True,
)
# Reconcile library: hide non-assigned games and unhide the assigned one.
# Without this, an interrupted earlier completion can leave the new
# assigned game hidden and stale games visible.
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
elif hidden > 0:
_echo(f" Library: hid {hidden} games")
def cmd_done(config: Config, state: State) -> None:
"""Check completion, pick next game, uninstall & hide.
All-in-one command for after finishing a game:
1. Verify 100% achievements on Steam.
2. Pick the next game (shortest HLTB leisure+dlc time).
3. Uninstall all non-assigned games.
4. Hide all non-assigned games in the Steam library.
5. Install the newly assigned game.
"""
if state.current_app_id is None:
_echo("No game currently assigned. Run 'scan' first.")
return
client = SteamAPIClient(config.steam_api_key, config.steam_id)
game_name = state.current_game_name
app_id = state.current_app_id
_echo(f"Checking {game_name} (AppID={app_id})...")
game = client.refresh_single_game(app_id, game_name)
if game is None:
_echo(" Could not fetch achievement data from Steam.")
return
_echo(
f" Progress: {game.unlocked_achievements}/{game.total_achievements}"
f" ({game.completion_pct:.1f}%)"
)
hltb_cache = load_hltb_cache()
hours = hltb_cache.get(app_id, -1.0)
if hours < 0:
hltb_cache = fetch_hltb_times_cached([(app_id, game_name)])
hours = hltb_cache.get(app_id, -1.0)
if hours > 0:
_echo(f" HLTB leisure+dlc estimate: {hours:.1f} hours")
_report_assigned_confidence(app_id, state)
if not game.is_complete:
remaining = game.total_achievements - game.unlocked_achievements
_echo(f"\n NOT COMPLETE: {remaining} achievements remaining. Keep going!")
_enforce_on_done(config, state)
return
_finalize_completion(config, state, game_name, app_id)
if name in _MOVED_TO_CMD_DONE_FINALIZE:
module = importlib.import_module("steam_backlog_enforcer._cmd_done_finalize")
return getattr(module, name)
msg = f"module {__name__!r} has no attribute {name!r}"
raise AttributeError(msg)

View File

@ -0,0 +1,192 @@
"""Finalising a completed game and re-enforcing afterwards.
Split out of :mod:`steam_backlog_enforcer._cmd_done` to keep both files
under the 250-line cap.
"""
from __future__ import annotations
import logging
from steam_backlog_enforcer._actions import allowed_app_ids
from steam_backlog_enforcer._cmd_done import (
_apply_cached_hours_to_games,
_prompt_keep_or_skip,
_refresh_uncached_shortlist_hours,
_report_assigned_confidence,
)
from steam_backlog_enforcer._enforce_loop import get_all_owned_app_ids
from steam_backlog_enforcer.config import Config, State, load_snapshot
from steam_backlog_enforcer.enforcer import (
enforce_allowed_game,
send_notification,
)
from steam_backlog_enforcer.game_install import (
_echo,
install_game,
is_game_installed,
uninstall_other_games,
)
from steam_backlog_enforcer.hltb import (
fetch_hltb_times_cached,
load_hltb_cache,
)
from steam_backlog_enforcer.library_hider import try_hide_other_games
from steam_backlog_enforcer.scanning import pick_next_game
from steam_backlog_enforcer.steam_api import GameInfo, SteamAPIClient
_REASSIGN_REFRESH_LIMIT = 50
_SKIP_DAYS = 7
logger = logging.getLogger(__name__)
def _finalize_completion(
config: Config,
state: State,
game_name: str,
app_id: int,
) -> None:
"""Mark game complete, pick next, hide non-assigned games, notify."""
_echo(f"\n COMPLETED: {game_name}!")
state.finished_app_ids.append(app_id)
snapshot_data = load_snapshot()
_echo("\nPicking next game...")
if not snapshot_data:
_echo(" No snapshot found. Run 'scan' first.")
state.current_app_id = None
state.current_game_name = ""
state.save()
return
games = [GameInfo.from_snapshot(d) for d in snapshot_data]
hltb_cache = load_hltb_cache()
skip = set(state.finished_app_ids) | state.active_skipped_ids()
_refresh_uncached_shortlist_hours(games, hltb_cache, skip)
_apply_cached_hours_to_games(games, hltb_cache)
pick_next_game(games, state, config, on_select=_prompt_keep_or_skip)
if state.current_app_id is None:
_echo(" No more games to assign!")
return
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f"\n Library hiding: skipped ({skipped})")
elif hidden > 0:
_echo(f"\n Library: hid {hidden} games")
if not is_game_installed(state.current_app_id):
logger.info(
"Assigned game still missing after library reconciliation; "
"re-triggering install"
)
_echo(
"\n Assigned game still missing after library reconciliation; "
"re-triggering install..."
)
_echo(f"\n Auto-installing {state.current_game_name}...")
install_game(
state.current_app_id,
state.current_game_name,
config.steam_id,
use_steam_protocol=True,
)
send_notification(
"Game Complete!",
f"Finished {game_name}! Now playing: {state.current_game_name}",
)
_echo(f"\nAll done! Go play {state.current_game_name}!")
def _enforce_on_done(config: Config, state: State) -> None:
"""Run a single enforcement pass during the 'done' command.
Kills unauthorized game processes, uninstalls unauthorized games,
and ensures the assigned game is installed.
"""
if state.current_app_id is None:
return
if config.kill_unauthorized_games:
violations = enforce_allowed_game(
allowed_app_ids(state),
kill_unauthorized=True,
)
for pid, app_id in violations:
_echo(f" Killed unauthorized game: AppID={app_id} (PID={pid})")
if config.uninstall_other_games:
count = uninstall_other_games(allowed_app_ids(state))
if count:
_echo(f" Uninstalled {count} unauthorized game(s)")
if not is_game_installed(state.current_app_id):
_echo(f" Re-installing {state.current_game_name}...")
install_game(
state.current_app_id,
state.current_game_name,
config.steam_id,
use_steam_protocol=True,
)
# Reconcile library: hide non-assigned games and unhide the assigned one.
# Without this, an interrupted earlier completion can leave the new
# assigned game hidden and stale games visible.
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
elif hidden > 0:
_echo(f" Library: hid {hidden} games")
def cmd_done(config: Config, state: State) -> None:
"""Check completion, pick next game, uninstall & hide.
All-in-one command for after finishing a game:
1. Verify 100% achievements on Steam.
2. Pick the next game (shortest HLTB leisure+dlc time).
3. Uninstall all non-assigned games.
4. Hide all non-assigned games in the Steam library.
5. Install the newly assigned game.
"""
if state.current_app_id is None:
_echo("No game currently assigned. Run 'scan' first.")
return
client = SteamAPIClient(config.steam_api_key, config.steam_id)
game_name = state.current_game_name
app_id = state.current_app_id
_echo(f"Checking {game_name} (AppID={app_id})...")
game = client.refresh_single_game(app_id, game_name)
if game is None:
_echo(" Could not fetch achievement data from Steam.")
return
_echo(
f" Progress: {game.unlocked_achievements}/{game.total_achievements}"
f" ({game.completion_pct:.1f}%)"
)
hltb_cache = load_hltb_cache()
hours = hltb_cache.get(app_id, -1.0)
if hours < 0:
hltb_cache = fetch_hltb_times_cached([(app_id, game_name)])
hours = hltb_cache.get(app_id, -1.0)
if hours > 0:
_echo(f" HLTB leisure+dlc estimate: {hours:.1f} hours")
_report_assigned_confidence(app_id, state)
if not game.is_complete:
remaining = game.total_achievements - game.unlocked_achievements
_echo(f"\n NOT COMPLETE: {remaining} achievements remaining. Keep going!")
_enforce_on_done(config, state)
return
_finalize_completion(config, state, game_name, app_id)

View File

@ -14,7 +14,12 @@ import os
from typing import TYPE_CHECKING
from steam_backlog_enforcer._enforce_loop import do_enforce
from steam_backlog_enforcer._playtime import (
from steam_backlog_enforcer._playtime_block import (
block_targets,
mounted_targets,
release_block,
)
from steam_backlog_enforcer._playtime_state import (
PlaytimeState,
gaming_day_key,
load_state,
@ -22,11 +27,6 @@ from steam_backlog_enforcer._playtime import (
save_state,
state_path,
)
from steam_backlog_enforcer._playtime_block import (
block_targets,
mounted_targets,
release_block,
)
from steam_backlog_enforcer.game_install import _echo
if TYPE_CHECKING:

View File

@ -27,6 +27,7 @@ from __future__ import annotations
import os
from pathlib import Path
import pwd
def desktop_runtime_dir(uid: int) -> str:
@ -70,3 +71,50 @@ def desktop_env_args(user: str, uid: int) -> list[str]:
f"DBUS_SESSION_BUS_ADDRESS={dbus_addr}",
f"XDG_RUNTIME_DIR={runtime_dir}",
]
def desktop_uid(user: str | None) -> int:
"""Resolve *user* to a uid, defaulting to the usual first desktop uid."""
if user:
try:
return pwd.getpwnam(user).pw_uid
except KeyError:
pass
return 1000
def resolve_desktop_user() -> str | None:
"""Resolve which desktop user owns the Steam/X11 session.
Prefers the explicit STEAM_ENFORCER_DESKTOP_USER (set by the systemd
unit, which has no SUDO_USER/USER of its own since it is started
directly by systemd rather than via `sudo`), then falls back to
SUDO_USER/USER for interactive `sudo` invocations.
"""
return (
os.environ.get("STEAM_ENFORCER_DESKTOP_USER")
or os.environ.get("SUDO_USER")
or os.environ.get("USER")
)
def desktop_user_cmd(cmd: list[str], user: str | None) -> list[str]:
"""Wrap *cmd* so it runs as *user* when the caller is root.
Returns *cmd* unchanged when already unprivileged or when no desktop user
resolves; otherwise prefixes ``sudo -u <user> env <session vars>``.
This is argv construction only — deliberately no ``subprocess`` call, so
every spawn site stays in a module covered by the test suite's
``_no_subprocess`` guard.
"""
if os.geteuid() == 0 and user and user != "root":
return [
"sudo",
"-u",
user,
"env",
*desktop_env_args(user, desktop_uid(user)),
*cmd,
]
return cmd

View File

@ -0,0 +1,26 @@
"""User-facing CLI output.
A one-function leaf module so every command can print without importing the
install machinery. Split out of :mod:`steam_backlog_enforcer.game_install` to
keep that module under the 250-line cap.
"""
from __future__ import annotations
import sys
def _echo(msg: str = "", *, end: str = "\n", flush: bool = False) -> None:
"""Write user-facing CLI output to stdout.
Args:
msg: Text to output.
end: String appended after the message.
flush: Whether to flush stdout immediately.
"""
sys.stdout.write(msg + end)
if flush:
sys.stdout.flush()
# Steam infrastructure app IDs that should NEVER be uninstalled.

View File

@ -5,10 +5,19 @@ from __future__ import annotations
import json
import logging
import time
from typing import Any
from steam_backlog_enforcer._actions import allowed_app_ids, allowed_games
from steam_backlog_enforcer._echo import _echo
from steam_backlog_enforcer._enforce_steps import (
_enforce_setup,
_reinstall_missing_allowed,
)
# Re-exported: five modules and the test suite import get_all_owned_app_ids
# from here, so splitting it into _owned_apps_cache stays invisible to them.
from steam_backlog_enforcer._owned_apps_cache import get_all_owned_app_ids
from steam_backlog_enforcer._playtime import playtime_tick
from steam_backlog_enforcer._steam_launch import steam_is_installed
from steam_backlog_enforcer._total_block import (
end_total_block_cleanup,
enforce_total_block_tick,
@ -19,132 +28,31 @@ from steam_backlog_enforcer._whitelist import (
lock_enforcement_files,
)
from steam_backlog_enforcer.config import (
CONFIG_DIR,
CONFIG_FILE,
Config,
State,
_atomic_write,
load_snapshot,
)
from steam_backlog_enforcer.enforcer import (
enforce_allowed_game,
send_notification,
)
from steam_backlog_enforcer.game_install import (
_echo,
from steam_backlog_enforcer.game_uninstall import (
get_installed_games,
install_game,
is_game_installed,
is_protected_app,
uninstall_game,
uninstall_other_games,
)
from steam_backlog_enforcer.library_hider import (
steam_is_installed,
try_hide_other_games,
)
from steam_backlog_enforcer.steam_api import SteamAPIClient
from steam_backlog_enforcer.store_blocker import block_store
logger = logging.getLogger(__name__)
_OWNED_IDS_CACHE_FILE = CONFIG_DIR / "owned_app_ids_cache.json"
_OWNED_IDS_CACHE_TTL_SECONDS = 3600
def _load_owned_app_ids_cache(steam_id: str) -> list[int] | None:
"""Return fresh cached owned app IDs for this steam_id, if available."""
if not steam_id or not _OWNED_IDS_CACHE_FILE.exists():
return None
try:
data: dict[str, Any] = json.loads(
_OWNED_IDS_CACHE_FILE.read_text(encoding="utf-8")
)
except (json.JSONDecodeError, OSError, ValueError):
return None
cached_steam_id = str(data.get("steam_id", ""))
if cached_steam_id != steam_id:
return None
fetched_at = float(data.get("fetched_at", 0.0) or 0.0)
age = time.time() - fetched_at
if age > _OWNED_IDS_CACHE_TTL_SECONDS:
return None
raw_ids = data.get("app_ids", [])
if not isinstance(raw_ids, list):
return None
return [int(app_id) for app_id in raw_ids]
def _save_owned_app_ids_cache(steam_id: str, app_ids: list[int]) -> None:
"""Persist owned app IDs cache for this steam_id."""
payload = {
"steam_id": steam_id,
"fetched_at": time.time(),
"app_ids": app_ids,
}
_atomic_write(_OWNED_IDS_CACHE_FILE, json.dumps(payload, indent=2) + "\n")
# ──────────────────────────────────────────────────────────────
# Helpers
# ──────────────────────────────────────────────────────────────
def get_all_owned_app_ids(config: Config) -> list[int]:
"""Get all owned game app IDs from Steam API plus snapshot fallback.
Snapshot data contains only games with achievements, so API data is the
primary source for library hiding. Snapshot IDs are merged in to keep
behavior resilient when the API result is partial.
"""
snapshot = load_snapshot() or []
snapshot_ids = [int(d["app_id"]) for d in snapshot if "app_id" in d]
cached_ids = _load_owned_app_ids_cache(config.steam_id)
if cached_ids is not None:
merged_ids: list[int] = []
seen: set[int] = set()
for app_id in [*cached_ids, *snapshot_ids]:
if app_id in seen:
continue
seen.add(app_id)
merged_ids.append(app_id)
logger.info("Using cached Steam owned IDs (%d entries).", len(cached_ids))
return merged_ids
try:
client = SteamAPIClient(config.steam_api_key, config.steam_id)
owned = client.get_owned_games()
api_ids = [int(g["appid"]) for g in owned if "appid" in g]
_save_owned_app_ids_cache(config.steam_id, api_ids)
merged_ids: list[int] = []
seen: set[int] = set()
for app_id in [*api_ids, *snapshot_ids]:
if app_id in seen:
continue
seen.add(app_id)
merged_ids.append(app_id)
except (OSError, RuntimeError, ValueError):
if snapshot_ids:
return snapshot_ids
logger.warning("Could not fetch owned game list for hiding.")
return []
else:
return merged_ids
# ──────────────────────────────────────────────────────────────
# Enforce mode (daemon loop)
# ──────────────────────────────────────────────────────────────
# How often the enforce loop runs (seconds).
# Seconds between enforce passes.
ENFORCE_INTERVAL = 3
__all__ = [
"ENFORCE_INTERVAL",
"do_enforce",
"get_all_owned_app_ids",
]
def _allowed_names(state: State) -> str:
"""Return a human-readable list of the games the user may play.
@ -191,99 +99,6 @@ def _guard_installed_games(allowed_app_ids: set[int]) -> int:
return count
def _reinstall_missing_allowed(config: Config, state: State) -> None:
"""Re-install any allowed game that vanished between loop iterations.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
for app_id, name in allowed_games(state):
if is_game_installed(app_id):
continue
logger.info("Allowed game disappeared — re-installing %s", name)
install_game(app_id, name, config.steam_id)
def _enforce_setup(config: Config, state: State) -> None:
"""Perform initial setup for enforcement mode.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
# Initial store block.
if config.block_store:
if block_store():
_echo(" Steam store: BLOCKED")
else:
_echo(" Steam store: FAILED (need sudo?)")
# Initial cleanup.
if config.uninstall_other_games:
_echo(" Uninstalling non-assigned games...")
count = uninstall_other_games(allowed_app_ids(state))
_echo(f" Uninstalled {count} games")
# Auto-install the assigned game.
_enforce_auto_install(config, state)
# Hide all other games in the Steam library.
_enforce_hide_games(config, state)
def _enforce_auto_install(config: Config, state: State) -> None:
"""Auto-install every allowed game that is not installed yet.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
for app_id, name in allowed_games(state):
if is_game_installed(app_id):
_echo(f" Allowed game already installed: {name}")
continue
_echo(f" Auto-installing {name}...")
if install_game(
app_id,
name,
config.steam_id,
use_steam_protocol=True,
):
send_notification("Game Installing", f"{name} is being downloaded.")
else:
_echo(" Could not auto-install. Install manually from Steam.")
def _enforce_hide_games(config: Config, state: State) -> None:
"""Hide non-assigned games in the Steam library.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
owned_ids = get_all_owned_app_ids(config)
if not owned_ids:
_echo(" Library hiding: skipped (no owned game list — run 'scan' first)")
return
# An unreachable Steam is not fatal: with no client there is no library to
# hide, and everything else the enforcer does (store block, install guard)
# still works. Letting this escape used to exit(1) into Restart=always,
# which spun the service through ~1000 restarts against a Steam that had
# been uninstalled - each attempt leaving a dead process named "steam"
# behind that /proc scanners misread as a live Steam.
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
return
if hidden > 0:
_echo(f" Library: hid {hidden} games (only assigned game visible)")
else:
_echo(" Library: games already hidden")
def _enforce_loop_iteration(
config: Config,
state: State,

View File

@ -0,0 +1,127 @@
"""The individual steps one enforce pass performs.
Split out of :mod:`steam_backlog_enforcer._enforce_loop` to keep both files
under the 250-line cap: this module holds *what* each pass does, while the
loop module owns the cadence and the surrounding lifecycle.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._actions import allowed_app_ids, allowed_games
from steam_backlog_enforcer._echo import _echo
from steam_backlog_enforcer._owned_apps_cache import get_all_owned_app_ids
from steam_backlog_enforcer._steam_client import is_game_installed
from steam_backlog_enforcer._steam_state import steam_library_ready
from steam_backlog_enforcer.enforcer import send_notification
from steam_backlog_enforcer.game_install import install_game
from steam_backlog_enforcer.game_uninstall import uninstall_other_games
from steam_backlog_enforcer.library_hider import try_hide_other_games
from steam_backlog_enforcer.store_blocker import block_store
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
logger = logging.getLogger(__name__)
def _reinstall_missing_allowed(config: Config, state: State) -> None:
"""Re-install any allowed game that vanished between loop iterations.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
# Nothing is reinstallable without a Steam library, and every game looks
# "missing" when steamapps does not exist — logging per game per 3s pass
# is just noise. install_game guards this too; returning here keeps the
# log quiet as well.
if not steam_library_ready():
return
for app_id, name in allowed_games(state):
if is_game_installed(app_id):
continue
logger.info("Allowed game disappeared — re-installing %s", name)
install_game(app_id, name, config.steam_id)
def _enforce_setup(config: Config, state: State) -> None:
"""Perform initial setup for enforcement mode.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
# Initial store block.
if config.block_store:
if block_store():
_echo(" Steam store: BLOCKED")
else:
_echo(" Steam store: FAILED (need sudo?)")
# Initial cleanup.
if config.uninstall_other_games:
_echo(" Uninstalling non-assigned games...")
count = uninstall_other_games(allowed_app_ids(state))
_echo(f" Uninstalled {count} games")
# Auto-install the assigned game.
_enforce_auto_install(config, state)
# Hide all other games in the Steam library.
_enforce_hide_games(config, state)
def _enforce_auto_install(config: Config, state: State) -> None:
"""Auto-install every allowed game that is not installed yet.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
for app_id, name in allowed_games(state):
if is_game_installed(app_id):
_echo(f" Allowed game already installed: {name}")
continue
_echo(f" Auto-installing {name}...")
if install_game(
app_id,
name,
config.steam_id,
use_steam_protocol=True,
):
send_notification("Game Installing", f"{name} is being downloaded.")
else:
_echo(" Could not auto-install. Install manually from Steam.")
def _enforce_hide_games(config: Config, state: State) -> None:
"""Hide non-assigned games in the Steam library.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
owned_ids = get_all_owned_app_ids(config)
if not owned_ids:
_echo(" Library hiding: skipped (no owned game list — run 'scan' first)")
return
# An unreachable Steam is not fatal: with no client there is no library to
# hide, and everything else the enforcer does (store block, install guard)
# still works. Letting this escape used to exit(1) into Restart=always,
# which spun the service through ~1000 restarts against a Steam that had
# been uninstalled - each attempt leaving a dead process named "steam"
# behind that /proc scanners misread as a live Steam.
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
return
if hidden > 0:
_echo(f" Library: hid {hidden} games (only assigned game visible)")
else:
_echo(" Library: games already hidden")

View File

@ -0,0 +1,101 @@
"""Game-name normalisation and the protected-name check.
Split out of :mod:`steam_backlog_enforcer.game_install` to keep it under the
250-line cap. Pure string handling with no filesystem or Steam knowledge, so
it stays a leaf module.
"""
from __future__ import annotations
import difflib
import logging
import re
# _allowed_games, not _actions: _actions imports game_uninstall, which
# imports this module. The leaf module has the same function and no cycle.
from steam_backlog_enforcer._allowed_games import allowed_games
from steam_backlog_enforcer.config import State
logger = logging.getLogger(__name__)
_NAME_FUZZY_MATCH_THRESHOLD = 0.82
_NUMBER_WORDS = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"ten": "10",
}
_ROMAN_NUMERALS = {
"i": "1",
"ii": "2",
"iii": "3",
"iv": "4",
"v": "5",
"vi": "6",
"vii": "7",
"viii": "8",
"ix": "9",
"x": "10",
}
def _normalize_game_name(name: str) -> str:
"""Canonicalize a game/folder name for fuzzy comparison.
Splits into alphanumeric words, maps spelled-out numbers ("two") and
roman numerals ("II") to digits, then joins with no separators. Makes
"Kingdom Come: Deliverance II", "KingdomComeDeliverance2", and "kingdom
come deliverance two" all normalize to the same string.
"""
words = re.findall(r"[A-Za-z0-9]+", name.lower())
mapped = [_NUMBER_WORDS.get(w) or _ROMAN_NUMERALS.get(w) or w for w in words]
return "".join(mapped)
def _protected_name_stems() -> list[str]:
"""Every name of every currently-allowed game, for the deletion safety net.
Returns [] (protects nothing extra beyond exact matches already checked
by callers) if state can't be loaded -- this is a best-effort safety net,
not a hard dependency.
"""
try:
return [name for _, name in allowed_games(State.load()) if name]
except Exception:
logger.exception("Could not load allowed games for the deletion safety net")
return []
def _is_protected_name(candidate: str) -> bool:
"""True if *candidate* plausibly names one of the currently-allowed games.
Errs toward over-matching on purpose: a false positive here just skips a
deletion that can be done manually; a false negative deletes real files.
"""
normalized_candidate = _normalize_game_name(candidate)
if not normalized_candidate:
return False
for protected in _protected_name_stems():
normalized_protected = _normalize_game_name(protected)
if not normalized_protected:
continue
if normalized_candidate == normalized_protected:
return True
ratio = difflib.SequenceMatcher(
None, normalized_candidate, normalized_protected
).ratio()
if ratio >= _NAME_FUZZY_MATCH_THRESHOLD:
return True
return False
# Real Steam directory — used as a safety check to block destructive
# operations that leak through during testing.

View File

@ -0,0 +1,95 @@
"""Cached batch lookup of HowLongToBeat times.
Split out of :mod:`steam_backlog_enforcer.hltb` to keep both files
under the 250-line cap.
"""
from __future__ import annotations
import logging
import time
from steam_backlog_enforcer._hltb_types import (
ProgressCb,
_HLTBExtras,
load_hltb_cache,
load_hltb_count_comp_cache,
load_hltb_leisure_100h_cache,
load_hltb_polls_cache,
load_hltb_rush_cache,
save_hltb_cache,
)
from steam_backlog_enforcer.hltb import fetch_hltb_times
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────
# Confidence-only batch fetch (no leisure/DLC detail pages)
# ──────────────────────────────────────────────────────────────
def fetch_hltb_times_cached(
games: list[tuple[int, str]],
progress_cb: ProgressCb | None = None,
) -> dict[int, float]:
"""Fetch HLTB times, using disk cache for already-known games.
Args:
games: list of (app_id, name) tuples to look up.
progress_cb: optional callback(done, total, found, game_name).
Returns: dict mapping app_id -> completionist_hours.
"""
cache = load_hltb_cache()
polls = load_hltb_polls_cache()
extras = _HLTBExtras(
count_comp=load_hltb_count_comp_cache(),
rush=load_hltb_rush_cache(),
leisure_100h=load_hltb_leisure_100h_cache(),
)
uncached = [(app_id, name) for app_id, name in games if app_id not in cache]
if uncached:
logger.info(
"Fetching HLTB data for %d uncached games (%d cached)...",
len(uncached),
len(games) - len(uncached),
)
t0 = time.monotonic()
fetch_hltb_times(
uncached,
cache=cache,
polls=polls,
progress_cb=progress_cb,
extras=extras,
)
elapsed = time.monotonic() - t0
# Final save.
save_hltb_cache(cache, polls, extras)
found = sum(1 for aid, _ in uncached if cache.get(aid, -1) > 0)
rate = len(uncached) / elapsed if elapsed > 0 else 0
logger.info(
"HLTB fetch done: %d/%d found in %.1fs (%.0f games/s)",
found,
len(uncached),
elapsed,
rate,
)
else:
logger.info("All %d games found in HLTB cache.", len(games))
return cache
_REEXPORTED_TYPES = frozenset({"HLTB_BASE_URL"})
_MOVED_TO_HLTB_CONFIDENCE = frozenset(
{
"fetch_hltb_confidence_cached",
"fetch_hltb_detail_missing",
"get_hltb_submit_url",
}
)

View File

@ -0,0 +1,117 @@
"""Extracting completionist and DLC data from a HowLongToBeat page.
Leaf helpers: they call nothing else in the module, so extracting
them introduces no cycle. Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
import asyncio
from http import HTTPStatus
import logging
import re
from typing import Any
import aiohttp
from steam_backlog_enforcer._hltb_page_parse import (
_as_positive_int,
_parse_game_page,
)
from steam_backlog_enforcer._hltb_types import (
HLTB_BASE_URL,
)
logger = logging.getLogger(__name__)
_NEXT_DATA_RE = re.compile(
r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>',
)
def _platform_comp_high_candidates(game_data: dict[str, Any]) -> list[int]:
"""Collect positive ``comp_high`` values from ``platformData`` entries."""
platform_data = game_data.get("platformData", [])
if not isinstance(platform_data, list):
return []
candidates = []
for entry in platform_data:
if isinstance(entry, dict):
v = _as_positive_int(entry.get("comp_high", 0))
if v > 0:
candidates.append(v)
return candidates
def _extract_comp_100_avg_and_high(game_data: dict[str, Any]) -> tuple[float, float]:
"""Extract (average comp_100, high comp_100) from game detail data.
Returns hours as floats: (avg_hours, high_hours). Returns (-1, -1) when
insufficient data is present. The average is ``comp_100`` (seconds) from
``game[0]``; the high is ``comp_100_h``.
"""
games = game_data.get("game", [])
if not isinstance(games, list) or not games:
return -1, -1
if not isinstance(games[0], dict):
return -1, -1
base = games[0]
avg_s = _as_positive_int(base.get("comp_100", 0))
high_s = _as_positive_int(base.get("comp_100_h", 0))
avg_h = round(avg_s / 3600, 2) if avg_s > 0 else -1
high_h = round(high_s / 3600, 2) if high_s > 0 else avg_h
return avg_h, high_h
def _extract_dlc_relationships(game_data: dict[str, Any]) -> list[tuple[int, float]]:
"""Extract DLC relationship IDs and fallback hours from detail data."""
relationships = game_data.get("relationships", [])
if not isinstance(relationships, list):
return []
dlcs: list[tuple[int, float]] = []
for rel in relationships:
if not isinstance(rel, dict):
continue
if str(rel.get("game_type", "")).lower() != "dlc":
continue
dlc_id = _as_positive_int(rel.get("game_id", 0))
fallback_comp_100 = _as_positive_int(rel.get("comp_100", 0))
if fallback_comp_100 > 0:
fallback_hours = round(fallback_comp_100 / 3600, 2)
else:
fallback_hours = 0.0
dlcs.append((dlc_id, fallback_hours))
return dlcs
async def _fetch_detail_one(
sem: asyncio.Semaphore,
session: aiohttp.ClientSession,
hltb_game_id: int,
) -> dict[str, Any] | None:
"""Fetch a single HLTB game detail page and parse its data."""
async with sem:
url = f"{HLTB_BASE_URL}/game/{hltb_game_id}"
headers = {
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
),
"accept": "text/html",
"referer": "https://howlongtobeat.com/",
}
try:
async with session.get(url, headers=headers) as resp:
if resp.status == HTTPStatus.OK:
html = await resp.text()
return _parse_game_page(html)
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
logger.debug(
"HLTB detail fetch failed for game_id=%d: %s",
hltb_game_id,
exc,
)
return None

View File

@ -0,0 +1,187 @@
"""Cached HowLongToBeat confidence lookups.
Split out of :mod:`steam_backlog_enforcer.hltb` to keep both files
under the 250-line cap.
"""
from __future__ import annotations
import logging
import time
from steam_backlog_enforcer._hltb_types import (
HLTB_BASE_URL,
ProgressCb,
_HLTBExtras,
load_hltb_cache,
load_hltb_count_comp_cache,
load_hltb_game_id_cache,
load_hltb_leisure_100h_cache,
load_hltb_polls_cache,
load_hltb_rush_cache,
save_hltb_cache,
)
from steam_backlog_enforcer.hltb import (
fetch_hltb_confidence,
fetch_hltb_times,
)
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────
# Confidence-only batch fetch (no leisure/DLC detail pages)
# ──────────────────────────────────────────────────────────────
def fetch_hltb_confidence_cached(
games: list[tuple[int, str]],
progress_cb: ProgressCb | None = None,
) -> dict[int, float]:
"""Fetch HLTB search-level confidence data, using disk cache for known IDs."""
cache = load_hltb_cache()
polls = load_hltb_polls_cache()
count_comp = load_hltb_count_comp_cache()
uncached = [(app_id, name) for app_id, name in games if app_id not in cache]
if uncached:
logger.info(
"Fetching HLTB confidence for %d uncached games (%d cached)...",
len(uncached),
len(games) - len(uncached),
)
t0 = time.monotonic()
fetch_hltb_confidence(
uncached,
cache=cache,
polls=polls,
progress_cb=progress_cb,
count_comp=count_comp,
)
elapsed = time.monotonic() - t0
save_hltb_cache(cache, polls, _HLTBExtras(count_comp=count_comp))
found = sum(1 for aid, _ in uncached if cache.get(aid, -1) > 0)
rate = len(uncached) / elapsed if elapsed > 0 else 0
logger.info(
"HLTB confidence fetch done: %d/%d found in %.1fs (%.0f games/s)",
found,
len(uncached),
elapsed,
rate,
)
else:
logger.info("All %d games found in HLTB cache.", len(games))
return cache
def fetch_hltb_detail_missing(
games: list[tuple[int, str]],
progress_cb: ProgressCb | None = None,
) -> int:
"""Fetch HLTB detail (rush + leisure) for games that are missing it.
Also backfills ``hltb_game_id`` for any game that already has rush/leisure
data but whose HLTB game ID was never stored (e.g. from an old cache).
Games with both rush data and a game_id are skipped entirely. For the
rest, temporarily removes them from the hours cache so ``fetch_hltb_times``
will visit their detail pages. Restores prior hours for any game the
re-fetch doesn't find.
Args:
games: list of (app_id, name) tuples to check.
progress_cb: optional progress callback.
Returns:
Number of games that now have rush-hour data after the fetch.
"""
rush = load_hltb_rush_cache()
game_id_cache = load_hltb_game_id_cache()
missing_rush = [
(app_id, name) for app_id, name in games if rush.get(app_id, -1) <= 0
]
# Also re-search games that have rush data but no HLTB game ID yet so the
# direct URL can be shown in stats output.
missing_id_only = [
(app_id, name)
for app_id, name in games
if rush.get(app_id, -1) > 0 and game_id_cache.get(app_id, 0) == 0
]
missing = missing_rush + missing_id_only
if not missing:
return 0
cache = load_hltb_cache()
polls = load_hltb_polls_cache()
extras = _HLTBExtras(
count_comp=load_hltb_count_comp_cache(),
rush=rush,
leisure_100h=load_hltb_leisure_100h_cache(),
hltb_game_id=game_id_cache,
)
# Remove from hours cache so fetch_hltb_times will visit the detail page.
prior_hours: dict[int, float] = {}
for app_id, _ in missing:
prior_hours[app_id] = cache.pop(app_id, -1.0)
n_rush = len(missing_rush)
n_id = len(missing_id_only)
if n_rush and n_id:
logger.info(
"Fetching HLTB detail for %d games missing rush/leisure data"
" + %d games missing game ID...",
n_rush,
n_id,
)
elif n_rush:
logger.info(
"Fetching HLTB detail for %d games missing rush/leisure data...", n_rush
)
else:
logger.info("Backfilling HLTB game ID for %d game(s)...", n_id)
t0 = time.monotonic()
fetch_hltb_times(
missing,
cache=cache,
polls=polls,
progress_cb=progress_cb,
extras=extras,
)
elapsed = time.monotonic() - t0
# Restore prior hours for games the detail fetch didn't re-find.
for app_id, old_hours in prior_hours.items():
if old_hours > 0 and cache.get(app_id, -1.0) <= 0:
cache[app_id] = old_hours
save_hltb_cache(cache, polls, extras)
fetched = sum(1 for app_id, _ in missing_rush if extras.rush.get(app_id, -1) > 0)
rate = len(missing) / elapsed if elapsed > 0 else 0
logger.info(
"HLTB detail fetch done: %d/%d got rush data in %.1fs (%.0f games/s)",
fetched,
len(missing_rush),
elapsed,
rate,
)
return fetched
def get_hltb_submit_url(game_name: str) -> str | None:
"""Look up a game on HLTB and return its submit page URL.
Args:
game_name: Name of the game to search for.
Returns:
URL like ``https://howlongtobeat.com/submit/game/12345``,
or ``None`` if the game wasn't found.
"""
results = fetch_hltb_times([(0, game_name)])
if results and results[0].hltb_game_id:
return f"{HLTB_BASE_URL}/submit/game/{results[0].hltb_game_id}"
return None

View File

@ -3,17 +3,24 @@
from __future__ import annotations
import asyncio
from http import HTTPStatus
import json
import logging
import re
from typing import Any
import aiohttp
from steam_backlog_enforcer._hltb_comp_extract import (
_extract_comp_100_avg_and_high,
_extract_dlc_relationships,
_fetch_detail_one,
_platform_comp_high_candidates,
)
from steam_backlog_enforcer._hltb_page_parse import (
_apply_dlc_leisure_overrides,
_as_positive_int,
)
from steam_backlog_enforcer._hltb_types import (
_SAVE_INTERVAL,
HLTB_BASE_URL,
MAX_CONCURRENT,
HLTBResult,
ProgressCb,
@ -28,71 +35,6 @@ _NEXT_DATA_RE = re.compile(
)
def _parse_game_page(html: str) -> dict[str, Any] | None:
"""Extract game data dict from a HLTB game page's __NEXT_DATA__."""
match = _NEXT_DATA_RE.search(html)
if not match:
return None
try:
data = json.loads(match.group(1))
result: dict[str, Any] = data["props"]["pageProps"]["game"]["data"]
except (json.JSONDecodeError, KeyError, TypeError):
return None
return result
def _as_positive_int(value: object) -> int:
"""Convert HLTB numeric JSON values to a positive int, or 0 when invalid."""
if isinstance(value, int):
return max(0, value)
if isinstance(value, float):
int_value = int(value)
return max(0, int_value)
if isinstance(value, str):
try:
int_value = int(value)
return max(0, int_value)
except ValueError:
return 0
return 0
def _platform_comp_high_candidates(game_data: dict[str, Any]) -> list[int]:
"""Collect positive ``comp_high`` values from ``platformData`` entries."""
platform_data = game_data.get("platformData", [])
if not isinstance(platform_data, list):
return []
candidates = []
for entry in platform_data:
if isinstance(entry, dict):
v = _as_positive_int(entry.get("comp_high", 0))
if v > 0:
candidates.append(v)
return candidates
def _extract_comp_100_avg_and_high(game_data: dict[str, Any]) -> tuple[float, float]:
"""Extract (average comp_100, high comp_100) from game detail data.
Returns hours as floats: (avg_hours, high_hours). Returns (-1, -1) when
insufficient data is present. The average is ``comp_100`` (seconds) from
``game[0]``; the high is ``comp_100_h``.
"""
games = game_data.get("game", [])
if not isinstance(games, list) or not games:
return -1, -1
if not isinstance(games[0], dict):
return -1, -1
base = games[0]
avg_s = _as_positive_int(base.get("comp_100", 0))
high_s = _as_positive_int(base.get("comp_100_h", 0))
avg_h = round(avg_s / 3600, 2) if avg_s > 0 else -1
high_h = round(high_s / 3600, 2) if high_s > 0 else avg_h
return avg_h, high_h
def _extract_base_leisure_hours(game_data: dict[str, Any]) -> float:
"""Extract base-game leisure hours from game detail data.
@ -137,29 +79,6 @@ def _extract_base_leisure_hours(game_data: dict[str, Any]) -> float:
return round(leisure_s / 3600, 2)
def _extract_dlc_relationships(game_data: dict[str, Any]) -> list[tuple[int, float]]:
"""Extract DLC relationship IDs and fallback hours from detail data."""
relationships = game_data.get("relationships", [])
if not isinstance(relationships, list):
return []
dlcs: list[tuple[int, float]] = []
for rel in relationships:
if not isinstance(rel, dict):
continue
if str(rel.get("game_type", "")).lower() != "dlc":
continue
dlc_id = _as_positive_int(rel.get("game_id", 0))
fallback_comp_100 = _as_positive_int(rel.get("comp_100", 0))
if fallback_comp_100 > 0:
fallback_hours = round(fallback_comp_100 / 3600, 2)
else:
fallback_hours = 0.0
dlcs.append((dlc_id, fallback_hours))
return dlcs
def _extract_leisure_hours(game_data: dict[str, Any]) -> float:
"""Compute total leisure hours: base game + all DLCs.
@ -180,35 +99,6 @@ def _extract_leisure_hours(game_data: dict[str, Any]) -> float:
return round(total_hours, 2)
async def _fetch_detail_one(
sem: asyncio.Semaphore,
session: aiohttp.ClientSession,
hltb_game_id: int,
) -> dict[str, Any] | None:
"""Fetch a single HLTB game detail page and parse its data."""
async with sem:
url = f"{HLTB_BASE_URL}/game/{hltb_game_id}"
headers = {
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
),
"accept": "text/html",
"referer": "https://howlongtobeat.com/",
}
try:
async with session.get(url, headers=headers) as resp:
if resp.status == HTTPStatus.OK:
html = await resp.text()
return _parse_game_page(html)
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
logger.debug(
"HLTB detail fetch failed for game_id=%d: %s",
hltb_game_id,
exc,
)
return None
def _process_game_detail(
game_data: dict[str, Any],
dlc_rels: list[tuple[int, float]],
@ -357,17 +247,3 @@ async def _fetch_dlc_leisure_hours(
if dlc_leisure > 0:
dlc_hours_by_id[dlc_id] = dlc_leisure
return dlc_hours_by_id
def _apply_dlc_leisure_overrides(
base_hours: float,
dlc_rels: list[tuple[int, float]],
dlc_hours_by_id: dict[int, float],
) -> float:
"""Replace fallback DLC hours with detailed leisure hours when available."""
adjusted = base_hours
for dlc_id, fallback_hours in dlc_rels:
dlc_leisure = dlc_hours_by_id.get(dlc_id, -1.0)
if dlc_leisure > 0:
adjusted += dlc_leisure - fallback_hours
return round(adjusted, 2)

View File

@ -0,0 +1,229 @@
"""Fuzzy name matching and search-variant building for HowLongToBeat.
Leaf helpers: they call nothing else in the module, so extracting
them introduces no cycle. Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
from difflib import SequenceMatcher
import logging
import re
from typing import Any
from steam_backlog_enforcer._hltb_types import (
_SUBSET_SUFFIXES,
HLTBResult,
)
_TM_RE = re.compile("[™®©\uff0a]")
_COLON_WORD_RE = re.compile(r":(\s|$)")
_STANDALONE_PUNCT_RE = re.compile(r"^[-/|]$")
_AMP_RE = re.compile(r"\s*&\s*")
_STEAM_SUFFIX_RE = re.compile(
r"\s+(?:\(Legacy\)|\(Classic\)|\(beta\)|\(Remastered\)|Legacy|Classic|RHCP"
r"|\(Phase\s+\d+\))\s*$",
re.IGNORECASE,
)
logger = logging.getLogger(__name__)
# When extended entry has ≥ this many times more hours than the exact match,
# prefer it even if its confidence count is lower.
_EXTENDED_DOMINANCE_RATIO = 4.0
# Minimum combined confidence for the dominance path (avoids picking entries
# that have almost no data at all).
_EXTENDED_MIN_CONFIDENCE = 3
# ──────────────────────────────────────────────────────────────
# HLTB API setup (done once, not per-request like the library)
# ──────────────────────────────────────────────────────────────
def _similarity(a: str, b: str) -> float:
"""Case-insensitive SequenceMatcher ratio between two strings."""
return SequenceMatcher(None, a.lower(), b.lower()).ratio()
def _sanitize_search_name(name: str) -> str:
"""Strip HLTB-breaking characters from a game name for searchTerms.
Removes trademark/copyright symbols, colons at word-end, standalone
punctuation tokens (dash, slash, pipe), and replaces & with 'and'.
"""
cleaned = _TM_RE.sub("", name)
cleaned = _AMP_RE.sub(" and ", cleaned)
cleaned = _COLON_WORD_RE.sub(" ", cleaned)
tokens = [t for t in cleaned.split() if not _STANDALONE_PUNCT_RE.match(t)]
return " ".join(tokens)
def _build_search_variants(game_name: str) -> list[str]:
"""Return fallback search terms for one Steam game title.
Tries progressively simplified names so HLTB search finds a result even
when the Steam title contains edition suffixes, Steam-only labels, or
subtitle decorators that HLTB does not index under.
Order matters: most-specific first, then stripped-down fallbacks.
Simplifications are chained so e.g. "Foo - Bar Edition" →
"Foo - Bar" → "Foo" and "Foo - Bar Edition" → "Foo Edition" → "Foo".
"""
base = game_name.strip()
seen: set[str] = set()
variants: list[str] = []
def _add(name: str) -> None:
s = name.strip()
if s and s not in seen:
seen.add(s)
variants.append(s)
_add(base)
# Strip Steam-only labels that HLTB never uses
no_steam = _STEAM_SUFFIX_RE.sub("", base).strip()
_add(no_steam)
# Strip trailing year "(YYYY)"
no_year = re.sub(r"\s*\(\d{4}\)$", "", base).strip()
_add(no_year)
# Strip " - subtitle" portion (e.g. "Brothers - A Tale of Two Sons" → "Brothers")
no_subtitle = re.sub(r"\s+-\s+.*$", "", base).strip()
_add(no_subtitle)
# Also strip edition from the subtitle-stripped name.
# e.g. "Rocksmith 2014 Edition - Remastered" → "Rocksmith 2014 Edition"
# → "Rocksmith 2014"
if no_subtitle != base:
_add(re.sub(r"\s+\w+\s+Edition\s*$", "", no_subtitle, flags=re.IGNORECASE))
_add(re.sub(r"\s+Edition\s*$", "", no_subtitle, flags=re.IGNORECASE))
# Strip "GOTY Edition" / "Gold Edition" / "Definitive Edition" etc. from base
no_edition = re.sub(r"\s+\w+\s+Edition\s*$", "", base, flags=re.IGNORECASE).strip()
_add(no_edition)
# Strip just " Edition" at end from base
no_bare_edition = re.sub(r"\s+Edition\s*$", "", base, flags=re.IGNORECASE).strip()
_add(no_bare_edition)
# Strip ": subtitle" portion (e.g. "Batman: Arkham Asylum" → "Batman")
no_colon_sub = re.sub(r"\s*:.*$", "", base).strip()
_add(no_colon_sub)
return variants
def _build_result_from_best(
app_id: int,
original_name: str,
query_name: str,
best: tuple[dict[str, Any], float],
) -> HLTBResult:
"""Convert selected HLTB entry into HLTBResult."""
entry, sim = best
hours = round(entry["comp_100"] / 3600, 2)
logger.debug(
("HLTB match for '%s' via '%s': '%s' (id=%s, comp_100=%s, sim=%.3f)"),
original_name,
query_name,
entry.get("game_name"),
entry.get("game_id"),
entry.get("comp_100"),
sim,
)
return HLTBResult(
app_id=app_id,
game_name=original_name,
completionist_hours=hours,
similarity=sim,
hltb_game_id=entry.get("game_id", 0),
comp_100_count=int(entry.get("comp_100_count", 0) or 0),
count_comp=int(entry.get("count_comp", 0) or 0),
)
def _find_exact_match(
usable: list[tuple[dict[str, Any], float]],
lower: str,
) -> tuple[dict[str, Any], float] | None:
"""Find best exact name/alias match (highest comp_100)."""
return next(
(
(e, s)
for e, s in sorted(
usable,
key=lambda x: x[0].get("comp_100", 0),
reverse=True,
)
if (e.get("game_name") or "").lower() == lower
or (e.get("game_alias") or "").lower() == lower
),
None,
)
def _find_best_extended(
usable: list[tuple[dict[str, Any], float]],
lower: str,
) -> tuple[dict[str, Any], float] | None:
"""Find best extended entry ("Name: Subtitle" / "Name - Subtitle").
Skips subset entries (prologue, demo, etc.). Compilations ("compil")
are included because HLTB classifies multi-chapter collections that
share the base title as compilations (e.g. "FAITH: The Unholy Trinity").
"""
best: tuple[dict[str, Any], float] | None = None
for entry, sim in usable:
game_type = str(entry.get("game_type", "")).lower()
if game_type not in ("", "game", "compil"):
continue
entry_name = (entry.get("game_name") or "").lower()
if entry_name.startswith((lower + ":", lower + " -")):
suffix = entry_name[len(lower) :].lstrip(" :-")
if not any(suffix.startswith(kw) for kw in _SUBSET_SUFFIXES) and (
best is None or entry.get("comp_100", 0) > best[0].get("comp_100", 0)
):
best = (entry, sim)
return best
def _resolve_exact_vs_extended(
best_exact: tuple[dict[str, Any], float] | None,
best_extended: tuple[dict[str, Any], float] | None,
usable: list[tuple[dict[str, Any], float]],
) -> tuple[dict[str, Any], float]:
"""Decide between exact match, extended entry, or highest similarity."""
if best_exact is not None and best_extended is not None:
exact_hours = best_exact[0].get("comp_100", 0)
extended_hours = best_extended[0].get("comp_100", 0)
exact_confidence = int(best_exact[0].get("comp_100_count", 0) or 0) + int(
best_exact[0].get("count_comp", 0) or 0
)
extended_confidence = int(best_extended[0].get("comp_100_count", 0) or 0) + int(
best_extended[0].get("count_comp", 0) or 0
)
# Prefer the extended entry when it has more hours AND either:
# (a) at least as much confidence (normal case), OR
# (b) dominant hours ratio (>=4x) with minimal data — handles cases
# like "FAITH: The Unholy Trinity" (17h, newer) vs "FAITH" 2017
# (1.5h, older/more data) where the older exact match has
# accumulated more confidence simply by being on HLTB longer.
dominates = (
exact_hours > 0
and extended_hours >= exact_hours * _EXTENDED_DOMINANCE_RATIO
and extended_confidence >= _EXTENDED_MIN_CONFIDENCE
)
if extended_hours > exact_hours and (
extended_confidence >= exact_confidence or dominates
):
return best_extended
return best_exact
if best_exact is not None:
return best_exact
if best_extended is not None:
return best_extended
# Fall back to highest similarity.
return max(usable, key=lambda x: x[1])

View File

@ -0,0 +1,61 @@
"""Parsing a HowLongToBeat game page.
Leaf helpers: they call nothing else in the module, so extracting
them introduces no cycle. Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
import json
import logging
import re
from typing import Any
logger = logging.getLogger(__name__)
_NEXT_DATA_RE = re.compile(
r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>',
)
def _parse_game_page(html: str) -> dict[str, Any] | None:
"""Extract game data dict from a HLTB game page's __NEXT_DATA__."""
match = _NEXT_DATA_RE.search(html)
if not match:
return None
try:
data = json.loads(match.group(1))
result: dict[str, Any] = data["props"]["pageProps"]["game"]["data"]
except (json.JSONDecodeError, KeyError, TypeError):
return None
return result
def _as_positive_int(value: object) -> int:
"""Convert HLTB numeric JSON values to a positive int, or 0 when invalid."""
if isinstance(value, int):
return max(0, value)
if isinstance(value, float):
int_value = int(value)
return max(0, int_value)
if isinstance(value, str):
try:
int_value = int(value)
return max(0, int_value)
except ValueError:
return 0
return 0
def _apply_dlc_leisure_overrides(
base_hours: float,
dlc_rels: list[tuple[int, float]],
dlc_hours_by_id: dict[int, float],
) -> float:
"""Replace fallback DLC hours with detailed leisure hours when available."""
adjusted = base_hours
for dlc_id, fallback_hours in dlc_rels:
dlc_leisure = dlc_hours_by_id.get(dlc_id, -1.0)
if dlc_leisure > 0:
adjusted += dlc_leisure - fallback_hours
return round(adjusted, 2)

View File

@ -4,25 +4,28 @@ from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from difflib import SequenceMatcher
from http import HTTPStatus
import json
import logging
import re
import time
from typing import Any
import aiohttp
from howlongtobeatpy.HTMLRequests import HTMLRequests
from steam_backlog_enforcer._hltb_detail import (
_fetch_leisure_times,
)
from steam_backlog_enforcer._hltb_matching import (
_build_result_from_best,
_build_search_variants,
)
from steam_backlog_enforcer._hltb_search_api import (
_build_search_payload,
_collect_candidates,
_get_auth_info,
_get_hltb_search_url,
_pick_best_hltb_entry,
)
from steam_backlog_enforcer._hltb_types import (
_SAVE_INTERVAL,
_SUBSET_SUFFIXES,
MAX_CONCURRENT,
MIN_SIMILARITY,
HLTBResult,
ProgressCb,
_AuthInfo,
@ -45,353 +48,6 @@ _EXTENDED_MIN_CONFIDENCE = 3
# ──────────────────────────────────────────────────────────────
def _get_hltb_search_url() -> str:
"""Discover the current HLTB search API endpoint.
Scrapes the homepage for JS bundles containing the fetch URL.
Falls back to ``/api/finder`` if extraction fails.
"""
try:
search_info = HTMLRequests.send_website_request_getcode(
parse_all_scripts=False,
)
if search_info is None:
search_info = HTMLRequests.send_website_request_getcode(
parse_all_scripts=True,
)
if search_info and search_info.search_url:
url: str = HTMLRequests.BASE_URL + search_info.search_url
return url
except (OSError, RuntimeError, ValueError, TypeError):
logger.debug("Failed to discover HLTB search URL, using default")
return "https://howlongtobeat.com/api/finder"
async def _get_auth_info(
search_url: str,
session: aiohttp.ClientSession,
) -> _AuthInfo | None:
"""Fetch the HLTB auth token and honeypot key/val (one GET request)."""
init_url = search_url + "/init"
ts = int(time.time() * 1000)
headers = {
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
),
"referer": "https://howlongtobeat.com/",
}
try:
async with session.get(
init_url,
params={"t": ts},
headers=headers,
) as resp:
if resp.status == HTTPStatus.OK:
data = await resp.json()
token: str | None = data.get("token")
if token is None:
return None
return _AuthInfo(
token=token,
hp_key=data.get("hpKey", ""),
hp_val=data.get("hpVal", ""),
)
except (aiohttp.ClientError, asyncio.TimeoutError):
logger.warning("Failed to get HLTB auth token")
return None
def _similarity(a: str, b: str) -> float:
"""Case-insensitive SequenceMatcher ratio between two strings."""
return SequenceMatcher(None, a.lower(), b.lower()).ratio()
_TM_RE = re.compile("[™®©\uff0a]")
_COLON_WORD_RE = re.compile(r":(\s|$)")
_STANDALONE_PUNCT_RE = re.compile(r"^[-/|]$")
_AMP_RE = re.compile(r"\s*&\s*")
def _sanitize_search_name(name: str) -> str:
"""Strip HLTB-breaking characters from a game name for searchTerms.
Removes trademark/copyright symbols, colons at word-end, standalone
punctuation tokens (dash, slash, pipe), and replaces & with 'and'.
"""
cleaned = _TM_RE.sub("", name)
cleaned = _AMP_RE.sub(" and ", cleaned)
cleaned = _COLON_WORD_RE.sub(" ", cleaned)
tokens = [t for t in cleaned.split() if not _STANDALONE_PUNCT_RE.match(t)]
return " ".join(tokens)
def _build_search_payload(game_name: str, auth: _AuthInfo | None = None) -> str:
"""Build the JSON POST body for an HLTB search."""
payload: dict[str, Any] = {
"searchType": "games",
"searchTerms": _sanitize_search_name(game_name).split(),
"searchPage": 1,
"size": 20,
"searchOptions": {
"games": {
"userId": 0,
"platform": "",
"sortCategory": "popular",
"rangeCategory": "main",
"rangeTime": {"min": 0, "max": 0},
"gameplay": {
"perspective": "",
"flow": "",
"genre": "",
"difficulty": "",
},
"rangeYear": {"max": "", "min": ""},
"modifier": "",
},
"users": {"sortCategory": "postcount"},
"lists": {"sortCategory": "follows"},
"filter": "",
"sort": 0,
"randomizer": 0,
},
"useCache": True,
}
if auth and auth.hp_key:
payload[auth.hp_key] = auth.hp_val
return json.dumps(payload)
_STEAM_SUFFIX_RE = re.compile(
r"\s+(?:\(Legacy\)|\(Classic\)|\(beta\)|\(Remastered\)|Legacy|Classic|RHCP"
r"|\(Phase\s+\d+\))\s*$",
re.IGNORECASE,
)
def _build_search_variants(game_name: str) -> list[str]:
"""Return fallback search terms for one Steam game title.
Tries progressively simplified names so HLTB search finds a result even
when the Steam title contains edition suffixes, Steam-only labels, or
subtitle decorators that HLTB does not index under.
Order matters: most-specific first, then stripped-down fallbacks.
Simplifications are chained so e.g. "Foo - Bar Edition" →
"Foo - Bar" → "Foo" and "Foo - Bar Edition" → "Foo Edition" → "Foo".
"""
base = game_name.strip()
seen: set[str] = set()
variants: list[str] = []
def _add(name: str) -> None:
s = name.strip()
if s and s not in seen:
seen.add(s)
variants.append(s)
_add(base)
# Strip Steam-only labels that HLTB never uses
no_steam = _STEAM_SUFFIX_RE.sub("", base).strip()
_add(no_steam)
# Strip trailing year "(YYYY)"
no_year = re.sub(r"\s*\(\d{4}\)$", "", base).strip()
_add(no_year)
# Strip " - subtitle" portion (e.g. "Brothers - A Tale of Two Sons" → "Brothers")
no_subtitle = re.sub(r"\s+-\s+.*$", "", base).strip()
_add(no_subtitle)
# Also strip edition from the subtitle-stripped name.
# e.g. "Rocksmith 2014 Edition - Remastered" → "Rocksmith 2014 Edition"
# → "Rocksmith 2014"
if no_subtitle != base:
_add(re.sub(r"\s+\w+\s+Edition\s*$", "", no_subtitle, flags=re.IGNORECASE))
_add(re.sub(r"\s+Edition\s*$", "", no_subtitle, flags=re.IGNORECASE))
# Strip "GOTY Edition" / "Gold Edition" / "Definitive Edition" etc. from base
no_edition = re.sub(r"\s+\w+\s+Edition\s*$", "", base, flags=re.IGNORECASE).strip()
_add(no_edition)
# Strip just " Edition" at end from base
no_bare_edition = re.sub(r"\s+Edition\s*$", "", base, flags=re.IGNORECASE).strip()
_add(no_bare_edition)
# Strip ": subtitle" portion (e.g. "Batman: Arkham Asylum" → "Batman")
no_colon_sub = re.sub(r"\s*:.*$", "", base).strip()
_add(no_colon_sub)
return variants
def _collect_candidates(
query_name: str,
data: dict[str, Any],
) -> list[tuple[dict[str, Any], float]]:
"""Build candidate list from one HLTB response payload."""
candidates: list[tuple[dict[str, Any], float]] = []
lower_name = query_name.lower()
for entry in data.get("data", []):
entry_name = entry.get("game_name", "")
entry_alias = entry.get("game_alias", "") or ""
is_dlc = str(entry.get("game_type", "")).lower() == "dlc"
sim = max(
_similarity(query_name, entry_name),
_similarity(query_name, entry_alias),
)
is_full_edition = (
(not is_dlc) and entry_name.lower().startswith(lower_name + ":")
) or ((not is_dlc) and entry_name.lower().startswith(lower_name + " -"))
if sim >= MIN_SIMILARITY or is_full_edition:
comp_100 = entry.get("comp_100", 0)
if comp_100 and comp_100 > 0:
candidates.append((entry, sim))
return candidates
def _build_result_from_best(
app_id: int,
original_name: str,
query_name: str,
best: tuple[dict[str, Any], float],
) -> HLTBResult:
"""Convert selected HLTB entry into HLTBResult."""
entry, sim = best
hours = round(entry["comp_100"] / 3600, 2)
logger.debug(
("HLTB match for '%s' via '%s': '%s' (id=%s, comp_100=%s, sim=%.3f)"),
original_name,
query_name,
entry.get("game_name"),
entry.get("game_id"),
entry.get("comp_100"),
sim,
)
return HLTBResult(
app_id=app_id,
game_name=original_name,
completionist_hours=hours,
similarity=sim,
hltb_game_id=entry.get("game_id", 0),
comp_100_count=int(entry.get("comp_100_count", 0) or 0),
count_comp=int(entry.get("count_comp", 0) or 0),
)
def _pick_best_hltb_entry(
search_name: str,
candidates: list[tuple[dict[str, Any], float]],
) -> tuple[dict[str, Any], float] | None:
"""Pick the best HLTB entry, preferring full editions over demos/chapters.
When a short name like "FAITH" matches both "FAITH" (demo) and
"FAITH: The Unholy Trinity" (full game), prefer the full game
since Steam often lists the full game under the shorter name.
When an exact match like "Timberman" (26 h) competes against an
unrelated subtitle entry like "Timberman: The Big Adventure" (2 h),
the exact match wins because it has more hours.
"""
if not candidates:
return None
# Prefer base games over DLC entries when both are present.
non_dlc = [c for c in candidates if str(c[0].get("game_type", "")).lower() != "dlc"]
usable = non_dlc or candidates
if len(usable) == 1:
return usable[0]
lower = search_name.lower()
best_exact = _find_exact_match(usable, lower)
best_extended = _find_best_extended(usable, lower)
return _resolve_exact_vs_extended(best_exact, best_extended, usable)
def _find_exact_match(
usable: list[tuple[dict[str, Any], float]],
lower: str,
) -> tuple[dict[str, Any], float] | None:
"""Find best exact name/alias match (highest comp_100)."""
return next(
(
(e, s)
for e, s in sorted(
usable,
key=lambda x: x[0].get("comp_100", 0),
reverse=True,
)
if (e.get("game_name") or "").lower() == lower
or (e.get("game_alias") or "").lower() == lower
),
None,
)
def _find_best_extended(
usable: list[tuple[dict[str, Any], float]],
lower: str,
) -> tuple[dict[str, Any], float] | None:
"""Find best extended entry ("Name: Subtitle" / "Name - Subtitle").
Skips subset entries (prologue, demo, etc.). Compilations ("compil")
are included because HLTB classifies multi-chapter collections that
share the base title as compilations (e.g. "FAITH: The Unholy Trinity").
"""
best: tuple[dict[str, Any], float] | None = None
for entry, sim in usable:
game_type = str(entry.get("game_type", "")).lower()
if game_type not in ("", "game", "compil"):
continue
entry_name = (entry.get("game_name") or "").lower()
if entry_name.startswith((lower + ":", lower + " -")):
suffix = entry_name[len(lower) :].lstrip(" :-")
if not any(suffix.startswith(kw) for kw in _SUBSET_SUFFIXES) and (
best is None or entry.get("comp_100", 0) > best[0].get("comp_100", 0)
):
best = (entry, sim)
return best
def _resolve_exact_vs_extended(
best_exact: tuple[dict[str, Any], float] | None,
best_extended: tuple[dict[str, Any], float] | None,
usable: list[tuple[dict[str, Any], float]],
) -> tuple[dict[str, Any], float]:
"""Decide between exact match, extended entry, or highest similarity."""
if best_exact is not None and best_extended is not None:
exact_hours = best_exact[0].get("comp_100", 0)
extended_hours = best_extended[0].get("comp_100", 0)
exact_confidence = int(best_exact[0].get("comp_100_count", 0) or 0) + int(
best_exact[0].get("count_comp", 0) or 0
)
extended_confidence = int(best_extended[0].get("comp_100_count", 0) or 0) + int(
best_extended[0].get("count_comp", 0) or 0
)
# Prefer the extended entry when it has more hours AND either:
# (a) at least as much confidence (normal case), OR
# (b) dominant hours ratio (>=4x) with minimal data — handles cases
# like "FAITH: The Unholy Trinity" (17h, newer) vs "FAITH" 2017
# (1.5h, older/more data) where the older exact match has
# accumulated more confidence simply by being on HLTB longer.
dominates = (
exact_hours > 0
and extended_hours >= exact_hours * _EXTENDED_DOMINANCE_RATIO
and extended_confidence >= _EXTENDED_MIN_CONFIDENCE
)
if extended_hours > exact_hours and (
extended_confidence >= exact_confidence or dominates
):
return best_extended
return best_exact
if best_exact is not None:
return best_exact
if best_extended is not None:
return best_extended
# Fall back to highest similarity.
return max(usable, key=lambda x: x[1])
# ──────────────────────────────────────────────────────────────
# Async fetching with shared session & progress
# ──────────────────────────────────────────────────────────────

View File

@ -0,0 +1,189 @@
"""Building and issuing the HowLongToBeat search request.
Leaf helpers: they call nothing else in the module, so extracting
them introduces no cycle. Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
import asyncio
from http import HTTPStatus
import json
import logging
import time
from typing import Any
import aiohttp
from howlongtobeatpy.HTMLRequests import HTMLRequests
from steam_backlog_enforcer._hltb_matching import (
_find_best_extended,
_find_exact_match,
_resolve_exact_vs_extended,
_sanitize_search_name,
_similarity,
)
from steam_backlog_enforcer._hltb_types import (
MIN_SIMILARITY,
_AuthInfo,
)
logger = logging.getLogger(__name__)
# When extended entry has ≥ this many times more hours than the exact match,
# prefer it even if its confidence count is lower.
_EXTENDED_DOMINANCE_RATIO = 4.0
# Minimum combined confidence for the dominance path (avoids picking entries
# that have almost no data at all).
_EXTENDED_MIN_CONFIDENCE = 3
# ──────────────────────────────────────────────────────────────
# HLTB API setup (done once, not per-request like the library)
# ──────────────────────────────────────────────────────────────
def _get_hltb_search_url() -> str:
"""Discover the current HLTB search API endpoint.
Scrapes the homepage for JS bundles containing the fetch URL.
Falls back to ``/api/finder`` if extraction fails.
"""
try:
search_info = HTMLRequests.send_website_request_getcode(
parse_all_scripts=False,
)
if search_info is None:
search_info = HTMLRequests.send_website_request_getcode(
parse_all_scripts=True,
)
if search_info and search_info.search_url:
url: str = HTMLRequests.BASE_URL + search_info.search_url
return url
except (OSError, RuntimeError, ValueError, TypeError):
logger.debug("Failed to discover HLTB search URL, using default")
return "https://howlongtobeat.com/api/finder"
async def _get_auth_info(
search_url: str,
session: aiohttp.ClientSession,
) -> _AuthInfo | None:
"""Fetch the HLTB auth token and honeypot key/val (one GET request)."""
init_url = search_url + "/init"
ts = int(time.time() * 1000)
headers = {
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0"
),
"referer": "https://howlongtobeat.com/",
}
try:
async with session.get(
init_url,
params={"t": ts},
headers=headers,
) as resp:
if resp.status == HTTPStatus.OK:
data = await resp.json()
token: str | None = data.get("token")
if token is None:
return None
return _AuthInfo(
token=token,
hp_key=data.get("hpKey", ""),
hp_val=data.get("hpVal", ""),
)
except (aiohttp.ClientError, asyncio.TimeoutError):
logger.warning("Failed to get HLTB auth token")
return None
def _build_search_payload(game_name: str, auth: _AuthInfo | None = None) -> str:
"""Build the JSON POST body for an HLTB search."""
payload: dict[str, Any] = {
"searchType": "games",
"searchTerms": _sanitize_search_name(game_name).split(),
"searchPage": 1,
"size": 20,
"searchOptions": {
"games": {
"userId": 0,
"platform": "",
"sortCategory": "popular",
"rangeCategory": "main",
"rangeTime": {"min": 0, "max": 0},
"gameplay": {
"perspective": "",
"flow": "",
"genre": "",
"difficulty": "",
},
"rangeYear": {"max": "", "min": ""},
"modifier": "",
},
"users": {"sortCategory": "postcount"},
"lists": {"sortCategory": "follows"},
"filter": "",
"sort": 0,
"randomizer": 0,
},
"useCache": True,
}
if auth and auth.hp_key:
payload[auth.hp_key] = auth.hp_val
return json.dumps(payload)
def _collect_candidates(
query_name: str,
data: dict[str, Any],
) -> list[tuple[dict[str, Any], float]]:
"""Build candidate list from one HLTB response payload."""
candidates: list[tuple[dict[str, Any], float]] = []
lower_name = query_name.lower()
for entry in data.get("data", []):
entry_name = entry.get("game_name", "")
entry_alias = entry.get("game_alias", "") or ""
is_dlc = str(entry.get("game_type", "")).lower() == "dlc"
sim = max(
_similarity(query_name, entry_name),
_similarity(query_name, entry_alias),
)
is_full_edition = (
(not is_dlc) and entry_name.lower().startswith(lower_name + ":")
) or ((not is_dlc) and entry_name.lower().startswith(lower_name + " -"))
if sim >= MIN_SIMILARITY or is_full_edition:
comp_100 = entry.get("comp_100", 0)
if comp_100 and comp_100 > 0:
candidates.append((entry, sim))
return candidates
def _pick_best_hltb_entry(
search_name: str,
candidates: list[tuple[dict[str, Any], float]],
) -> tuple[dict[str, Any], float] | None:
"""Pick the best HLTB entry, preferring full editions over demos/chapters.
When a short name like "FAITH" matches both "FAITH" (demo) and
"FAITH: The Unholy Trinity" (full game), prefer the full game
since Steam often lists the full game under the shorter name.
When an exact match like "Timberman" (26 h) competes against an
unrelated subtitle entry like "Timberman: The Big Adventure" (2 h),
the exact match wins because it has more hours.
"""
if not candidates:
return None
# Prefer base games over DLC entries when both are present.
non_dlc = [c for c in candidates if str(c[0].get("game_type", "")).lower() != "dlc"]
usable = non_dlc or candidates
if len(usable) == 1:
return usable[0]
lower = search_name.lower()
best_exact = _find_exact_match(usable, lower)
best_extended = _find_best_extended(usable, lower)
return _resolve_exact_vs_extended(best_exact, best_extended, usable)

View File

@ -0,0 +1,114 @@
"""Toggling the protected/immutable flag on /etc/hosts around edits.
Leaf helpers: they call nothing else in the blocker, so extracting them
introduces no cycle. Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
import logging
from pathlib import Path
import shutil
import subprocess
from steam_backlog_enforcer.config import (
BLOCKED_DOMAINS,
HOSTS_FILE,
)
logger = logging.getLogger(__name__)
# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this
# module lives two levels below it); the script itself is in the
# linux_configuration checkout under testsAndMisc, not directly under $HOME.
_REPO_ROOT = Path(__file__).resolve().parents[2]
HOSTS_INSTALL_SCRIPT = (
_REPO_ROOT
/ "testsAndMisc"
/ "linux_configuration"
/ "scripts"
/ "periodic_background"
/ "hosts"
/ "install.sh"
)
# iptables chain name for our blocking rules.
IPTABLES_CHAIN = "STEAM_ENFORCER"
# Resolved absolute paths for executables (avoids S607 partial-path warnings).
_SUDO = shutil.which("sudo") or "/usr/bin/sudo"
_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables"
_BASH = shutil.which("bash") or "/usr/bin/bash"
_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl"
_TEE = shutil.which("tee") or "/usr/bin/tee"
# IP address used in /etc/hosts for blocking domains.
_HOSTS_REDIRECT_IP = ".".join(["0"] * 4)
def _disable_hosts_protection() -> None:
"""Temporarily unlock /etc/hosts so its content can be edited.
Guard-lib: stop watcher, collapse bind mount, chattr -i.
"""
subprocess.run(
[_SUDO, _GUARDCTL, "file-guard", "pacman-unlock", "hosts"],
capture_output=True,
timeout=10,
check=False,
)
def _enable_hosts_protection() -> None:
"""Re-lock /etc/hosts, adopting its current content as the new canonical.
Guard-lib: chattr +i, reapply bind mount, restart watcher.
"""
subprocess.run(
[_SUDO, _GUARDCTL, "file-guard", "sync", "hosts"],
capture_output=True,
timeout=10,
check=False,
)
def _sudo_write_hosts(content: str) -> None:
"""Write *content* to /etc/hosts via ``sudo tee``."""
subprocess.run(
[_SUDO, _TEE, str(HOSTS_FILE)],
input=content.encode(),
stdout=subprocess.DEVNULL,
timeout=10,
check=True,
)
def _reblock_hosts() -> bool:
"""Uncomment Steam Store entries in /etc/hosts."""
try:
_disable_hosts_protection()
content = HOSTS_FILE.read_text(encoding="utf-8")
new_lines = []
changed = False
for line in content.splitlines(keepends=True):
stripped = line.strip()
if stripped.startswith("# ") and any(
d in stripped for d in BLOCKED_DOMAINS
):
# Remove the '# ' prefix.
uncommented = line.replace("# ", "", 1)
new_lines.append(uncommented)
changed = True
else:
new_lines.append(line)
if changed:
_sudo_write_hosts("".join(new_lines))
logger.info("Re-enabled Steam Store entries in /etc/hosts.")
_enable_hosts_protection()
except OSError:
logger.exception("Failed to modify /etc/hosts")
return False
else:
return True

View File

@ -0,0 +1,147 @@
"""Abandonment and the status payload for manual picks.
Split out of :mod:`steam_backlog_enforcer._actions` to keep both files
under the 250-line cap.
"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any
from steam_backlog_enforcer._actions import (
find_manual_pick,
is_manual_pick_locked,
)
from steam_backlog_enforcer._allowed_games import (
active_manual_picks,
allowed_games,
)
from steam_backlog_enforcer._total_block import get_total_block_status
from steam_backlog_enforcer.game_install import get_installed_games, is_protected_app
from steam_backlog_enforcer.store_blocker import is_store_blocked
# Marks these two as an intentional re-export (they're imported from
# _allowed_games above, not defined here) -- without this, mypy's
# --no-implicit-reexport flags every downstream `from _actions import
# active_manual_picks` as an error. Everything else in this file is
# accessible normally; this only needs to list names imported-then-reexported.
__all__ = [
"active_manual_picks",
"allowed_games",
]
if TYPE_CHECKING:
from steam_backlog_enforcer.config import State
# How long an abandoned pick stays out of the auto-assignment pool, so that
# ``scan`` does not immediately hand back the game the user just rejected.
ABANDON_COOLDOWN_DAYS = 30
def manual_pick_age_days(state: State, app_id: int) -> float | None:
"""Return how many days ago *app_id* was picked, or ``None``.
Informational only — picks can be abandoned at any age. ``None`` means the
question does not apply: *app_id* is not an active manual pick, or its
timestamp is missing/malformed.
Args:
state: The loaded enforcer state.
app_id: The manually-picked app id to measure.
Returns:
Fractional days elapsed since the pick was made, or ``None`` when the
question does not apply.
"""
pick = find_manual_pick(state, app_id)
if pick is None or not pick.get("started_at"):
return None
try:
started = datetime.fromisoformat(pick["started_at"])
except ValueError:
return None
return (datetime.now(timezone.utc) - started).total_seconds() / 86400
def abandon_manual_pick(state: State, app_id: int) -> bool:
"""Drop one manual pick and persist ``state``.
A pick may be abandoned at any time, however long ago it was made.
Only the named pick is dropped: any other active pick keeps its own lock
and deadline. The abandoned app id goes onto the existing skip cooldown so
``scan`` will not hand the same game straight back. State-only: like
``apply_manual_pick`` this performs no uninstall/hide cascade, so the MCP
server can call it without touching the filesystem.
Args:
state: The enforcer state to mutate and save.
app_id: The manually-picked app id to back out of.
Returns:
``True`` if the pick was abandoned, ``False`` if it is not an active
pick, in which case ``state`` is untouched.
"""
if find_manual_pick(state, app_id) is None:
return False
state.skip_for_days(app_id, ABANDON_COOLDOWN_DAYS)
state.manual_picks = [
p for p in active_manual_picks(state) if p.get("app_id") != app_id
]
# The abandoned pick may also have been the current assignment; hand the
# assignment to a surviving pick so the enforcer keeps guarding it, or
# clear it so 'scan' can reassign.
if state.current_app_id == app_id:
survivor = state.manual_picks[-1] if state.manual_picks else None
state.current_app_id = survivor["app_id"] if survivor else None
state.current_game_name = survivor["game_name"] if survivor else ""
state.save()
return True
def status_payload(state: State) -> dict[str, Any]:
"""Build the structured status snapshot that ``cmd_status`` renders as text.
Pure data, no stdout — safe for the MCP server. Reads only ``State`` and the
stdout-free leaf helpers; never constructs ``Config`` and never exposes the
Steam API key.
Args:
state: The loaded enforcer state.
Returns:
A JSON-ready dict describing the current enforcement status.
"""
total_block = get_total_block_status()
installed = get_installed_games()
real_games = [(aid, name) for aid, name in installed if not is_protected_app(aid)]
assigned_installed = (
any(aid == state.current_app_id for aid, _ in installed)
if state.current_app_id
else None
)
return {
"current_app_id": state.current_app_id,
"current_game_name": state.current_game_name or None,
"finished_count": len(state.finished_app_ids),
"store_blocked": is_store_blocked(),
"installed_count": len(real_games),
"assigned_game_installed": assigned_installed,
"total_block": {
"active": total_block.active,
"days_remaining": round(total_block.days_remaining, 1),
"until": total_block.until.isoformat() if total_block.until else None,
},
"manual_pick_locked": is_manual_pick_locked(state),
"manual_picks": [
{
**pick,
"age_days": manual_pick_age_days(state, pick["app_id"]),
}
for pick in active_manual_picks(state)
],
}

View File

@ -1,426 +1,19 @@
"""MCP (Model Context Protocol) server for Steam Backlog Enforcer.
"""MCP server entry point for the Steam Backlog Enforcer.
Exposes the enforcer's read surface and two *gated* write actions as typed MCP
tools, so an MCP client (Claude Code and its subagents) can query and — with
explicit confirmation — drive the backlog without shelling out to the CLI.
Run via the dedicated venv that has the ``mcp`` extra installed::
~/.venvs/steam-backlog-mcp/bin/python -m steam_backlog_enforcer._mcp
(see ``scripts/setup_mcp.sh`` and the repo-root ``.mcp.json``).
Safety invariants (do not break when adding tools):
* **stdout is the JSON-RPC channel.** This module and every function a tool
calls must never write to stdout. All logging is routed to STDERR below, and
tools call only stdout-free leaf helpers (never the ``cmd_*`` handlers, which
``_echo`` to stdout / ``input()`` / ``sys.exit()``).
* **No secret ever leaves.** There is no tool that returns ``Config`` or reads
``config.json``; read tools load only ``State`` and the secrets-free web
dataset. Game-name lookups use the on-disk snapshot only (no Steam API key).
* **Writes are gated.** Every write tool defaults to a dry-run preview and
mutates only when ``confirm=True``. These write tools must never be added to
a permission allowlist (a subagent could then bypass the human).
The tools themselves live in :mod:`steam_backlog_enforcer._mcp_query` (read
only) and :mod:`steam_backlog_enforcer._mcp_actions` (state changing); both
are imported here for their registration side effect.
"""
from __future__ import annotations
from datetime import datetime, timezone
import logging
import os
import sys
from typing import Any
from mcp.server.fastmcp import FastMCP
from steam_backlog_enforcer import _mcp_actions, _mcp_gaming_time, _mcp_query
from steam_backlog_enforcer._mcp_server import logger, mcp
from steam_backlog_enforcer._actions import (
ABANDON_COOLDOWN_DAYS,
MANUAL_GRACE_DAYS,
abandon_manual_pick,
active_manual_picks,
apply_manual_pick,
can_abandon_manual_pick,
find_manual_pick,
manual_pick_grace_remaining,
status_payload,
)
from steam_backlog_enforcer._allowed_games import MANUAL_LOCK_DAYS
from steam_backlog_enforcer._playtime import (
PlaytimeState,
gaming_day_key,
load_state,
rules_for,
save_state,
)
from steam_backlog_enforcer._playtime_block import mounted_targets, release_block
from steam_backlog_enforcer._total_block import start_total_block
from steam_backlog_enforcer._web_dataset import build_web_dataset, dataset_to_payload
from steam_backlog_enforcer.config import Config, State, load_snapshot
from steam_backlog_enforcer.steam_api import GameInfo
# Log to STDERR only — STDOUT carries the MCP JSON-RPC protocol frames, so a
# single stray stdout write would corrupt the stream and kill the session.
logging.basicConfig(
level=logging.INFO,
stream=sys.stderr,
format="%(asctime)s [%(levelname)s] steam-mcp: %(message)s",
)
logger = logging.getLogger(__name__)
mcp = FastMCP("steam-backlog-enforcer")
_DEFAULT_LIST_LIMIT = 50
def _resolve_game_name(app_id: int) -> str | None:
"""Resolve a game name from the on-disk snapshot only (no Config / API).
Deliberately snapshot-only: it never constructs ``Config`` and never touches
the Steam API key, so it is safe to call from an MCP tool. A game absent from
the last snapshot simply resolves to ``None``.
Args:
app_id: The Steam app id to look up.
Returns:
The game name, or ``None`` if not present in the snapshot.
"""
snapshot = load_snapshot()
if snapshot:
for entry in snapshot:
if entry.get("app_id") == app_id:
return str(entry["name"])
return None
def _backlog_sort_key(game: GameInfo) -> tuple[int, float]:
"""Sort incomplete games shortest-completionist-first, unknowns last."""
if game.completionist_hours > 0:
return (0, game.completionist_hours)
return (1, 0.0)
# ──────────────────────────────────────────────────────────────
# Read tools (State-only; never expose Config / the Steam API key)
# ──────────────────────────────────────────────────────────────
@mcp.tool()
def get_dataset() -> dict[str, Any]:
"""Return the full, secrets-free backlog dataset.
Includes every incomplete candidate game with HowLongToBeat times,
ProtonDB tiers, pace-vs-HLTB calibration, and the default CLI thresholds —
the same projection the local web UI consumes. Reads on-disk caches only
(no network, no Steam API key).
"""
return dataset_to_payload(build_web_dataset(State.load()))
@mcp.tool()
def get_status() -> dict[str, Any]:
"""Return the current enforcer status.
Reports the assigned game, finished count, whether the Steam store is
blocked, installed-game count, any active total block (with days remaining),
and whether a manual-pick lock is in force.
"""
return status_payload(State.load())
@mcp.tool()
def get_stats() -> dict[str, Any]:
"""Return backlog completion-time estimates.
A focused subset of the dataset: the default qualifying-games summary
(rush / leisure / worst-case totals) and the player's measured pace versus
HowLongToBeat.
"""
payload = dataset_to_payload(build_web_dataset(State.load()))
return {
"default_summary": payload["default_summary"],
"pace_vs_hltb": payload["pace_vs_hltb"],
}
@mcp.tool()
def list_backlog(limit: int = _DEFAULT_LIST_LIMIT) -> dict[str, Any]:
"""List incomplete games, shortest-completionist-first, capped at ``limit``.
Args:
limit: Maximum number of games to return (non-positive returns none).
"""
snapshot = load_snapshot()
if snapshot is None:
return {
"total": 0,
"returned": 0,
"games": [],
"note": "No snapshot found. Run 'scan' first.",
}
games = [GameInfo.from_snapshot(entry) for entry in snapshot]
incomplete = sorted((g for g in games if not g.is_complete), key=_backlog_sort_key)
capped = incomplete[: max(0, limit)]
return {
"total": len(incomplete),
"returned": len(capped),
"games": [
{
"app_id": g.app_id,
"name": g.name,
"completion_pct": round(g.completion_pct, 1),
"completionist_hours": g.completionist_hours,
}
for g in capped
],
}
# ──────────────────────────────────────────────────────────────
# Gated write tools (preview unless confirm=True; NEVER allowlist these)
# ──────────────────────────────────────────────────────────────
@mcp.tool()
def pick_manual(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
"""Lock the enforcer to a game by Steam app_id (gated write).
With ``confirm=False`` (the default) this performs **no** mutation and
returns a preview of what confirming would do. Call again with
``confirm=True`` to apply. Applying overrides the current assignment and
locks all other commands for ``MANUAL_LOCK_DAYS`` days (or until 100%
achievements). Unlike the CLI's ``pick-manual``, this mutates **state only**
— it never uninstalls, installs, or hides games.
Args:
app_id: The Steam app id to lock in (must exist in the last snapshot).
confirm: Set ``True`` to actually apply the pick; otherwise preview.
"""
game_name = _resolve_game_name(app_id)
if game_name is None:
return {
"ok": False,
"reason": f"AppID={app_id} not found in the snapshot. Run 'scan' first.",
}
if not confirm:
return {
"ok": True,
"preview": True,
"action": "pick_manual",
"app_id": app_id,
"game_name": game_name,
"effect": (
"Overrides the current assignment and locks all other commands "
f"for {MANUAL_LOCK_DAYS} days or until 100% achievements."
),
"confirm_required": True,
}
state = State.load()
refused = apply_manual_pick(
state,
app_id,
game_name,
max_picks=Config.load().max_manual_picks,
)
if refused is not None:
return {"ok": False, "reason": refused}
logger.info("pick_manual applied: %s (AppID=%s)", game_name, app_id)
return {
"ok": True,
"applied": True,
"action": "pick_manual",
"app_id": app_id,
"game_name": game_name,
}
@mcp.tool()
def abandon_pick(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
"""Undo a manual pick inside its grace window (gated write).
With ``confirm=False`` (the default) this performs **no** mutation and
returns a preview. Only works within ``MANUAL_GRACE_DAYS`` days of the
pick. Like ``pick_manual``, this mutates **state only** — the CLI's
``abandon-pick`` additionally uninstalls the abandoned game.
Args:
app_id: The manually-picked app id to back out of.
confirm: Set ``True`` to actually abandon the pick; otherwise preview.
"""
state = State.load()
picks = active_manual_picks(state)
if not picks:
return {"ok": False, "reason": "No manual pick is active."}
pick = find_manual_pick(state, app_id)
if pick is None:
listed = ", ".join(f"AppID={p['app_id']}" for p in picks)
return {
"ok": False,
"reason": (
f"AppID={app_id} is not one of the active manual picks ({listed})."
),
}
remaining = manual_pick_grace_remaining(state, app_id)
if not can_abandon_manual_pick(state, app_id):
return {
"ok": False,
"reason": (
f"The {MANUAL_GRACE_DAYS}-day grace period has expired; "
"the pick can no longer be abandoned."
),
}
game_name = str(pick["game_name"])
if not confirm:
return {
"ok": True,
"preview": True,
"action": "abandon_pick",
"app_id": app_id,
"game_name": game_name,
"grace_days_left": remaining,
"effect": (
"Releases the manual pick lock, clears the assignment, and "
f"keeps the game out of auto-assignment for "
f"{ABANDON_COOLDOWN_DAYS} days."
),
"confirm_required": True,
}
abandon_manual_pick(state, app_id)
logger.info("abandon_pick applied: %s (AppID=%s)", game_name, app_id)
return {
"ok": True,
"applied": True,
"action": "abandon_pick",
"app_id": app_id,
"game_name": game_name,
}
@mcp.tool()
def block_gaming(days: int, *, confirm: bool = False) -> dict[str, Any]:
"""Start a total gaming block for ``days`` days (gated, privileged write).
With ``confirm=False`` (the default) returns a preview only. With
``confirm=True`` it attempts the block, which **requires root** (it edits
``/etc/hosts`` and uninstalls Steam). The MCP server runs unprivileged, so
this will normally return ``{"ok": false, "reason": "requires elevated
privileges"}`` rather than succeeding. There is no in-app undo.
Args:
days: Whole number of days to block all gaming (must be >= 1).
confirm: Set ``True`` to attempt the block; otherwise preview.
"""
if days < 1:
return {"ok": False, "reason": "days must be at least 1."}
if not confirm:
return {
"ok": True,
"preview": True,
"action": "block_gaming",
"days": days,
"effect": (
f"For {days} day(s): uninstalls Steam, kills game launchers, and "
"blocks Steam + game-website domains. There is NO in-app undo."
),
"requires_root": True,
"confirm_required": True,
}
try:
applied = start_total_block(days)
except (OSError, RuntimeError) as exc: # never crash the server on a write
logger.warning("block_gaming failed: %s", exc)
return {"ok": False, "reason": "requires elevated privileges"}
if not applied:
return {"ok": False, "reason": "requires elevated privileges"}
logger.info("block_gaming applied: %d day(s)", days)
return {"ok": True, "applied": True, "action": "block_gaming", "days": days}
@mcp.tool()
def get_gaming_time() -> dict[str, Any]:
"""Return today's gaming-budget usage and whether the cutoff has engaged.
The gaming day starts at 06:00 local time, so a session played after
midnight still counts against the day it began in. Reads on-disk state and
the live mount table only — no network, no Steam API key, no config secrets.
"""
config = Config.load()
rules = rules_for(config, demo=False)
stored = load_state(demo=False)
masked = sorted(str(path) for path in mounted_targets())
if stored is None:
return {
"ok": True,
"recorded": False,
"budget_seconds": rules.budget_seconds,
"enforcement": rules.enforcement,
"masked_launchers": masked,
}
return {
"ok": True,
"recorded": True,
"gaming_day": stored.day_key,
"day_starts_at": "06:00 local",
"seconds_used": round(stored.seconds, 1),
"budget_seconds": rules.budget_seconds,
"seconds_remaining": round(max(0.0, rules.budget_seconds - stored.seconds), 1),
"blocked": stored.is_blocked(),
"enforcement": rules.enforcement,
"counts_launchers": rules.count_launchers,
"masked_launchers": masked,
}
@mcp.tool()
def reset_gaming_time(*, confirm: bool = False) -> dict[str, Any]:
"""Reset today's gaming counter and lift the block (gated, privileged write).
With ``confirm=False`` (the default) returns a preview and mutates nothing.
With ``confirm=True`` it attempts the reset, which **requires root** (it
releases bind mounts over ``/usr/bin/steam`` and friends). The MCP server
runs unprivileged, so this will normally return ``{"ok": false, "reason":
"requires elevated privileges"}`` rather than succeeding.
Args:
confirm: Set ``True`` to attempt the reset; otherwise preview.
"""
if not confirm:
return {
"ok": True,
"preview": True,
"action": "reset_gaming_time",
"effect": (
"Zeroes today's gaming counter and unmasks every launcher "
"binary, restoring a full daily budget immediately."
),
"requires_root": True,
"confirm_required": True,
}
if os.geteuid() != 0:
return {"ok": False, "reason": "requires elevated privileges"}
try:
released = release_block()
now = datetime.now(timezone.utc).astimezone()
save_state(
PlaytimeState(day_key=gaming_day_key(now), last_tick_at=now.timestamp()),
demo=False,
)
except (OSError, ValueError) as exc: # never crash the server on a write
logger.warning("reset_gaming_time failed: %s", exc)
return {"ok": False, "reason": "requires elevated privileges"}
logger.info("reset_gaming_time applied; released %d mount(s)", len(released))
return {
"ok": True,
"applied": True,
"action": "reset_gaming_time",
"released": [str(path) for path in released],
}
# Imported for their @mcp.tool() registration side effect.
__all__ = ["_mcp_actions", "_mcp_gaming_time", "_mcp_query", "main", "mcp"]
def main() -> None:

View File

@ -0,0 +1,178 @@
"""Mutating MCP tools: manual picks, abandonment and gaming blocks.
Every tool here takes an explicit ``confirm`` flag, so a model cannot change
enforcement state on a single unconfirmed call. The read-only half lives in
:mod:`steam_backlog_enforcer._mcp_query`.
"""
from __future__ import annotations
from typing import Any
from steam_backlog_enforcer._actions import (
ABANDON_COOLDOWN_DAYS,
abandon_manual_pick,
active_manual_picks,
apply_manual_pick,
find_manual_pick,
manual_pick_age_days,
)
from steam_backlog_enforcer._allowed_games import MANUAL_LOCK_DAYS
from steam_backlog_enforcer._mcp_server import (
_resolve_game_name,
logger,
mcp,
)
from steam_backlog_enforcer._total_block import start_total_block
from steam_backlog_enforcer.config import Config, State
@mcp.tool()
def pick_manual(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
"""Lock the enforcer to a game by Steam app_id (gated write).
With ``confirm=False`` (the default) this performs **no** mutation and
returns a preview of what confirming would do. Call again with
``confirm=True`` to apply. Applying overrides the current assignment and
locks all other commands for ``MANUAL_LOCK_DAYS`` days (or until 100%
achievements). Unlike the CLI's ``pick-manual``, this mutates **state only**
— it never uninstalls, installs, or hides games.
Args:
app_id: The Steam app id to lock in (must exist in the last snapshot).
confirm: Set ``True`` to actually apply the pick; otherwise preview.
"""
game_name = _resolve_game_name(app_id)
if game_name is None:
return {
"ok": False,
"reason": f"AppID={app_id} not found in the snapshot. Run 'scan' first.",
}
if not confirm:
return {
"ok": True,
"preview": True,
"action": "pick_manual",
"app_id": app_id,
"game_name": game_name,
"effect": (
"Overrides the current assignment and locks all other commands "
f"for {MANUAL_LOCK_DAYS} days or until 100% achievements."
),
"confirm_required": True,
}
state = State.load()
refused = apply_manual_pick(
state,
app_id,
game_name,
max_picks=Config.load().max_manual_picks,
)
if refused is not None:
return {"ok": False, "reason": refused}
logger.info("pick_manual applied: %s (AppID=%s)", game_name, app_id)
return {
"ok": True,
"applied": True,
"action": "pick_manual",
"app_id": app_id,
"game_name": game_name,
}
@mcp.tool()
def abandon_pick(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
"""Undo a manual pick (gated write).
With ``confirm=False`` (the default) this performs **no** mutation and
returns a preview. A pick can be abandoned at any time, however long ago
it was made. Like ``pick_manual``, this mutates **state only** — the CLI's
``abandon-pick`` additionally uninstalls the abandoned game.
Args:
app_id: The manually-picked app id to back out of.
confirm: Set ``True`` to actually abandon the pick; otherwise preview.
"""
state = State.load()
picks = active_manual_picks(state)
if not picks:
return {"ok": False, "reason": "No manual pick is active."}
pick = find_manual_pick(state, app_id)
if pick is None:
listed = ", ".join(f"AppID={p['app_id']}" for p in picks)
return {
"ok": False,
"reason": (
f"AppID={app_id} is not one of the active manual picks ({listed})."
),
}
age = manual_pick_age_days(state, app_id)
game_name = str(pick["game_name"])
if not confirm:
return {
"ok": True,
"preview": True,
"action": "abandon_pick",
"app_id": app_id,
"game_name": game_name,
"age_days": age,
"effect": (
"Releases the manual pick lock, clears the assignment, and "
f"keeps the game out of auto-assignment for "
f"{ABANDON_COOLDOWN_DAYS} days."
),
"confirm_required": True,
}
abandon_manual_pick(state, app_id)
logger.info("abandon_pick applied: %s (AppID=%s)", game_name, app_id)
return {
"ok": True,
"applied": True,
"action": "abandon_pick",
"app_id": app_id,
"game_name": game_name,
}
@mcp.tool()
def block_gaming(days: int, *, confirm: bool = False) -> dict[str, Any]:
"""Start a total gaming block for ``days`` days (gated, privileged write).
With ``confirm=False`` (the default) returns a preview only. With
``confirm=True`` it attempts the block, which **requires root** (it edits
``/etc/hosts`` and uninstalls Steam). The MCP server runs unprivileged, so
this will normally return ``{"ok": false, "reason": "requires elevated
privileges"}`` rather than succeeding. There is no in-app undo.
Args:
days: Whole number of days to block all gaming (must be >= 1).
confirm: Set ``True`` to attempt the block; otherwise preview.
"""
if days < 1:
return {"ok": False, "reason": "days must be at least 1."}
if not confirm:
return {
"ok": True,
"preview": True,
"action": "block_gaming",
"days": days,
"effect": (
f"For {days} day(s): uninstalls Steam, kills game launchers, and "
"blocks Steam + game-website domains. There is NO in-app undo."
),
"requires_root": True,
"confirm_required": True,
}
try:
applied = start_total_block(days)
except (OSError, RuntimeError) as exc: # never crash the server on a write
logger.warning("block_gaming failed: %s", exc)
return {"ok": False, "reason": "requires elevated privileges"}
if not applied:
return {"ok": False, "reason": "requires elevated privileges"}
logger.info("block_gaming applied: %d day(s)", days)
return {"ok": True, "applied": True, "action": "block_gaming", "days": days}

View File

@ -0,0 +1,109 @@
"""MCP tools for the daily gaming-time budget.
Reading today's usage and resetting it are separated from the pick/block
tools because they operate on the playtime state, not on which game is
assigned.
"""
from __future__ import annotations
from datetime import datetime, timezone
import os
from typing import Any
from steam_backlog_enforcer._mcp_server import (
logger,
mcp,
)
from steam_backlog_enforcer._playtime import (
PlaytimeState,
gaming_day_key,
load_state,
rules_for,
save_state,
)
from steam_backlog_enforcer._playtime_block import mounted_targets, release_block
from steam_backlog_enforcer.config import Config
@mcp.tool()
def get_gaming_time() -> dict[str, Any]:
"""Return today's gaming-budget usage and whether the cutoff has engaged.
The gaming day starts at 06:00 local time, so a session played after
midnight still counts against the day it began in. Reads on-disk state and
the live mount table only — no network, no Steam API key, no config secrets.
"""
config = Config.load()
rules = rules_for(config, demo=False)
stored = load_state(demo=False)
masked = sorted(str(path) for path in mounted_targets())
if stored is None:
return {
"ok": True,
"recorded": False,
"budget_seconds": rules.budget_seconds,
"enforcement": rules.enforcement,
"masked_launchers": masked,
}
return {
"ok": True,
"recorded": True,
"gaming_day": stored.day_key,
"day_starts_at": "06:00 local",
"seconds_used": round(stored.seconds, 1),
"budget_seconds": rules.budget_seconds,
"seconds_remaining": round(max(0.0, rules.budget_seconds - stored.seconds), 1),
"blocked": stored.is_blocked(),
"enforcement": rules.enforcement,
"counts_launchers": rules.count_launchers,
"masked_launchers": masked,
}
@mcp.tool()
def reset_gaming_time(*, confirm: bool = False) -> dict[str, Any]:
"""Reset today's gaming counter and lift the block (gated, privileged write).
With ``confirm=False`` (the default) returns a preview and mutates nothing.
With ``confirm=True`` it attempts the reset, which **requires root** (it
releases bind mounts over ``/usr/bin/steam`` and friends). The MCP server
runs unprivileged, so this will normally return ``{"ok": false, "reason":
"requires elevated privileges"}`` rather than succeeding.
Args:
confirm: Set ``True`` to attempt the reset; otherwise preview.
"""
if not confirm:
return {
"ok": True,
"preview": True,
"action": "reset_gaming_time",
"effect": (
"Zeroes today's gaming counter and unmasks every launcher "
"binary, restoring a full daily budget immediately."
),
"requires_root": True,
"confirm_required": True,
}
if os.geteuid() != 0:
return {"ok": False, "reason": "requires elevated privileges"}
try:
released = release_block()
now = datetime.now(timezone.utc).astimezone()
save_state(
PlaytimeState(day_key=gaming_day_key(now), last_tick_at=now.timestamp()),
demo=False,
)
except (OSError, ValueError) as exc: # never crash the server on a write
logger.warning("reset_gaming_time failed: %s", exc)
return {"ok": False, "reason": "requires elevated privileges"}
logger.info("reset_gaming_time applied; released %d mount(s)", len(released))
return {
"ok": True,
"applied": True,
"action": "reset_gaming_time",
"released": [str(path) for path in released],
}

View File

@ -0,0 +1,98 @@
"""Read-only MCP tools: dataset, status, stats and the backlog list.
Separated from the mutating tools in
:mod:`steam_backlog_enforcer._mcp_actions` so that "what can this server
change?" is answerable by looking at one file.
"""
from __future__ import annotations
from typing import Any
from steam_backlog_enforcer._actions import (
status_payload,
)
from steam_backlog_enforcer._mcp_server import (
_DEFAULT_LIST_LIMIT,
_backlog_sort_key,
mcp,
)
from steam_backlog_enforcer._web_dataset import build_web_dataset, dataset_to_payload
from steam_backlog_enforcer.config import State, load_snapshot
from steam_backlog_enforcer.steam_api import GameInfo
@mcp.tool()
def get_dataset() -> dict[str, Any]:
"""Return the full, secrets-free backlog dataset.
Includes every incomplete candidate game with HowLongToBeat times,
ProtonDB tiers, pace-vs-HLTB calibration, and the default CLI thresholds —
the same projection the local web UI consumes. Reads on-disk caches only
(no network, no Steam API key).
"""
return dataset_to_payload(build_web_dataset(State.load()))
@mcp.tool()
def get_status() -> dict[str, Any]:
"""Return the current enforcer status.
Reports the assigned game, finished count, whether the Steam store is
blocked, installed-game count, any active total block (with days remaining),
and whether a manual-pick lock is in force.
"""
return status_payload(State.load())
@mcp.tool()
def get_stats() -> dict[str, Any]:
"""Return backlog completion-time estimates.
A focused subset of the dataset: the default qualifying-games summary
(rush / leisure / worst-case totals) and the player's measured pace versus
HowLongToBeat.
"""
payload = dataset_to_payload(build_web_dataset(State.load()))
return {
"default_summary": payload["default_summary"],
"pace_vs_hltb": payload["pace_vs_hltb"],
}
@mcp.tool()
def list_backlog(limit: int = _DEFAULT_LIST_LIMIT) -> dict[str, Any]:
"""List incomplete games, shortest-completionist-first, capped at ``limit``.
Args:
limit: Maximum number of games to return (non-positive returns none).
"""
snapshot = load_snapshot()
if snapshot is None:
return {
"total": 0,
"returned": 0,
"games": [],
"note": "No snapshot found. Run 'scan' first.",
}
games = [GameInfo.from_snapshot(entry) for entry in snapshot]
incomplete = sorted((g for g in games if not g.is_complete), key=_backlog_sort_key)
capped = incomplete[: max(0, limit)]
return {
"total": len(incomplete),
"returned": len(capped),
"games": [
{
"app_id": g.app_id,
"name": g.name,
"completion_pct": round(g.completion_pct, 1),
"completionist_hours": g.completionist_hours,
}
for g in capped
],
}
# ──────────────────────────────────────────────────────────────
# Gated write tools (preview unless confirm=True; NEVER allowlist these)
# ──────────────────────────────────────────────────────────────

View File

@ -0,0 +1,83 @@
"""MCP (Model Context Protocol) server for Steam Backlog Enforcer.
Exposes the enforcer's read surface and two *gated* write actions as typed MCP
tools, so an MCP client (Claude Code and its subagents) can query and — with
explicit confirmation — drive the backlog without shelling out to the CLI.
Run via the dedicated venv that has the ``mcp`` extra installed::
~/.venvs/steam-backlog-mcp/bin/python -m steam_backlog_enforcer._mcp
(see ``scripts/setup_mcp.sh`` and the repo-root ``.mcp.json``).
Safety invariants (do not break when adding tools):
* **stdout is the JSON-RPC channel.** This module and every function a tool
calls must never write to stdout. All logging is routed to STDERR below, and
tools call only stdout-free leaf helpers (never the ``cmd_*`` handlers, which
``_echo`` to stdout / ``input()`` / ``sys.exit()``).
* **No secret ever leaves.** There is no tool that returns ``Config`` or reads
``config.json``; read tools load only ``State`` and the secrets-free web
dataset. Game-name lookups use the on-disk snapshot only (no Steam API key).
* **Writes are gated.** Every write tool defaults to a dry-run preview and
mutates only when ``confirm=True``. These write tools must never be added to
a permission allowlist (a subagent could then bypass the human).
"""
from __future__ import annotations
import logging
import sys
from typing import TYPE_CHECKING
from mcp.server.fastmcp import FastMCP
from steam_backlog_enforcer.config import load_snapshot
if TYPE_CHECKING:
from steam_backlog_enforcer.steam_api import GameInfo
# Log to STDERR only — STDOUT carries the MCP JSON-RPC protocol frames, so a
# single stray stdout write would corrupt the stream and kill the session.
logging.basicConfig(
level=logging.INFO,
stream=sys.stderr,
format="%(asctime)s [%(levelname)s] steam-mcp: %(message)s",
)
logger = logging.getLogger(__name__)
mcp = FastMCP("steam-backlog-enforcer")
_DEFAULT_LIST_LIMIT = 50
def _resolve_game_name(app_id: int) -> str | None:
"""Resolve a game name from the on-disk snapshot only (no Config / API).
Deliberately snapshot-only: it never constructs ``Config`` and never touches
the Steam API key, so it is safe to call from an MCP tool. A game absent from
the last snapshot simply resolves to ``None``.
Args:
app_id: The Steam app id to look up.
Returns:
The game name, or ``None`` if not present in the snapshot.
"""
snapshot = load_snapshot()
if snapshot:
for entry in snapshot:
if entry.get("app_id") == app_id:
return str(entry["name"])
return None
def _backlog_sort_key(game: GameInfo) -> tuple[int, float]:
"""Sort incomplete games shortest-completionist-first, unknowns last."""
if game.completionist_hours > 0:
return (0, game.completionist_hours)
return (1, 0.0)
# ──────────────────────────────────────────────────────────────
# Read tools (State-only; never expose Config / the Steam API key)
# ──────────────────────────────────────────────────────────────

View File

@ -0,0 +1,121 @@
"""Cached lookup of the Steam account's full owned-app list.
Split out of :mod:`steam_backlog_enforcer._enforce_loop` to keep both files
under the 250-line cap. The enforce loop runs every 3s but the owned-games
list changes rarely, so it is cached on disk with a TTL rather than re-fetched
from the Steam Web API each pass.
"""
from __future__ import annotations
import json
import logging
import time
from typing import Any
from steam_backlog_enforcer.config import (
CONFIG_DIR,
Config,
_atomic_write,
load_snapshot,
)
from steam_backlog_enforcer.steam_api import SteamAPIClient
logger = logging.getLogger(__name__)
_OWNED_IDS_CACHE_FILE = CONFIG_DIR / "owned_app_ids_cache.json"
_OWNED_IDS_CACHE_TTL_SECONDS = 3600
def _load_owned_app_ids_cache(steam_id: str) -> list[int] | None:
"""Return fresh cached owned app IDs for this steam_id, if available."""
if not steam_id or not _OWNED_IDS_CACHE_FILE.exists():
return None
try:
data: dict[str, Any] = json.loads(
_OWNED_IDS_CACHE_FILE.read_text(encoding="utf-8")
)
except (json.JSONDecodeError, OSError, ValueError):
return None
cached_steam_id = str(data.get("steam_id", ""))
if cached_steam_id != steam_id:
return None
fetched_at = float(data.get("fetched_at", 0.0) or 0.0)
age = time.time() - fetched_at
if age > _OWNED_IDS_CACHE_TTL_SECONDS:
return None
raw_ids = data.get("app_ids", [])
if not isinstance(raw_ids, list):
return None
return [int(app_id) for app_id in raw_ids]
def _save_owned_app_ids_cache(steam_id: str, app_ids: list[int]) -> None:
"""Persist owned app IDs cache for this steam_id."""
payload = {
"steam_id": steam_id,
"fetched_at": time.time(),
"app_ids": app_ids,
}
_atomic_write(_OWNED_IDS_CACHE_FILE, json.dumps(payload, indent=2) + "\n")
# ──────────────────────────────────────────────────────────────
# Helpers
# ──────────────────────────────────────────────────────────────
def get_all_owned_app_ids(config: Config) -> list[int]:
"""Get all owned game app IDs from Steam API plus snapshot fallback.
Snapshot data contains only games with achievements, so API data is the
primary source for library hiding. Snapshot IDs are merged in to keep
behavior resilient when the API result is partial.
"""
snapshot = load_snapshot() or []
snapshot_ids = [int(d["app_id"]) for d in snapshot if "app_id" in d]
cached_ids = _load_owned_app_ids_cache(config.steam_id)
if cached_ids is not None:
merged_ids: list[int] = []
seen: set[int] = set()
for app_id in [*cached_ids, *snapshot_ids]:
if app_id in seen:
continue
seen.add(app_id)
merged_ids.append(app_id)
logger.info("Using cached Steam owned IDs (%d entries).", len(cached_ids))
return merged_ids
try:
client = SteamAPIClient(config.steam_api_key, config.steam_id)
owned = client.get_owned_games()
api_ids = [int(g["appid"]) for g in owned if "appid" in g]
_save_owned_app_ids_cache(config.steam_id, api_ids)
merged_ids: list[int] = []
seen: set[int] = set()
for app_id in [*api_ids, *snapshot_ids]:
if app_id in seen:
continue
seen.add(app_id)
merged_ids.append(app_id)
except (OSError, RuntimeError, ValueError):
if snapshot_ids:
return snapshot_ids
logger.warning("Could not fetch owned game list for hiding.")
return []
else:
return merged_ids
# ──────────────────────────────────────────────────────────────
# Enforce mode (daemon loop)
# ──────────────────────────────────────────────────────────────
# How often the enforce loop runs (seconds).

View File

@ -0,0 +1,78 @@
"""Thin, reusable wrappers around the pacman package manager.
These three operations (query owner, query installed, remove) carry no
total-block policy of their own -- they are the generic primitives the
total-block purge is written in terms of, which is why they live here
rather than inside it.
"""
from __future__ import annotations
import logging
import shutil
import subprocess
logger = logging.getLogger(__name__)
_SUDO = shutil.which("sudo") or "/usr/bin/sudo"
# Call pacman.orig directly (bypassing pacman_wrapper's interactive
# word-unscramble challenge for "steam") - this is the tool's own
# authorized action, not a user bypass attempt, and enforce_total_block_tick
# must be able to run unattended.
PACMAN = shutil.which("pacman.orig") or shutil.which("pacman") or "/usr/bin/pacman.orig"
def pacman_owner(path: str) -> str | None:
"""Return the pacman package name that owns *path*, or None."""
result = subprocess.run(
[PACMAN, "-Qo", path],
capture_output=True,
text=True,
timeout=10,
check=False,
)
if result.returncode != 0:
return None
marker = " is owned by "
if marker not in result.stdout:
return None
tail = result.stdout.split(marker, 1)[1].strip()
return tail.split()[0] if tail else None
def is_package_installed(package: str) -> bool:
"""Return True if *package* is currently installed via pacman."""
result = subprocess.run(
[PACMAN, "-Qi", package],
capture_output=True,
timeout=10,
check=False,
)
return result.returncode == 0
def uninstall_package(package: str) -> bool:
"""Remove *package* via pacman. Returns True on success or if absent."""
try:
result = subprocess.run(
[_SUDO, PACMAN, "-R", "--noconfirm", package],
capture_output=True,
text=True,
timeout=120,
check=False,
)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to run pacman -R %s", package)
return False
if result.returncode == 0:
return True
if "target not found" in (result.stderr or "").lower():
return True
logger.error(
"pacman -R %s failed (rc=%d): %s",
package,
result.returncode,
result.stderr[-500:] if result.stderr else "",
)
return False

View File

@ -27,398 +27,45 @@ is why :func:`get_pids_by_cmdline_names` exists alongside
from __future__ import annotations
from dataclasses import dataclass, field, replace
from datetime import datetime, timedelta, timezone
import json
from dataclasses import replace
from datetime import datetime, timezone
import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING
from steam_backlog_enforcer._playtime_block import (
kill_gaming_processes,
mounted_targets,
reconcile,
request_steam_shutdown,
steam_and_launcher_pids,
)
from steam_backlog_enforcer._total_block import (
LAUNCHER_PROCESS_NAMES,
is_total_block_active,
from steam_backlog_enforcer._playtime_budget import (
accumulate,
roll_over,
)
from steam_backlog_enforcer._whitelist import _try_set_immutable, unlock_for_write
from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
from steam_backlog_enforcer.enforcer import (
get_pids_by_process_names,
get_running_steam_game_pids,
from steam_backlog_enforcer._playtime_cutoff import (
_begin_cutoff,
_sustain_block,
_warn,
)
from steam_backlog_enforcer.library_hider import _resolve_desktop_user, _run_as_user
from steam_backlog_enforcer._playtime_procs import qualifying_pids
from steam_backlog_enforcer._playtime_state import (
PlaytimeRules,
PlaytimeState,
gaming_day_key,
load_state,
rules_for,
save_state,
)
from steam_backlog_enforcer._total_block import is_total_block_active
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config
logger = logging.getLogger(__name__)
PLAYTIME_STATE_FILE = CONFIG_DIR / "playtime_state.json"
PLAYTIME_DEMO_STATE_FILE = CONFIG_DIR / "playtime_demo_state.json"
_PROC = Path("/proc")
_SCHEMA_VERSION = 1
# The gaming day starts here, local time. 05:59 belongs to the previous day.
_DAY_BOUNDARY_HOURS = 6
# Each tick's measured delta is capped at this many tick intervals. Two is the
# smallest value that tolerates one skipped tick without inflating the count.
_DELTA_CLAMP_FACTOR = 2.0
_DEFAULT_BUDGET_SECONDS = 8 * 3600.0
_DEMO_BUDGET_SECONDS = 60.0
# Seconds remaining at which to warn, descending.
_WARN_AT: tuple[int, ...] = (3600, 1800, 600, 300)
_DEMO_WARN_AT: tuple[int, ...] = (30, 10)
# Grace between "budget exhausted" and masking the Steam binaries. Masking
# makes `steam -shutdown` a no-op, so Steam must be given a moment to close
# its games cleanly first — otherwise every single cutoff is a hard SIGTERM.
_SHUTDOWN_GRACE_SECONDS = 3.0
_SIGKILL_AFTER_SECONDS = 30.0
_DEMO_SIGKILL_AFTER_SECONDS = 10.0
# argv[0] basenames that tell us nothing: the real program is argv[1].
_INTERPRETERS = frozenset({"bash", "env", "java", "perl", "python", "python3", "sh"})
# An interpreter invocation needs at least `<interp> <script>` to name a program.
_MIN_ARGV_FOR_INTERPRETER = 2
_SECONDS_PER_MINUTE = 60
_MINUTES_PER_HOUR = 60
@dataclass
class PlaytimeState:
"""Per-gaming-day playtime accounting, persisted between ticks."""
schema_version: int = _SCHEMA_VERSION
day_key: str = ""
"""Gaming day this record covers, ``YYYY-MM-DD``, 06:00-shifted."""
seconds: float = 0.0
"""Qualifying seconds accrued during ``day_key``."""
last_tick_at: float = 0.0
"""Epoch seconds of the last accounting tick; ``0.0`` means never ticked."""
blocked_at: float = 0.0
"""Epoch seconds when the cutoff engaged; ``0.0`` means not blocked."""
warned_seconds: list[int] = field(default_factory=list)
"""Warning thresholds already fired during ``day_key``."""
def is_blocked(self) -> bool:
"""Whether the cutoff has engaged for this gaming day.
Deliberately a method rather than a field: ``save`` serialises
``self.__dict__``, so a derived field would be persisted and could
drift out of step with ``blocked_at``.
"""
return self.blocked_at > 0.0
@dataclass(frozen=True)
class PlaytimeRules:
"""Resolved budget policy for one tick.
Frozen and passed explicitly so that every decision function stays pure
and testable without touching ``Config`` or the clock.
"""
budget_seconds: float
warn_at: tuple[int, ...]
sigkill_after: float
count_launchers: bool
enforcement: bool
demo: bool
def rules_for(config: Config, *, demo: bool) -> PlaytimeRules:
"""Build the policy for this tick from *config*.
Demo mode changes the budget and the warning thresholds and nothing else —
in particular it uses the same qualifying-process predicate as production,
because a demo that exercises different logic proves nothing about it.
Args:
config: Loaded user configuration.
demo: Whether this is a short-budget demo run.
Returns:
The rules governing this tick.
"""
return PlaytimeRules(
budget_seconds=_DEMO_BUDGET_SECONDS
if demo
else float(config.daily_gaming_seconds),
warn_at=_DEMO_WARN_AT if demo else _WARN_AT,
sigkill_after=(_DEMO_SIGKILL_AFTER_SECONDS if demo else _SIGKILL_AFTER_SECONDS),
count_launchers=config.count_launcher_processes,
enforcement=config.playtime_enforcement,
demo=demo,
)
def gaming_day_key(now: datetime) -> str:
"""Return the ``YYYY-MM-DD`` gaming day containing *now*.
The boundary is 06:00 local, so 02:00 on the 5th belongs to the 4th.
Args:
now: Timezone-aware local timestamp.
Returns:
The gaming day key.
"""
return (now - timedelta(hours=_DAY_BOUNDARY_HOURS)).date().isoformat()
def state_path(*, demo: bool) -> Path:
"""Return the state file for a demo or production run.
Demo runs use a separate file so a demo can never consume or clobber the
real day's counter.
Args:
demo: Whether this is a demo run.
Returns:
Path to the state file.
"""
return PLAYTIME_DEMO_STATE_FILE if demo else PLAYTIME_STATE_FILE
def load_state(*, demo: bool) -> PlaytimeState | None:
"""Load persisted state, or ``None`` if it is absent or unusable.
``None`` deliberately covers "missing", "corrupt" and "written by a
different schema" alike: the caller's recovery path is the same for all
three, and treating an unreadable file as a fresh day is exactly the
reset-by-deletion the immutable flag exists to prevent.
Args:
demo: Whether this is a demo run.
Returns:
The stored state, or ``None`` if it could not be read.
"""
path = state_path(demo=demo)
if not path.exists():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
logger.warning("Playtime state at %s is unreadable; assuming tampered.", path)
return None
if not isinstance(data, dict) or data.get("schema_version") != _SCHEMA_VERSION:
logger.warning("Playtime state at %s has an unknown schema.", path)
return None
fields = PlaytimeState.__dataclass_fields__
return PlaytimeState(**{k: v for k, v in data.items() if k in fields})
def save_state(state: PlaytimeState, *, demo: bool) -> None:
"""Persist *state*, re-applying the immutable flag for production runs.
``_atomic_write`` finishes with ``rename(2)``, which fails ``EPERM`` against
an immutable destination — so clearing the flag first is mandatory, not
decorative. Demo state is left mutable: it carries no enforcement weight and
an immutable copy could not be deleted during cleanup, even by root.
Args:
state: State to write.
demo: Whether this is a demo run.
"""
path = state_path(demo=demo)
if not demo:
unlock_for_write(path)
_atomic_write(path, json.dumps(state.__dict__, indent=2) + "\n")
if not demo:
_try_set_immutable(path, immutable=True)
def get_pids_by_cmdline_names(names: frozenset[str]) -> dict[int, str]:
"""Scan ``/proc/*/cmdline`` for processes whose program name is in *names*.
Complements ``enforcer.get_pids_by_process_names``, which matches on
``comm`` and therefore cannot see interpreter-launched programs: the kernel
records ``/usr/bin/lutris`` as ``python3``. When ``argv[0]``'s basename is a
known interpreter this falls through to ``argv[1]``.
The daemon itself runs under ``python3``, so its own PID is skipped.
Args:
names: Program basenames to match.
Returns:
Mapping of PID to the matched name.
"""
own_pid = os.getpid()
found: dict[int, str] = {}
for entry in _PROC.iterdir():
if not entry.name.isdigit():
continue
pid = int(entry.name)
if pid == own_pid:
continue
matched = _match_cmdline(entry, names)
if matched is not None:
found[pid] = matched
return found
def _match_cmdline(entry: Path, names: frozenset[str]) -> str | None:
"""Return the name in *names* that *entry*'s cmdline runs, if any.
Args:
entry: A ``/proc/<pid>`` directory.
names: Program basenames to match.
Returns:
The matched name, or ``None``.
"""
try:
raw = (entry / "cmdline").read_bytes()
except (OSError, ValueError):
return None
argv = [
part for part in raw.decode("utf-8", errors="replace").split("\x00") if part
]
if not argv:
return None
first = Path(argv[0]).name
if first in names:
return first
if first not in _INTERPRETERS or len(argv) < _MIN_ARGV_FOR_INTERPRETER:
return None
second = Path(argv[1]).name
return second if second in names else None
def qualifying_pids(rules: PlaytimeRules) -> set[int]:
"""Return PIDs whose runtime counts against the daily budget.
Steam games are identified by the ``SteamAppId`` environment variable, using
the same ``!= 0`` predicate ``enforcer.enforce_allowed_game`` uses to exclude
the Steam client tree — browsing the store is not gaming.
Args:
rules: Policy for this tick.
Returns:
The set of qualifying PIDs.
"""
pids = {pid for pid, app_id in get_running_steam_game_pids().items() if app_id != 0}
if rules.count_launchers:
pids |= set(get_pids_by_process_names(LAUNCHER_PROCESS_NAMES))
pids |= set(get_pids_by_cmdline_names(LAUNCHER_PROCESS_NAMES))
return pids
def accumulate(
state: PlaytimeState,
*,
now: datetime,
qualifying: set[int],
interval: float,
) -> PlaytimeState:
"""Add this tick's elapsed gaming time to *state*.
Pure. Every argument is mandatory, including the clock — a defaulted ``now``
would add a branch that exists only to be covered.
The delta is clamped to ``_DELTA_CLAMP_FACTOR`` intervals so that a suspend,
a skipped tick or a forward NTP step cannot inflate the count, and floored
at zero so a backward step cannot refund time.
Args:
state: Current accounting state.
now: Timezone-aware local timestamp for this tick.
qualifying: PIDs currently counting against the budget.
interval: Nominal seconds between ticks.
Returns:
The updated state.
"""
stamp = now.timestamp()
if state.last_tick_at <= 0.0:
return replace(state, last_tick_at=stamp)
delta = stamp - state.last_tick_at
if delta <= 0.0 or not qualifying:
return replace(state, last_tick_at=stamp)
credited = min(delta, interval * _DELTA_CLAMP_FACTOR)
return replace(state, last_tick_at=stamp, seconds=state.seconds + credited)
def roll_over(state: PlaytimeState, *, day_key: str) -> PlaytimeState:
"""Reset *state* if the gaming day has changed.
Pure. ``last_tick_at`` carries across the boundary so the first tick of the
new day measures a sane delta rather than restarting from zero.
Args:
state: Current accounting state.
day_key: The gaming day *now* falls in.
Returns:
Either *state* unchanged, or a fresh record for *day_key*.
"""
if state.day_key == day_key:
return state
return PlaytimeState(day_key=day_key, last_tick_at=state.last_tick_at)
def pending_warning(state: PlaytimeState, rules: PlaytimeRules) -> int | None:
"""Return the largest un-fired warning threshold *state* has crossed.
Pure. Returning only the largest matters when a tick is skipped: crossing
two thresholds at once should warn once, not twice.
Args:
state: Current accounting state.
rules: Policy for this tick.
Returns:
The threshold in seconds-remaining, or ``None`` if none is due.
"""
remaining = rules.budget_seconds - state.seconds
for threshold in rules.warn_at:
if remaining <= threshold and threshold not in state.warned_seconds:
return threshold
return None
def notify_desktop_user(title: str, body: str) -> None:
"""Send a desktop notification into the real user's session.
``enforcer.send_notification`` runs ``notify-send`` as root with no
``DBUS_SESSION_BUS_ADDRESS``, which cannot reach the user's session bus from
a system service. This routes through the same ``sudo -u <user> env ...``
mechanism that ``library_hider`` uses to launch Steam.
Args:
title: Notification title.
body: Notification body.
"""
user = _resolve_desktop_user()
try:
_run_as_user(["notify-send", title, body, "--icon=dialog-warning"], user)
except (OSError, ValueError):
logger.debug("Could not send desktop notification.")
def playtime_tick(config: Config, *, interval: float, demo: bool = False) -> None:
"""Account for this tick's gaming time and enforce the daily budget.
@ -510,108 +157,3 @@ def _policy(
return _begin_cutoff(state, rules, now=now)
return _sustain_block(state, rules, now=now)
def _warn(state: PlaytimeState, rules: PlaytimeRules) -> PlaytimeState:
"""Fire the due warning, if any, and record that it fired.
Args:
state: Current accounting state.
rules: Policy for this tick.
Returns:
The updated state.
"""
threshold = pending_warning(state, rules)
if threshold is None:
return state
notify_desktop_user(
"Gaming time running out",
f"{_humanise(threshold)} of today's gaming budget left.",
)
return replace(state, warned_seconds=[*state.warned_seconds, threshold])
def _begin_cutoff(
state: PlaytimeState,
rules: PlaytimeRules,
*,
now: datetime,
) -> PlaytimeState:
"""Start the cutoff: ask Steam to close cleanly, then SIGTERM the games.
No mount happens on this tick. Masking the Steam binaries turns
``steam -shutdown`` into a no-op, which would cost a clean close — and
therefore a cloud-save flush — on every single cutoff.
Args:
state: Current accounting state.
rules: Policy for this tick.
now: Timezone-aware local timestamp.
Returns:
The updated state.
"""
logger.warning("Daily gaming budget exhausted; shutting Steam down.")
notify_desktop_user(
"Gaming time is up",
"Daily budget used up. Steam and games are shutting down. Unblocks at 06:00.",
)
request_steam_shutdown()
kill_gaming_processes(_kill_set(rules), force=False)
return replace(state, blocked_at=now.timestamp())
def _sustain_block(
state: PlaytimeState,
rules: PlaytimeRules,
*,
now: datetime,
) -> PlaytimeState:
"""Hold the block: mask the binaries once the grace has passed, keep killing.
Args:
state: Current accounting state.
rules: Policy for this tick.
now: Timezone-aware local timestamp.
Returns:
*state*, unchanged — upkeep mutates the system, not the record.
"""
elapsed = now.timestamp() - state.blocked_at
if elapsed >= _SHUTDOWN_GRACE_SECONDS:
reconcile(should_block=True)
kill_gaming_processes(_kill_set(rules), force=elapsed >= rules.sigkill_after)
return state
def _kill_set(rules: PlaytimeRules) -> set[int]:
"""Return every PID the cutoff should terminate.
Wider than :func:`qualifying_pids` on purpose. A Lutris-launched Wine game
has no ``SteamAppId`` and its ``comm`` is the game's own binary, so neither
matcher sees it — only walking down from the launcher does.
Args:
rules: Policy for this tick.
Returns:
PIDs to signal.
"""
return qualifying_pids(rules) | steam_and_launcher_pids()
def _humanise(seconds: int) -> str:
"""Render a warning threshold as a short human phrase.
Args:
seconds: Seconds remaining.
Returns:
A phrase such as ``"30 minutes"`` or ``"10 seconds"``.
"""
if seconds < _SECONDS_PER_MINUTE:
return f"{seconds} seconds"
minutes = seconds // _SECONDS_PER_MINUTE
return "1 hour" if minutes == _MINUTES_PER_HOUR else f"{minutes} minutes"

View File

@ -33,19 +33,12 @@ that at runtime.
from __future__ import annotations
import contextlib
import logging
import os
from pathlib import Path
import shutil
import signal
import subprocess
from steam_backlog_enforcer._total_block import (
LAUNCHER_PROCESS_NAMES,
STEAM_CLIENT_PROCESS_NAMES,
)
from steam_backlog_enforcer.enforcer import get_pids_by_process_names
from steam_backlog_enforcer._playtime_mountinfo import _mountpoints
from steam_backlog_enforcer._playtime_run import _run
logger = logging.getLogger(__name__)
@ -84,8 +77,6 @@ _MAX_UMOUNT_PASSES = 20
_MOUNTINFO_MIN_FIELDS = 5
_MOUNTPOINT_FIELD = 4
_STAT_PPID_INDEX = 1
_MAX_PROCESS_TREE_DEPTH = 32
_STUB_MODE = 0o755
@ -111,69 +102,6 @@ def block_targets() -> tuple[Path, ...]:
return BLOCK_TARGETS
def _run(cmd: list[str]) -> bool:
"""Run a privileged command, reporting success.
The single subprocess seam in this module, so tests can assert on exact
argv without ever executing ``mount``.
Args:
cmd: Argument vector to execute.
Returns:
True if the command exited zero.
"""
try:
result = subprocess.run(cmd, capture_output=True, check=False, timeout=15)
except (OSError, subprocess.SubprocessError):
logger.exception("Playtime block command failed: %s", cmd)
return False
if result.returncode != 0:
logger.warning("Playtime block command exited %d: %s", result.returncode, cmd)
return result.returncode == 0
def _unescape_mountinfo(field: str) -> str:
"""Decode the octal escapes the kernel writes into mountinfo paths.
Args:
field: A raw mountinfo field.
Returns:
The decoded field.
"""
return (
field.replace(r"\040", " ")
.replace(r"\011", "\t")
.replace(r"\012", "\n")
.replace(r"\134", "\\")
)
def _mountpoints(path: Path) -> set[Path]:
"""Parse *path* as mountinfo and return the mount points it lists.
Args:
path: A mountinfo file.
Returns:
Every mount point named in the file.
"""
try:
raw = path.read_text(encoding="utf-8")
except (OSError, ValueError):
logger.warning("Could not read mountinfo at %s.", path)
return set()
points: set[Path] = set()
for line in raw.splitlines():
fields = line.split(" ")
if len(fields) < _MOUNTINFO_MIN_FIELDS:
continue
points.add(Path(_unescape_mountinfo(fields[_MOUNTPOINT_FIELD])))
return points
def mounted_targets() -> set[Path]:
"""Return the block targets currently masked by a mount.
@ -298,152 +226,6 @@ def reconcile(*, should_block: bool) -> tuple[list[Path], list[Path]]:
return masked, []
def request_steam_shutdown() -> None:
"""Ask Steam to close cleanly, without waiting for it.
``library_hider._shutdown_steam`` polls for up to 30 seconds, which would
stall the 3-second enforce loop for ten ticks. The cutoff sequence gives
Steam its grace period across ticks instead.
"""
steam = shutil.which("steam")
if steam is None:
logger.info("Steam binary not on PATH; skipping clean shutdown.")
return
_run([steam, "-shutdown"])
def steam_and_launcher_pids() -> set[int]:
"""Return PIDs of the Steam client and every known game launcher.
Returns:
The launcher and client PIDs.
"""
names = STEAM_CLIENT_PROCESS_NAMES | LAUNCHER_PROCESS_NAMES
return set(get_pids_by_process_names(names))
def _read_ppid(pid: int) -> int | None:
"""Return the parent PID of *pid*, or ``None`` if it cannot be read.
``/proc/<pid>/stat`` embeds ``comm`` in parentheses and ``comm`` may contain
spaces and parentheses, so the fields after it are found by splitting on the
last ``") "`` rather than by whitespace position.
Args:
pid: Process to inspect.
Returns:
The parent PID, or ``None``.
"""
try:
raw = (_PROC / str(pid) / "stat").read_text(encoding="utf-8")
except (OSError, ValueError):
return None
_, _, rest = raw.rpartition(") ")
fields = rest.split()
if len(fields) <= _STAT_PPID_INDEX:
return None
try:
return int(fields[_STAT_PPID_INDEX])
except ValueError:
return None
def _child_map() -> dict[int, list[int]]:
"""Build a parent-PID to child-PIDs map from ``/proc``.
Returns:
Mapping of parent PID to its direct children.
"""
children: dict[int, list[int]] = {}
try:
entries = list(_PROC.iterdir())
except OSError:
return children
for entry in entries:
if not entry.name.isdigit():
continue
pid = int(entry.name)
ppid = _read_ppid(pid)
if ppid is not None:
children.setdefault(ppid, []).append(pid)
return children
def descendant_pids(roots: set[int]) -> set[int]:
"""Return every process descended from *roots*.
A Lutris-launched Wine game carries no ``SteamAppId`` and its ``comm`` is
the game's own binary, so neither of the budget matchers can see it. Walking
down from the launcher is the only thing that does.
The daemon's own process and its ancestors are excluded, so a misidentified
root cannot make the enforcer kill itself.
Args:
roots: Processes to walk down from.
Returns:
The transitive descendants, excluding *roots* themselves.
"""
children = _child_map()
protected = _own_process_chain()
found: set[int] = set()
frontier = [pid for pid in roots if pid not in protected]
for _ in range(_MAX_PROCESS_TREE_DEPTH):
if not frontier:
break
nxt: list[int] = []
for pid in frontier:
for child in children.get(pid, []):
if child in found or child in protected:
continue
found.add(child)
nxt.append(child)
frontier = nxt
return found
def _own_process_chain() -> set[int]:
"""Return this process and its ancestors.
Returns:
PIDs that must never be signalled.
"""
chain: set[int] = set()
pid: int | None = os.getpid()
for _ in range(_MAX_PROCESS_TREE_DEPTH):
if pid is None or pid <= 0 or pid in chain:
break
chain.add(pid)
pid = _read_ppid(pid)
return chain
def kill_gaming_processes(pids: set[int], *, force: bool) -> list[int]:
"""Signal every process in *pids*, plus everything descended from them.
Args:
pids: Processes to terminate.
force: Send ``SIGKILL`` instead of ``SIGTERM``.
Returns:
The PIDs actually signalled.
"""
protected = _own_process_chain()
targets = (pids | descendant_pids(pids)) - protected
sig = signal.SIGKILL if force else signal.SIGTERM
signalled: list[int] = []
for pid in sorted(targets):
with contextlib.suppress(ProcessLookupError, PermissionError):
os.kill(pid, sig)
signalled.append(pid)
return signalled
def _mount_bin() -> str:
"""Return the ``mount`` executable path.

View File

@ -0,0 +1,98 @@
"""Pure state transitions for the daily playtime budget.
Separated from persistence: nothing here touches the disk or the clock
beyond what it is handed, which is what makes the budget arithmetic
straightforward to test.
"""
from __future__ import annotations
from dataclasses import replace
import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._playtime_state import (
_DELTA_CLAMP_FACTOR,
PlaytimeRules,
PlaytimeState,
)
if TYPE_CHECKING:
from datetime import datetime
logger = logging.getLogger(__name__)
def accumulate(
state: PlaytimeState,
*,
now: datetime,
qualifying: set[int],
interval: float,
) -> PlaytimeState:
"""Add this tick's elapsed gaming time to *state*.
Pure. Every argument is mandatory, including the clock — a defaulted ``now``
would add a branch that exists only to be covered.
The delta is clamped to ``_DELTA_CLAMP_FACTOR`` intervals so that a suspend,
a skipped tick or a forward NTP step cannot inflate the count, and floored
at zero so a backward step cannot refund time.
Args:
state: Current accounting state.
now: Timezone-aware local timestamp for this tick.
qualifying: PIDs currently counting against the budget.
interval: Nominal seconds between ticks.
Returns:
The updated state.
"""
stamp = now.timestamp()
if state.last_tick_at <= 0.0:
return replace(state, last_tick_at=stamp)
delta = stamp - state.last_tick_at
if delta <= 0.0 or not qualifying:
return replace(state, last_tick_at=stamp)
credited = min(delta, interval * _DELTA_CLAMP_FACTOR)
return replace(state, last_tick_at=stamp, seconds=state.seconds + credited)
def roll_over(state: PlaytimeState, *, day_key: str) -> PlaytimeState:
"""Reset *state* if the gaming day has changed.
Pure. ``last_tick_at`` carries across the boundary so the first tick of the
new day measures a sane delta rather than restarting from zero.
Args:
state: Current accounting state.
day_key: The gaming day *now* falls in.
Returns:
Either *state* unchanged, or a fresh record for *day_key*.
"""
if state.day_key == day_key:
return state
return PlaytimeState(day_key=day_key, last_tick_at=state.last_tick_at)
def pending_warning(state: PlaytimeState, rules: PlaytimeRules) -> int | None:
"""Return the largest un-fired warning threshold *state* has crossed.
Pure. Returning only the largest matters when a tick is skipped: crossing
two thresholds at once should warn once, not twice.
Args:
state: Current accounting state.
rules: Policy for this tick.
Returns:
The threshold in seconds-remaining, or ``None`` if none is due.
"""
remaining = rules.budget_seconds - state.seconds
for threshold in rules.warn_at:
if remaining <= threshold and threshold not in state.warned_seconds:
return threshold
return None

View File

@ -0,0 +1,125 @@
"""Warning, cutoff and kill steps of the playtime policy.
The escalation ladder once a budget is spent: warn, ask Steam to shut down
cleanly, then mask its binaries and SIGTERM/SIGKILL what is still running.
The grace between shutdown and masking exists because masking makes
``steam -shutdown`` itself a no-op.
"""
from __future__ import annotations
from dataclasses import replace
import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._playtime_block import (
reconcile,
)
from steam_backlog_enforcer._playtime_budget import pending_warning
from steam_backlog_enforcer._playtime_kill import (
kill_gaming_processes,
request_steam_shutdown,
steam_and_launcher_pids,
)
from steam_backlog_enforcer._playtime_notify import _humanise, notify_desktop_user
from steam_backlog_enforcer._playtime_procs import qualifying_pids
from steam_backlog_enforcer._playtime_state import (
_SHUTDOWN_GRACE_SECONDS,
PlaytimeRules,
PlaytimeState,
)
if TYPE_CHECKING:
from datetime import datetime
logger = logging.getLogger(__name__)
def _warn(state: PlaytimeState, rules: PlaytimeRules) -> PlaytimeState:
"""Fire the due warning, if any, and record that it fired.
Args:
state: Current accounting state.
rules: Policy for this tick.
Returns:
The updated state.
"""
threshold = pending_warning(state, rules)
if threshold is None:
return state
notify_desktop_user(
"Gaming time running out",
f"{_humanise(threshold)} of today's gaming budget left.",
)
return replace(state, warned_seconds=[*state.warned_seconds, threshold])
def _begin_cutoff(
state: PlaytimeState,
rules: PlaytimeRules,
*,
now: datetime,
) -> PlaytimeState:
"""Start the cutoff: ask Steam to close cleanly, then SIGTERM the games.
No mount happens on this tick. Masking the Steam binaries turns
``steam -shutdown`` into a no-op, which would cost a clean close — and
therefore a cloud-save flush — on every single cutoff.
Args:
state: Current accounting state.
rules: Policy for this tick.
now: Timezone-aware local timestamp.
Returns:
The updated state.
"""
logger.warning("Daily gaming budget exhausted; shutting Steam down.")
notify_desktop_user(
"Gaming time is up",
"Daily budget used up. Steam and games are shutting down. Unblocks at 06:00.",
)
request_steam_shutdown()
kill_gaming_processes(_kill_set(rules), force=False)
return replace(state, blocked_at=now.timestamp())
def _sustain_block(
state: PlaytimeState,
rules: PlaytimeRules,
*,
now: datetime,
) -> PlaytimeState:
"""Hold the block: mask the binaries once the grace has passed, keep killing.
Args:
state: Current accounting state.
rules: Policy for this tick.
now: Timezone-aware local timestamp.
Returns:
*state*, unchanged — upkeep mutates the system, not the record.
"""
elapsed = now.timestamp() - state.blocked_at
if elapsed >= _SHUTDOWN_GRACE_SECONDS:
reconcile(should_block=True)
kill_gaming_processes(_kill_set(rules), force=elapsed >= rules.sigkill_after)
return state
def _kill_set(rules: PlaytimeRules) -> set[int]:
"""Return every PID the cutoff should terminate.
Wider than :func:`qualifying_pids` on purpose. A Lutris-launched Wine game
has no ``SteamAppId`` and its ``comm`` is the game's own binary, so neither
matcher sees it — only walking down from the launcher does.
Args:
rules: Policy for this tick.
Returns:
PIDs to signal.
"""
return qualifying_pids(rules) | steam_and_launcher_pids()

View File

@ -0,0 +1,176 @@
"""Finding and stopping the processes a playtime cutoff must end.
Killing Steam's own PIDs is not enough: a running game is a *descendant* of
the client, so the tree is walked from the launcher roots downwards. The
enforcer's own process chain is excluded, since it is itself a child of the
same session on a desktop install.
"""
from __future__ import annotations
import contextlib
import logging
import os
from pathlib import Path
import shutil
import signal
from steam_backlog_enforcer._playtime_run import _run
from steam_backlog_enforcer._total_block_launchers import (
LAUNCHER_PROCESS_NAMES,
STEAM_CLIENT_PROCESS_NAMES,
)
from steam_backlog_enforcer.enforcer import get_pids_by_process_names
logger = logging.getLogger(__name__)
_PROC = Path("/proc")
_STAT_PPID_INDEX = 1
_MAX_PROCESS_TREE_DEPTH = 32
def request_steam_shutdown() -> None:
"""Ask Steam to close cleanly, without waiting for it.
``library_hider._shutdown_steam`` polls for up to 30 seconds, which would
stall the 3-second enforce loop for ten ticks. The cutoff sequence gives
Steam its grace period across ticks instead.
"""
steam = shutil.which("steam")
if steam is None:
logger.info("Steam binary not on PATH; skipping clean shutdown.")
return
_run([steam, "-shutdown"])
def steam_and_launcher_pids() -> set[int]:
"""Return PIDs of the Steam client and every known game launcher.
Returns:
The launcher and client PIDs.
"""
names = STEAM_CLIENT_PROCESS_NAMES | LAUNCHER_PROCESS_NAMES
return set(get_pids_by_process_names(names))
def _read_ppid(pid: int) -> int | None:
"""Return the parent PID of *pid*, or ``None`` if it cannot be read.
``/proc/<pid>/stat`` embeds ``comm`` in parentheses and ``comm`` may contain
spaces and parentheses, so the fields after it are found by splitting on the
last ``") "`` rather than by whitespace position.
Args:
pid: Process to inspect.
Returns:
The parent PID, or ``None``.
"""
try:
raw = (_PROC / str(pid) / "stat").read_text(encoding="utf-8")
except (OSError, ValueError):
return None
_, _, rest = raw.rpartition(") ")
fields = rest.split()
if len(fields) <= _STAT_PPID_INDEX:
return None
try:
return int(fields[_STAT_PPID_INDEX])
except ValueError:
return None
def _child_map() -> dict[int, list[int]]:
"""Build a parent-PID to child-PIDs map from ``/proc``.
Returns:
Mapping of parent PID to its direct children.
"""
children: dict[int, list[int]] = {}
try:
entries = list(_PROC.iterdir())
except OSError:
return children
for entry in entries:
if not entry.name.isdigit():
continue
pid = int(entry.name)
ppid = _read_ppid(pid)
if ppid is not None:
children.setdefault(ppid, []).append(pid)
return children
def descendant_pids(roots: set[int]) -> set[int]:
"""Return every process descended from *roots*.
A Lutris-launched Wine game carries no ``SteamAppId`` and its ``comm`` is
the game's own binary, so neither of the budget matchers can see it. Walking
down from the launcher is the only thing that does.
The daemon's own process and its ancestors are excluded, so a misidentified
root cannot make the enforcer kill itself.
Args:
roots: Processes to walk down from.
Returns:
The transitive descendants, excluding *roots* themselves.
"""
children = _child_map()
protected = _own_process_chain()
found: set[int] = set()
frontier = [pid for pid in roots if pid not in protected]
for _ in range(_MAX_PROCESS_TREE_DEPTH):
if not frontier:
break
nxt: list[int] = []
for pid in frontier:
for child in children.get(pid, []):
if child in found or child in protected:
continue
found.add(child)
nxt.append(child)
frontier = nxt
return found
def _own_process_chain() -> set[int]:
"""Return this process and its ancestors.
Returns:
PIDs that must never be signalled.
"""
chain: set[int] = set()
pid: int | None = os.getpid()
for _ in range(_MAX_PROCESS_TREE_DEPTH):
if pid is None or pid <= 0 or pid in chain:
break
chain.add(pid)
pid = _read_ppid(pid)
return chain
def kill_gaming_processes(pids: set[int], *, force: bool) -> list[int]:
"""Signal every process in *pids*, plus everything descended from them.
Args:
pids: Processes to terminate.
force: Send ``SIGKILL`` instead of ``SIGTERM``.
Returns:
The PIDs actually signalled.
"""
protected = _own_process_chain()
targets = (pids | descendant_pids(pids)) - protected
sig = signal.SIGKILL if force else signal.SIGTERM
signalled: list[int] = []
for pid in sorted(targets):
with contextlib.suppress(ProcessLookupError, PermissionError):
os.kill(pid, sig)
signalled.append(pid)
return signalled

View File

@ -0,0 +1,59 @@
"""Reading the kernel's mount table to see which blocks are live.
``/proc/self/mountinfo`` is the source of truth rather than our own record of
what we mounted: a bind mount can survive a crash or be removed by hand, and
the enforcer has to reconcile against reality on every tick.
"""
from __future__ import annotations
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
_INIT_MOUNTINFO_PATH = Path("/proc/1/mountinfo")
MOUNTINFO_PATH = Path("/proc/self/mountinfo")
_MOUNTINFO_MIN_FIELDS = 5
_MOUNTPOINT_FIELD = 4
def _unescape_mountinfo(field: str) -> str:
"""Decode the octal escapes the kernel writes into mountinfo paths.
Args:
field: A raw mountinfo field.
Returns:
The decoded field.
"""
return (
field.replace(r"\040", " ")
.replace(r"\011", "\t")
.replace(r"\012", "\n")
.replace(r"\134", "\\")
)
def _mountpoints(path: Path) -> set[Path]:
"""Parse *path* as mountinfo and return the mount points it lists.
Args:
path: A mountinfo file.
Returns:
Every mount point named in the file.
"""
try:
raw = path.read_text(encoding="utf-8")
except (OSError, ValueError):
logger.warning("Could not read mountinfo at %s.", path)
return set()
points: set[Path] = set()
for line in raw.splitlines():
fields = line.split(" ")
if len(fields) < _MOUNTINFO_MIN_FIELDS:
continue
points.add(Path(_unescape_mountinfo(fields[_MOUNTPOINT_FIELD])))
return points

View File

@ -0,0 +1,51 @@
"""Desktop notifications for the playtime budget, and time formatting.
Notifications must reach the logged-in desktop session, not the root systemd
context the enforcer runs in, which is why they are dispatched through
``_run_as_user``.
"""
from __future__ import annotations
import logging
from steam_backlog_enforcer._steam_launch import _resolve_desktop_user
from steam_backlog_enforcer._steam_process import _run_as_user
logger = logging.getLogger(__name__)
_SECONDS_PER_MINUTE = 60
_MINUTES_PER_HOUR = 60
def notify_desktop_user(title: str, body: str) -> None:
"""Send a desktop notification into the real user's session.
``enforcer.send_notification`` now drops privileges too, so this differs
only in delivery: it is fire-and-forget (``Popen``) where that one waits up
to 5s, which matters on the playtime-cutoff path.
Args:
title: Notification title.
body: Notification body.
"""
user = _resolve_desktop_user()
try:
_run_as_user(["notify-send", title, body, "--icon=dialog-warning"], user)
except (OSError, ValueError):
logger.debug("Could not send desktop notification.")
def _humanise(seconds: int) -> str:
"""Render a warning threshold as a short human phrase.
Args:
seconds: Seconds remaining.
Returns:
A phrase such as ``"30 minutes"`` or ``"10 seconds"``.
"""
if seconds < _SECONDS_PER_MINUTE:
return f"{seconds} seconds"
minutes = seconds // _SECONDS_PER_MINUTE
return "1 hour" if minutes == _MINUTES_PER_HOUR else f"{minutes} minutes"

View File

@ -0,0 +1,111 @@
"""Identifying gaming processes by their /proc cmdline.
Process-name matching alone misses launchers run through an interpreter
(``lutris`` is a Python script; several Minecraft launchers are ``java -jar``),
so this reads argv and looks past the interpreter to the real program.
"""
from __future__ import annotations
import os
from pathlib import Path
from typing import TYPE_CHECKING
from steam_backlog_enforcer._total_block_launchers import LAUNCHER_PROCESS_NAMES
from steam_backlog_enforcer.enforcer import (
get_pids_by_process_names,
get_running_steam_game_pids,
)
if TYPE_CHECKING:
from steam_backlog_enforcer._playtime_state import PlaytimeRules
_PROC = Path("/proc")
# argv[0] basenames that tell us nothing: the real program is argv[1].
_INTERPRETERS = frozenset({"bash", "env", "java", "perl", "python", "python3", "sh"})
# An interpreter invocation needs at least `<interp> <script>` to name a program.
_MIN_ARGV_FOR_INTERPRETER = 2
def get_pids_by_cmdline_names(names: frozenset[str]) -> dict[int, str]:
"""Scan ``/proc/*/cmdline`` for processes whose program name is in *names*.
Complements ``enforcer.get_pids_by_process_names``, which matches on
``comm`` and therefore cannot see interpreter-launched programs: the kernel
records ``/usr/bin/lutris`` as ``python3``. When ``argv[0]``'s basename is a
known interpreter this falls through to ``argv[1]``.
The daemon itself runs under ``python3``, so its own PID is skipped.
Args:
names: Program basenames to match.
Returns:
Mapping of PID to the matched name.
"""
own_pid = os.getpid()
found: dict[int, str] = {}
for entry in _PROC.iterdir():
if not entry.name.isdigit():
continue
pid = int(entry.name)
if pid == own_pid:
continue
matched = _match_cmdline(entry, names)
if matched is not None:
found[pid] = matched
return found
def _match_cmdline(entry: Path, names: frozenset[str]) -> str | None:
"""Return the name in *names* that *entry*'s cmdline runs, if any.
Args:
entry: A ``/proc/<pid>`` directory.
names: Program basenames to match.
Returns:
The matched name, or ``None``.
"""
try:
raw = (entry / "cmdline").read_bytes()
except (OSError, ValueError):
return None
argv = [
part for part in raw.decode("utf-8", errors="replace").split("\x00") if part
]
if not argv:
return None
first = Path(argv[0]).name
if first in names:
return first
if first not in _INTERPRETERS or len(argv) < _MIN_ARGV_FOR_INTERPRETER:
return None
second = Path(argv[1]).name
return second if second in names else None
def qualifying_pids(rules: PlaytimeRules) -> set[int]:
"""Return PIDs whose runtime counts against the daily budget.
Steam games are identified by the ``SteamAppId`` environment variable, using
the same ``!= 0`` predicate ``enforcer.enforce_allowed_game`` uses to exclude
the Steam client tree — browsing the store is not gaming.
Args:
rules: Policy for this tick.
Returns:
The set of qualifying PIDs.
"""
pids = {pid for pid, app_id in get_running_steam_game_pids().items() if app_id != 0}
if rules.count_launchers:
pids |= set(get_pids_by_process_names(LAUNCHER_PROCESS_NAMES))
pids |= set(get_pids_by_cmdline_names(LAUNCHER_PROCESS_NAMES))
return pids

View File

@ -0,0 +1,34 @@
"""Running the privileged commands a playtime block needs.
One helper, shared by the mount side and the process-kill side, so the
"log the failure and carry on" policy is written once.
"""
from __future__ import annotations
import logging
import subprocess
logger = logging.getLogger(__name__)
def _run(cmd: list[str]) -> bool:
"""Run a privileged command, reporting success.
The single subprocess seam in this module, so tests can assert on exact
argv without ever executing ``mount``.
Args:
cmd: Argument vector to execute.
Returns:
True if the command exited zero.
"""
try:
result = subprocess.run(cmd, capture_output=True, check=False, timeout=15)
except (OSError, subprocess.SubprocessError):
logger.exception("Playtime block command failed: %s", cmd)
return False
if result.returncode != 0:
logger.warning("Playtime block command exited %d: %s", result.returncode, cmd)
return result.returncode == 0

View File

@ -0,0 +1,196 @@
"""The daily playtime budget: its state, its rules, and its persistence.
A gaming "day" runs 06:00-05:59 local, so late-night sessions count against
the day they started in. State is written atomically and re-read every tick,
which is what lets the enforcer survive a restart mid-session.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timedelta
import json
import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._whitelist import _try_set_immutable, unlock_for_write
from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
if TYPE_CHECKING:
from pathlib import Path
from steam_backlog_enforcer.config import Config
logger = logging.getLogger(__name__)
PLAYTIME_STATE_FILE = CONFIG_DIR / "playtime_state.json"
PLAYTIME_DEMO_STATE_FILE = CONFIG_DIR / "playtime_demo_state.json"
_SCHEMA_VERSION = 1
# The gaming day starts here, local time. 05:59 belongs to the previous day.
_DAY_BOUNDARY_HOURS = 6
# Each tick's measured delta is capped at this many tick intervals. Two is the
# smallest value that tolerates one skipped tick without inflating the count.
_DELTA_CLAMP_FACTOR = 2.0
_DEFAULT_BUDGET_SECONDS = 8 * 3600.0
_DEMO_BUDGET_SECONDS = 60.0
# Seconds remaining at which to warn, descending.
_WARN_AT: tuple[int, ...] = (3600, 1800, 600, 300)
_DEMO_WARN_AT: tuple[int, ...] = (30, 10)
# Grace between "budget exhausted" and masking the Steam binaries. Masking
# makes `steam -shutdown` a no-op, so Steam must be given a moment to close
# its games cleanly first — otherwise every single cutoff is a hard SIGTERM.
_SHUTDOWN_GRACE_SECONDS = 3.0
_SIGKILL_AFTER_SECONDS = 30.0
_DEMO_SIGKILL_AFTER_SECONDS = 10.0
@dataclass
class PlaytimeState:
"""Per-gaming-day playtime accounting, persisted between ticks."""
schema_version: int = _SCHEMA_VERSION
day_key: str = ""
"""Gaming day this record covers, ``YYYY-MM-DD``, 06:00-shifted."""
seconds: float = 0.0
"""Qualifying seconds accrued during ``day_key``."""
last_tick_at: float = 0.0
"""Epoch seconds of the last accounting tick; ``0.0`` means never ticked."""
blocked_at: float = 0.0
"""Epoch seconds when the cutoff engaged; ``0.0`` means not blocked."""
warned_seconds: list[int] = field(default_factory=list)
"""Warning thresholds already fired during ``day_key``."""
def is_blocked(self) -> bool:
"""Whether the cutoff has engaged for this gaming day.
Deliberately a method rather than a field: ``save`` serialises
``self.__dict__``, so a derived field would be persisted and could
drift out of step with ``blocked_at``.
"""
return self.blocked_at > 0.0
@dataclass(frozen=True)
class PlaytimeRules:
"""Resolved budget policy for one tick.
Frozen and passed explicitly so that every decision function stays pure
and testable without touching ``Config`` or the clock.
"""
budget_seconds: float
warn_at: tuple[int, ...]
sigkill_after: float
count_launchers: bool
enforcement: bool
demo: bool
def rules_for(config: Config, *, demo: bool) -> PlaytimeRules:
"""Build the policy for this tick from *config*.
Demo mode changes the budget and the warning thresholds and nothing else —
in particular it uses the same qualifying-process predicate as production,
because a demo that exercises different logic proves nothing about it.
Args:
config: Loaded user configuration.
demo: Whether this is a short-budget demo run.
Returns:
The rules governing this tick.
"""
return PlaytimeRules(
budget_seconds=_DEMO_BUDGET_SECONDS
if demo
else float(config.daily_gaming_seconds),
warn_at=_DEMO_WARN_AT if demo else _WARN_AT,
sigkill_after=(_DEMO_SIGKILL_AFTER_SECONDS if demo else _SIGKILL_AFTER_SECONDS),
count_launchers=config.count_launcher_processes,
enforcement=config.playtime_enforcement,
demo=demo,
)
def gaming_day_key(now: datetime) -> str:
"""Return the ``YYYY-MM-DD`` gaming day containing *now*.
The boundary is 06:00 local, so 02:00 on the 5th belongs to the 4th.
Args:
now: Timezone-aware local timestamp.
Returns:
The gaming day key.
"""
return (now - timedelta(hours=_DAY_BOUNDARY_HOURS)).date().isoformat()
def state_path(*, demo: bool) -> Path:
"""Return the state file for a demo or production run.
Demo runs use a separate file so a demo can never consume or clobber the
real day's counter.
Args:
demo: Whether this is a demo run.
Returns:
Path to the state file.
"""
return PLAYTIME_DEMO_STATE_FILE if demo else PLAYTIME_STATE_FILE
def load_state(*, demo: bool) -> PlaytimeState | None:
"""Load persisted state, or ``None`` if it is absent or unusable.
``None`` deliberately covers "missing", "corrupt" and "written by a
different schema" alike: the caller's recovery path is the same for all
three, and treating an unreadable file as a fresh day is exactly the
reset-by-deletion the immutable flag exists to prevent.
Args:
demo: Whether this is a demo run.
Returns:
The stored state, or ``None`` if it could not be read.
"""
path = state_path(demo=demo)
if not path.exists():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
logger.warning("Playtime state at %s is unreadable; assuming tampered.", path)
return None
if not isinstance(data, dict) or data.get("schema_version") != _SCHEMA_VERSION:
logger.warning("Playtime state at %s has an unknown schema.", path)
return None
fields = PlaytimeState.__dataclass_fields__
return PlaytimeState(**{k: v for k, v in data.items() if k in fields})
def save_state(state: PlaytimeState, *, demo: bool) -> None:
"""Persist *state*, re-applying the immutable flag for production runs.
``_atomic_write`` finishes with ``rename(2)``, which fails ``EPERM`` against
an immutable destination — so clearing the flag first is mandatory, not
decorative. Demo state is left mutable: it carries no enforcement weight and
an immutable copy could not be deleted during cleanup, even by root.
Args:
state: State to write.
demo: Whether this is a demo run.
"""
path = state_path(demo=demo)
if not demo:
unlock_for_write(path)
_atomic_write(path, json.dumps(state.__dict__, indent=2) + "\n")
if not demo:
_try_set_immutable(path, immutable=True)

View File

@ -0,0 +1,108 @@
"""Backfilling and reporting HLTB poll confidence for finished games.
Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._echo import _echo
from steam_backlog_enforcer._hltb_types import (
load_hltb_cache,
load_hltb_polls_cache,
save_hltb_cache,
)
from steam_backlog_enforcer.hltb import fetch_hltb_confidence_cached
if TYPE_CHECKING:
from steam_backlog_enforcer._steam_models import GameInfo
from steam_backlog_enforcer.config import State
logger = logging.getLogger(__name__)
def _backfill_polls_for_finished(
state: State,
games: list[GameInfo],
) -> dict[int, int]:
"""Lazily fetch poll counts for already-finished games missing them.
Reads the polls cache, identifies finished games whose poll count is
still ``0`` (typically because the cache predates the polls schema),
and triggers a one-shot HLTB search to backfill them. Returns the
refreshed polls cache.
"""
polls_cache = load_hltb_polls_cache()
name_by_id = {g.app_id: g.name for g in games}
missing = [
(aid, name_by_id[aid])
for aid in state.finished_app_ids
if aid in name_by_id and polls_cache.get(aid, 0) == 0
]
if not missing:
return polls_cache
logger.info(
"Backfilling HLTB poll counts for %d already-finished games...",
len(missing),
)
# Force a fresh search by removing the hours entries we want to refetch.
# (fetch_hltb_times_cached skips entries already in the hours cache.)
cache = load_hltb_cache()
preserved_hours = {aid: cache[aid] for aid, _ in missing if aid in cache}
for aid, _name in missing:
cache.pop(aid, None)
save_hltb_cache(cache, polls_cache)
fetch_hltb_confidence_cached(missing)
# Restore any previously-known hours that the refetch may have replaced
# with a worse match (we trust prior leisure+dlc estimates).
refreshed_hours = load_hltb_cache()
refreshed_polls = load_hltb_polls_cache()
for aid, prior_hours in preserved_hours.items():
if prior_hours > 0 and refreshed_hours.get(aid, -1) <= 0:
refreshed_hours[aid] = prior_hours
save_hltb_cache(refreshed_hours, refreshed_polls)
return refreshed_polls
def _report_poll_confidence(
chosen: GameInfo,
games: list[GameInfo],
state: State,
) -> None:
"""Print HLTB poll-count confidence info for the just-assigned game.
Shows the chosen game's ``comp_100_count`` (number of polled
completionist times on HowLongToBeat) and the historical minimum
among the user's previously-finished games. Marks a new historical
low so the user can be skeptical of unreliable estimates.
"""
polls_cache = _backfill_polls_for_finished(state, games)
chosen_polls = polls_cache.get(chosen.app_id, chosen.comp_100_count)
chosen.comp_100_count = chosen_polls
finished_polls = [
(polls_cache[aid], aid)
for aid in state.finished_app_ids
if polls_cache.get(aid, 0) > 0
]
if not finished_polls:
_echo(f" HLTB confidence: {chosen_polls} polled completionist times")
return
min_polls, min_aid = min(finished_polls)
name_by_id = {g.app_id: g.name for g in games}
min_name = name_by_id.get(min_aid, f"AppID={min_aid}")
warning = ""
if 0 < chosen_polls < min_polls:
warning = " ⚠ NEW LOW — estimate may be unreliable"
elif chosen_polls == 0:
warning = " ⚠ no polls recorded — estimate may be unreliable"
_echo(f" HLTB confidence: {chosen_polls} polled completionist times{warning}")
_echo(f" Historical min among finished: {min_polls} ({min_name})")

View File

@ -0,0 +1,44 @@
"""Steam AppIDs that must never be uninstalled.
Runtimes and compatibility tools, not games: removing one silently breaks
every Proton title. Split out of :mod:`steam_backlog_enforcer.game_install`
to keep that module under the 250-line cap; this is data, not logic.
"""
from __future__ import annotations
PROTECTED_APP_IDS = {
# Steam runtimes and tooling (never uninstall these)
228980, # Steamworks Common Redistributables
1070560, # Steam Linux Runtime 1.0 (scout)
1391110, # Steam Linux Runtime 2.0 (soldier)
1628350, # Steam Linux Runtime 3.0 (sniper)
4183110, # Steam Linux Runtime 4.0
4185400, # Steam Linux Runtime 4.0 - Arm64
961940, # Steam Linux Runtime (legacy)
4690330, # Legacy Steam Runtime
613220, # Steam 360 Video Player
250820, # SteamVR
1007, # Steamworks SDK Redist
# Proton versions (never uninstall these)
858280, # Proton 3.7 (Beta)
930400, # Proton 3.16 (Beta)
1054830, # Proton 4.2
1113280, # Proton 4.11
1245040, # Proton 5.0
1420170, # Proton 5.13
1580130, # Proton 6.3
1887720, # Proton 7.0
2230260, # Proton 7.0 (alt)
2348590, # Proton 8.0
2805730, # Proton 9.0
3201940, # Proton 9.0 (alt)
3658110, # Proton 10.0
4628710, # Proton 11.0
4628740, # Proton 11.0 (ARM64)
2180100, # Proton Hotfix
1493710, # Proton Experimental
1161040, # Proton BattlEye Runtime
1007020, # Proton EasyAntiCheat Runtime
1826330, # Proton EasyAntiCheat Runtime
}

View File

@ -0,0 +1,142 @@
"""Interactive pick prompt and assignment of the chosen game.
Split out of :mod:`steam_backlog_enforcer.scanning` to keep both files under
the 250-line cap. Leaf helpers: nothing here calls back into ``scanning``.
"""
from __future__ import annotations
from datetime import datetime, timezone
import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._scanning_candidates import (
_pick_next_shortest_candidate,
_sort_key,
)
from steam_backlog_enforcer._scanning_confidence import (
_apply_cached_confidence_to_candidates,
_report_poll_confidence,
)
from steam_backlog_enforcer.game_install import (
_echo,
install_game,
is_game_installed,
uninstall_other_games,
)
if TYPE_CHECKING:
from collections.abc import Callable
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.steam_api import GameInfo
logger = logging.getLogger(__name__)
_NO_CONF_MSG = (
"\nNo assignable games found "
"(HLTB confidence thresholds: comp_100 polls>=3, "
"count_comp>=15, sum>=18)."
)
def _prompt_user_pick(qualified: list[GameInfo]) -> int:
"""Present numbered list, return 0-based index of user's choice."""
for i, g in enumerate(qualified, 1):
hours_str = (
f" (~{g.completionist_hours:.1f}h)" if g.completionist_hours > 0 else ""
)
_echo(f" {i}. {g.name} (AppID={g.app_id}){hours_str}")
while True:
raw = input("Select game number: ")
try:
idx = int(raw)
except ValueError:
_echo(f"Invalid input: {raw!r}")
continue
if idx < 1 or idx > len(qualified):
_echo(f"Out of range: {idx}")
continue
return idx - 1
def _assign_chosen_game(
chosen: GameInfo,
games: list[GameInfo],
state: State,
config: Config,
) -> None:
"""Save assignment, announce it, and handle install/uninstall."""
state.current_app_id = chosen.app_id
state.current_game_name = chosen.name
if not state.enforcement_started_at:
state.enforcement_started_at = datetime.now(timezone.utc).isoformat()
state.save()
hours_str = (
f" (~{chosen.completionist_hours:.1f}h leisure+dlc)"
if chosen.completionist_hours > 0
else ""
)
_echo(f"\n>>> ASSIGNED: {chosen.name} (AppID={chosen.app_id}){hours_str}")
_echo(
f" Progress: {chosen.unlocked_achievements}/{chosen.total_achievements}"
f" ({chosen.completion_pct:.1f}%)"
)
_report_poll_confidence(chosen, games, state)
if config.uninstall_other_games:
count = uninstall_other_games(chosen.app_id)
if count:
_echo(f"\n Uninstalled {count} non-assigned games")
if not is_game_installed(chosen.app_id):
_echo(f"\n Auto-installing {chosen.name}...")
install_game(
chosen.app_id, chosen.name, config.steam_id, use_steam_protocol=True
)
def _pick_next_game_sequential(
games: list[GameInfo],
state: State,
config: Config,
on_select: Callable[[GameInfo], bool],
) -> None:
"""Pick the next-shortest playable game, asking the user per candidate.
``on_select`` is called with each prospective pick. Returning ``True``
accepts the assignment; returning ``False`` records a 7-day skip on
``state`` for that game and the next candidate is evaluated.
"""
while True:
skip = set(state.finished_app_ids) | state.active_skipped_ids()
candidates = [g for g in games if not g.is_complete and g.app_id not in skip]
if not candidates:
_echo(_NO_CONF_MSG)
state.current_app_id = None
state.current_game_name = ""
state.save()
return
candidates.sort(key=_sort_key)
_apply_cached_confidence_to_candidates(candidates)
chosen, confidence_skipped, linux_skipped = _pick_next_shortest_candidate(
candidates
)
if chosen is None:
_echo(
_NO_CONF_MSG
if confidence_skipped > 0 and linux_skipped == 0
else "\nNo playable games left (all have poor ProtonDB ratings)!"
)
state.current_app_id = None
state.current_game_name = ""
state.save()
return
if not on_select(chosen):
state.skip_for_days(chosen.app_id, 7)
state.save()
_echo(f"\n Skipped {chosen.name} for 7 days; picking next...")
continue
_assign_chosen_game(chosen, games, state, config)
return

View File

@ -0,0 +1,149 @@
"""Candidate selection helpers for ``scan`` and ``pick_next_game``.
Split out of :mod:`steam_backlog_enforcer.scanning` to keep both files under
the 250-line cap. Leaf helpers: nothing here calls back into ``scanning``.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._scanning_confidence import (
_candidate_passes_hltb_confidence,
)
from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.protondb import (
ProtonDBRating,
fetch_protondb_ratings,
)
if TYPE_CHECKING:
from steam_backlog_enforcer.steam_api import GameInfo
logger = logging.getLogger(__name__)
_PROTONDB_BATCH_SIZE = 20
_PICK_LIST_SIZE = 10
def _sort_key(g: GameInfo) -> tuple[int, float]:
"""Sort by known HLTB time (shortest first), then unknown games."""
if g.completionist_hours > 0:
return (0, g.completionist_hours)
return (1, g.name.lower().encode().hex().__hash__())
def _pick_playable_candidate(
candidates: list[GameInfo],
) -> GameInfo | None:
"""Return the first candidate with an acceptable ProtonDB rating.
Checks candidates in batches (sorted by HLTB hours, shortest first).
Games rated silver-or-worse, or gold-trending-down, are skipped.
"""
offset = 0
while offset < len(candidates):
batch = candidates[offset : offset + _PROTONDB_BATCH_SIZE]
app_ids = [g.app_id for g in batch]
ratings = fetch_protondb_ratings(app_ids)
for game in batch:
rating = ratings.get(game.app_id, ProtonDBRating(app_id=game.app_id))
if rating.is_playable:
if offset > 0 or game is not batch[0]:
_echo(
f" Skipped {offset + batch.index(game)} game(s) "
f"with poor Linux compatibility"
)
return game
logger.info(
"Skipping %s (AppID=%d): ProtonDB %s (trending %s)",
game.name,
game.app_id,
rating.tier,
rating.trending_tier,
)
offset += _PROTONDB_BATCH_SIZE
return None
def _collect_qualified_candidates(
candidates: list[GameInfo],
) -> tuple[list[GameInfo], int, int]:
"""Collect up to _PICK_LIST_SIZE playable, HLTB-confident candidates."""
qualified: list[GameInfo] = []
confidence_skipped = 0
linux_skipped = 0
for game in candidates:
if len(qualified) >= _PICK_LIST_SIZE:
break
if not _candidate_passes_hltb_confidence(game):
confidence_skipped += 1
continue
playable = _pick_playable_candidate([game])
if playable is not None:
qualified.append(playable)
else:
linux_skipped += 1
return qualified, confidence_skipped, linux_skipped
def _pick_next_shortest_candidate(
candidates: list[GameInfo],
) -> tuple[GameInfo | None, int, int]:
"""Pick next game by checking confidence one candidate at a time.
The list must be pre-sorted by desired priority (shortest first).
"""
confidence_skipped = 0
linux_skipped = 0
for game in candidates:
if not _candidate_passes_hltb_confidence(game):
confidence_skipped += 1
continue
# Reuse existing ProtonDB compatibility gate for one candidate.
playable = _pick_playable_candidate([game])
if playable is not None:
if linux_skipped > 0:
_echo(
f" Skipped {linux_skipped} game(s) with poor Linux compatibility"
)
return playable, confidence_skipped, linux_skipped
linux_skipped += 1
if linux_skipped > 0:
_echo(f" Skipped {linux_skipped} game(s) with poor Linux compatibility")
return None, confidence_skipped, linux_skipped
def _collect_top_candidates(
candidates: list[GameInfo],
n: int = 3,
) -> tuple[list[GameInfo], int, int]:
"""Collect up to n candidates that pass the Linux compatibility gate.
Args:
candidates: Pre-sorted list of candidate games.
n: Maximum number of qualified games to collect.
Returns:
Tuple of (qualified_list, conf_skipped, linux_skipped).
"""
qualified: list[GameInfo] = []
linux_skipped = 0
for game in candidates:
if len(qualified) >= n:
break
playable = _pick_playable_candidate([game])
if playable is not None:
qualified.append(playable)
else:
linux_skipped += 1
if linux_skipped > 0:
_echo(f" Skipped {linux_skipped} game(s) with poor Linux compatibility")
return qualified, 0, linux_skipped

View File

@ -16,11 +16,20 @@ from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.hltb import fetch_hltb_confidence_cached
if TYPE_CHECKING:
from steam_backlog_enforcer.config import State
from steam_backlog_enforcer.steam_api import GameInfo
from steam_backlog_enforcer._polls_reporting import (
_backfill_polls_for_finished,
_report_poll_confidence,
)
logger = logging.getLogger(__name__)
__all__ = [
"_backfill_polls_for_finished",
"_report_poll_confidence",
]
_MIN_COMP_100_POLLS = 3
_MIN_COUNT_COMP = 15
_MIN_CONFIDENCE_SUM = 18
@ -166,88 +175,3 @@ def _candidate_passes_hltb_confidence(game: GameInfo) -> bool:
)
return False
return True
def _backfill_polls_for_finished(
state: State,
games: list[GameInfo],
) -> dict[int, int]:
"""Lazily fetch poll counts for already-finished games missing them.
Reads the polls cache, identifies finished games whose poll count is
still ``0`` (typically because the cache predates the polls schema),
and triggers a one-shot HLTB search to backfill them. Returns the
refreshed polls cache.
"""
polls_cache = load_hltb_polls_cache()
name_by_id = {g.app_id: g.name for g in games}
missing = [
(aid, name_by_id[aid])
for aid in state.finished_app_ids
if aid in name_by_id and polls_cache.get(aid, 0) == 0
]
if not missing:
return polls_cache
logger.info(
"Backfilling HLTB poll counts for %d already-finished games...",
len(missing),
)
# Force a fresh search by removing the hours entries we want to refetch.
# (fetch_hltb_times_cached skips entries already in the hours cache.)
cache = load_hltb_cache()
preserved_hours = {aid: cache[aid] for aid, _ in missing if aid in cache}
for aid, _name in missing:
cache.pop(aid, None)
save_hltb_cache(cache, polls_cache)
fetch_hltb_confidence_cached(missing)
# Restore any previously-known hours that the refetch may have replaced
# with a worse match (we trust prior leisure+dlc estimates).
refreshed_hours = load_hltb_cache()
refreshed_polls = load_hltb_polls_cache()
for aid, prior_hours in preserved_hours.items():
if prior_hours > 0 and refreshed_hours.get(aid, -1) <= 0:
refreshed_hours[aid] = prior_hours
save_hltb_cache(refreshed_hours, refreshed_polls)
return refreshed_polls
def _report_poll_confidence(
chosen: GameInfo,
games: list[GameInfo],
state: State,
) -> None:
"""Print HLTB poll-count confidence info for the just-assigned game.
Shows the chosen game's ``comp_100_count`` (number of polled
completionist times on HowLongToBeat) and the historical minimum
among the user's previously-finished games. Marks a new historical
low so the user can be skeptical of unreliable estimates.
"""
polls_cache = _backfill_polls_for_finished(state, games)
chosen_polls = polls_cache.get(chosen.app_id, chosen.comp_100_count)
chosen.comp_100_count = chosen_polls
finished_polls = [
(polls_cache[aid], aid)
for aid in state.finished_app_ids
if polls_cache.get(aid, 0) > 0
]
if not finished_polls:
_echo(f" HLTB confidence: {chosen_polls} polled completionist times")
return
min_polls, min_aid = min(finished_polls)
name_by_id = {g.app_id: g.name for g in games}
min_name = name_by_id.get(min_aid, f"AppID={min_aid}")
warning = ""
if 0 < chosen_polls < min_polls:
warning = " ⚠ NEW LOW — estimate may be unreliable"
elif chosen_polls == 0:
warning = " ⚠ no polls recorded — estimate may be unreliable"
_echo(f" HLTB confidence: {chosen_polls} polled completionist times{warning}")
_echo(f" Historical min among finished: {min_polls} ({min_name})")

View File

@ -0,0 +1,80 @@
"""Tampering detection for installed games.
Split out of :mod:`steam_backlog_enforcer.scanning` to keep both files under
the 250-line cap. Leaf helpers: nothing here calls back into ``scanning``.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from steam_backlog_enforcer.config import load_snapshot
from steam_backlog_enforcer.enforcer import send_notification
from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.steam_api import SteamAPIClient
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
logger = logging.getLogger(__name__)
_TAMPER_CHECK_LIMIT = 3
def _check_game_tampering(
client: SteamAPIClient,
entry: dict[str, Any],
state: State,
) -> tuple[str, int, int] | None:
"""Check if a single game has unexpected achievement progress.
Args:
client: Steam API client.
entry: Snapshot entry for the game.
state: Current enforcer state.
Returns:
Tuple of (name, app_id, diff) if tampering detected, else None.
"""
app_id = entry["app_id"]
if app_id == state.current_app_id:
return None
if entry["unlocked_achievements"] >= entry["total_achievements"]:
return None
if entry.get("playtime_minutes", 0) <= 0:
return None
game = client.refresh_single_game(
app_id, entry["name"], entry.get("playtime_minutes", 0)
)
if game and game.unlocked_achievements > entry["unlocked_achievements"]:
diff = game.unlocked_achievements - entry["unlocked_achievements"]
return (entry["name"], app_id, diff)
return None
def detect_tampering(config: Config, state: State) -> None:
"""Check if achievements were unlocked on non-assigned games."""
old_snapshot = load_snapshot()
if old_snapshot is None:
return
client = SteamAPIClient(config.steam_api_key, config.steam_id)
# Quick check: only re-fetch a few random non-assigned games.
suspicious: list[tuple[str, int, int]] = []
for entry in old_snapshot:
result = _check_game_tampering(client, entry, state)
if result:
suspicious.append(result)
if len(suspicious) >= _TAMPER_CHECK_LIMIT:
break
if suspicious:
_echo("\n TAMPERING DETECTED:")
for name, app_id, diff in suspicious:
_echo(f" {name} (AppID={app_id}): +{diff} new achievements!")
send_notification(
"Tampering Detected!",
f"Achievements unlocked on {len(suspicious)} non-assigned games!",
)

View File

@ -2,45 +2,42 @@
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
import logging
import secrets
from typing import TYPE_CHECKING
from urllib.parse import quote_plus
from steam_backlog_enforcer._hltb_types import (
HLTB_BASE_URL,
_read_raw_cache,
load_hltb_cache,
load_hltb_game_id_cache,
load_hltb_leisure_100h_cache,
load_hltb_rush_cache,
)
from steam_backlog_enforcer._scanning_confidence import (
_apply_cached_confidence_to_candidates,
_confidence_fail_reasons,
_refresh_candidate_confidence_batch,
from steam_backlog_enforcer._stats_display import (
_format_completion_date,
_print_pace_scenario,
_print_worst_example,
_sum_hours,
)
from steam_backlog_enforcer._stats_gathering import (
_ensure_completed_rush_data,
_ensure_rush_data,
_filter_qualifying_games,
_refresh_recently_played_completions,
)
from steam_backlog_enforcer._stats_types import _GameTimes
from steam_backlog_enforcer._web_dataset import (
PaceVsHLTB,
compute_pace_vs_hltb,
count_complete_since_start,
)
from steam_backlog_enforcer.config import SNAPSHOT_FILE, load_snapshot
from steam_backlog_enforcer.config import load_snapshot
from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.hltb import fetch_hltb_detail_missing
from steam_backlog_enforcer.protondb import (
ProtonDBRating,
fetch_protondb_ratings,
)
from steam_backlog_enforcer.steam_api import (
GameInfo,
SteamAPIClient,
SteamAPIError,
)
# _GameTimes lives in the _stats_types leaf so both this module and its
# helper modules can share it; it is re-exported here because callers (and
# tests) have always imported it from _stats. Without __all__, mypy's
# --no-implicit-reexport rejects those imports.
__all__ = ["_GameTimes"]
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
@ -50,181 +47,6 @@ _HOURS_PER_DAY_PRESETS = (2.0, 4.0, 6.0, 8.0)
_LINE = "─" * 70
_HLTB_SEARCH_BASE = "https://howlongtobeat.com/?q="
@dataclass
class _GameTimes:
"""Per-game time estimates for stats display."""
game: GameInfo
worst_hours: float
rush_hours: float
leisure_100h: float
hltb_game_id: int = field(default=0)
def _filter_qualifying_games(
games: list[GameInfo],
state: State,
) -> tuple[list[_GameTimes], int, int, int]:
"""Return qualifying incomplete games with their time estimates.
Applies the same HLTB-confidence and Linux-compatibility filters as the
game picker. The current game and already-finished games are excluded.
Returns:
(qualified_list, hltb_skipped, linux_skipped, no_data_skipped)
"""
rush_cache = load_hltb_rush_cache()
leisure_100h_cache = load_hltb_leisure_100h_cache()
game_id_cache = load_hltb_game_id_cache()
hours_cache = load_hltb_cache()
exclude = set(state.finished_app_ids)
if state.current_app_id is not None:
exclude.add(state.current_app_id)
candidates = [g for g in games if not g.is_complete and g.app_id not in exclude]
_apply_cached_confidence_to_candidates(candidates)
_refresh_candidate_confidence_batch(candidates)
hltb_skipped = 0
linux_skipped = 0
no_data_skipped = 0
app_ids_to_check: list[int] = []
conf_ok: list[GameInfo] = []
for game in candidates:
if _confidence_fail_reasons(game):
hltb_skipped += 1
continue
conf_ok.append(game)
app_ids_to_check.append(game.app_id)
ratings: dict[int, ProtonDBRating] = {}
if app_ids_to_check:
ratings = fetch_protondb_ratings(app_ids_to_check)
qualified: list[_GameTimes] = []
for game in conf_ok:
rating = ratings.get(game.app_id, ProtonDBRating(app_id=game.app_id))
if not rating.is_playable:
linux_skipped += 1
continue
rush = rush_cache.get(game.app_id, -1)
leisure = leisure_100h_cache.get(game.app_id, -1)
# worst_hours = max of: snapshot completionist, HLTB hours cache (fallback
# when snapshot is stale/missing), and leisure_100h (slowest 100% time).
snap_hours = game.completionist_hours if game.completionist_hours > 0 else -1
cache_hours = hours_cache.get(game.app_id, -1)
worst_candidates = [v for v in (snap_hours, cache_hours, leisure) if v > 0]
worst = max(worst_candidates) if worst_candidates else -1
if worst <= 0 and rush <= 0 and leisure <= 0:
no_data_skipped += 1
continue
qualified.append(
_GameTimes(
game=game,
worst_hours=worst,
rush_hours=rush,
leisure_100h=leisure,
hltb_game_id=game_id_cache.get(game.app_id, 0),
)
)
return qualified, hltb_skipped, linux_skipped, no_data_skipped
def _ensure_rush_data(qualified: list[_GameTimes]) -> bool:
"""Auto-fetch rush/leisure detail for games that are missing it.
Returns True when a fetch was performed; the caller should then re-run
``_filter_qualifying_games`` to pick up the updated caches.
"""
total_q = len(qualified)
missing = sum(1 for e in qualified if e.rush_hours <= 0)
if not qualified or not missing:
return False
_echo(f"Fetching HLTB detail for {missing}/{total_q} games missing rush/leisure...")
game_pairs = [(e.game.app_id, e.game.name) for e in qualified]
fetch_hltb_detail_missing(game_pairs)
return True
def _ensure_completed_rush_data(games: list[GameInfo]) -> bool:
"""Fetch rush/leisure detail for completed games used for pace calibration.
Completed games aren't processed by ``_ensure_rush_data`` (which only
handles incomplete qualifying games), so this separate pass fills in
their rush/leisure data for ``compute_pace_vs_hltb``.
Returns True when at least one new fetch was performed.
"""
pairs = [
(g.app_id, g.name) for g in games if g.is_complete and g.playtime_minutes > 0
]
if not pairs:
return False
_echo(
f"Fetching HLTB detail for {len(pairs)} completed games (pace calibration)..."
)
fetched = fetch_hltb_detail_missing(pairs)
return fetched > 0
def _print_worst_example(entries: list[_GameTimes]) -> None:
"""Print a randomly selected example from the worst-case qualified games."""
examples = [e for e in entries if e.worst_hours > 0]
if not examples:
return
example = secrets.choice(examples)
_echo(f"\n Example game: {example.game.name!r}")
_echo(f" Worst case: {example.worst_hours:.1f} h")
if example.rush_hours > 0:
_echo(f" Rush: {example.rush_hours:.1f} h")
if example.leisure_100h > 0:
_echo(f" Leisure: {example.leisure_100h:.1f} h")
hltb_game_id = example.hltb_game_id
if hltb_game_id == 0:
# On-demand backfill: one search to get the HLTB game ID for this game.
fetch_hltb_detail_missing([(example.game.app_id, example.game.name)])
hltb_game_id = load_hltb_game_id_cache().get(example.game.app_id, 0)
if hltb_game_id > 0:
_echo(f" HLTB: {HLTB_BASE_URL}/game/{hltb_game_id}")
else:
_echo(f" HLTB: {_HLTB_SEARCH_BASE}{quote_plus(example.game.name)}")
def _sum_hours(entries: list[_GameTimes], attr: str) -> tuple[float, int]:
"""Sum a time attribute across entries; return (total_hours, missing_count).
Games where the attribute is ≤ 0 contribute 0 to the sum and are counted
in ``missing_count`` so the user knows the estimate may be an undercount.
"""
total = 0.0
missing = 0
for e in entries:
val: float = getattr(e, attr)
if val > 0:
total += val
else:
missing += 1
return round(total, 1), missing
def _format_completion_date(hours: float, daily_hours: float) -> str:
"""Return 'N days (YYYY-MM-DD)' for finishing hours at daily_hours per day."""
if hours <= 0 or daily_hours <= 0:
return "N/A"
days = int(hours / daily_hours)
target = datetime.now(timezone.utc) + timedelta(days=days)
return f"{days} days ({target.strftime('%Y-%m-%d')})"
def _print_scenario(
label: str,
@ -249,50 +71,6 @@ def _print_scenario(
_echo(f" @ {daily:.0f} h/day → {estimate}")
def _print_pace_scenario(state: State, remaining: int, games_done: int) -> None:
"""Print the pace-based completion estimate.
``games_done`` must be the count of games completed ON OR AFTER
``state.enforcement_started_at`` (use ``count_complete_since_start``).
Pre-enforcement completions inflate the rate and are excluded.
"""
_echo("\n 1. AT YOUR CURRENT PACE")
if not state.enforcement_started_at:
_echo(" No start date recorded.")
_echo(" Set enforcement_started_at in state.json (ISO-8601 UTC)")
_echo(" to enable this estimate.")
return
try:
started = datetime.fromisoformat(state.enforcement_started_at)
except ValueError:
_echo(f" Invalid enforcement_started_at: {state.enforcement_started_at!r}")
return
now = datetime.now(timezone.utc)
days_elapsed = max(1, (now - started).days)
if games_done == 0:
_echo(f" Started: {started.strftime('%Y-%m-%d')}")
_echo(" No games finished yet — pace cannot be estimated.")
return
rate = games_done / days_elapsed
_echo(f" Started: {started.strftime('%Y-%m-%d')}")
_echo(
f" Finished: {games_done} games in {days_elapsed} days "
"(since enforcement start)"
)
_echo(
f" Pace: {rate:.4f} games/day (1 game every {1 / rate:.1f} days)"
)
_echo(f" Remaining: {remaining} games")
days_to_go = int(remaining / rate)
finish = now + timedelta(days=days_to_go)
_echo(f" Est. complete: {days_to_go} days ({finish.strftime('%Y-%m-%d')})")
def _print_player_speed_scenario(
pace: PaceVsHLTB | None,
rush_total: float,
@ -344,74 +122,6 @@ def _print_player_speed_scenario(
_echo(f" @ {daily:.0f} h/day → {estimate}")
def _refresh_recently_played_completions(
games: list[GameInfo],
config: Config,
) -> list[GameInfo]:
"""Refresh achievement data for incomplete games played since last scan.
Makes 1 ``GetOwnedGames`` request + 1 ``GetPlayerAchievements`` per
recently-played incomplete game. Finds games newly completed since the
last ``scan`` without re-scanning the whole library.
Returns a new list with updated GameInfo objects for any game that was
played after the snapshot was written; all other games are unchanged.
"""
try:
snapshot_mtime = SNAPSHOT_FILE.stat().st_mtime
except OSError:
return games
try:
client = SteamAPIClient(config.steam_api_key, config.steam_id)
owned_raw = client.get_owned_games()
except SteamAPIError:
logger.debug("Steam API unavailable; skipping completion refresh.")
return games
last_played_map = {g["appid"]: g.get("rtime_last_played", 0) for g in owned_raw}
to_refresh = [
g
for g in games
if not g.is_complete and last_played_map.get(g.app_id, 0) > snapshot_mtime
]
if not to_refresh:
return games
_echo(
f"Refreshing {len(to_refresh)} recently-played game(s)"
" for up-to-date completion status..."
)
game_map = {g.app_id: g for g in games}
def _refresh_one(game: GameInfo) -> GameInfo:
achievements = client.get_achievement_details(game.app_id)
if not achievements:
return game
unlocked = sum(1 for a in achievements if a.achieved)
return GameInfo(
app_id=game.app_id,
name=game.name,
total_achievements=len(achievements),
unlocked_achievements=unlocked,
playtime_minutes=game.playtime_minutes,
achievements=achievements,
completionist_hours=game.completionist_hours,
comp_100_count=game.comp_100_count,
count_comp=game.count_comp,
)
with ThreadPoolExecutor(max_workers=20) as pool:
futures = {pool.submit(_refresh_one, g): g for g in to_refresh}
for future in as_completed(futures):
refreshed = future.result()
game_map[refreshed.app_id] = refreshed
return list(game_map.values())
def cmd_stats(_config: Config, state: State) -> None:
"""Display backlog completion-time statistics.

View File

@ -0,0 +1,116 @@
"""Formatting helpers for the ``stats`` command's printed report.
Split out of :mod:`steam_backlog_enforcer._stats` to keep both files under
the 250-line cap. Leaf helpers: nothing here calls back into ``_stats``.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import secrets
from typing import TYPE_CHECKING
from urllib.parse import quote_plus
from steam_backlog_enforcer._hltb_types import (
HLTB_BASE_URL,
load_hltb_game_id_cache,
)
from steam_backlog_enforcer._stats_types import _HLTB_SEARCH_BASE, _GameTimes
from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.hltb import fetch_hltb_detail_missing
if TYPE_CHECKING:
from steam_backlog_enforcer.config import State
def _print_worst_example(entries: list[_GameTimes]) -> None:
"""Print a randomly selected example from the worst-case qualified games."""
examples = [e for e in entries if e.worst_hours > 0]
if not examples:
return
example = secrets.choice(examples)
_echo(f"\n Example game: {example.game.name!r}")
_echo(f" Worst case: {example.worst_hours:.1f} h")
if example.rush_hours > 0:
_echo(f" Rush: {example.rush_hours:.1f} h")
if example.leisure_100h > 0:
_echo(f" Leisure: {example.leisure_100h:.1f} h")
hltb_game_id = example.hltb_game_id
if hltb_game_id == 0:
# On-demand backfill: one search to get the HLTB game ID for this game.
fetch_hltb_detail_missing([(example.game.app_id, example.game.name)])
hltb_game_id = load_hltb_game_id_cache().get(example.game.app_id, 0)
if hltb_game_id > 0:
_echo(f" HLTB: {HLTB_BASE_URL}/game/{hltb_game_id}")
else:
_echo(f" HLTB: {_HLTB_SEARCH_BASE}{quote_plus(example.game.name)}")
def _sum_hours(entries: list[_GameTimes], attr: str) -> tuple[float, int]:
"""Sum a time attribute across entries; return (total_hours, missing_count).
Games where the attribute is ≤ 0 contribute 0 to the sum and are counted
in ``missing_count`` so the user knows the estimate may be an undercount.
"""
total = 0.0
missing = 0
for e in entries:
val: float = getattr(e, attr)
if val > 0:
total += val
else:
missing += 1
return round(total, 1), missing
def _format_completion_date(hours: float, daily_hours: float) -> str:
"""Return 'N days (YYYY-MM-DD)' for finishing hours at daily_hours per day."""
if hours <= 0 or daily_hours <= 0:
return "N/A"
days = int(hours / daily_hours)
target = datetime.now(timezone.utc) + timedelta(days=days)
return f"{days} days ({target.strftime('%Y-%m-%d')})"
def _print_pace_scenario(state: State, remaining: int, games_done: int) -> None:
"""Print the pace-based completion estimate.
``games_done`` must be the count of games completed ON OR AFTER
``state.enforcement_started_at`` (use ``count_complete_since_start``).
Pre-enforcement completions inflate the rate and are excluded.
"""
_echo("\n 1. AT YOUR CURRENT PACE")
if not state.enforcement_started_at:
_echo(" No start date recorded.")
_echo(" Set enforcement_started_at in state.json (ISO-8601 UTC)")
_echo(" to enable this estimate.")
return
try:
started = datetime.fromisoformat(state.enforcement_started_at)
except ValueError:
_echo(f" Invalid enforcement_started_at: {state.enforcement_started_at!r}")
return
now = datetime.now(timezone.utc)
days_elapsed = max(1, (now - started).days)
if games_done == 0:
_echo(f" Started: {started.strftime('%Y-%m-%d')}")
_echo(" No games finished yet — pace cannot be estimated.")
return
rate = games_done / days_elapsed
_echo(f" Started: {started.strftime('%Y-%m-%d')}")
_echo(
f" Finished: {games_done} games in {days_elapsed} days "
"(since enforcement start)"
)
_echo(
f" Pace: {rate:.4f} games/day (1 game every {1 / rate:.1f} days)"
)
_echo(f" Remaining: {remaining} games")
days_to_go = int(remaining / rate)
finish = now + timedelta(days=days_to_go)
_echo(f" Est. complete: {days_to_go} days ({finish.strftime('%Y-%m-%d')})")

View File

@ -0,0 +1,222 @@
"""Game selection and HLTB/completion data top-ups for ``stats``.
Split out of :mod:`steam_backlog_enforcer._stats` to keep both files under
the 250-line cap. Leaf helpers: nothing here calls back into ``_stats``.
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, as_completed
import logging
from typing import TYPE_CHECKING
from steam_backlog_enforcer._hltb_types import (
load_hltb_cache,
load_hltb_game_id_cache,
load_hltb_leisure_100h_cache,
load_hltb_rush_cache,
)
from steam_backlog_enforcer._scanning_confidence import (
_apply_cached_confidence_to_candidates,
_confidence_fail_reasons,
_refresh_candidate_confidence_batch,
)
from steam_backlog_enforcer._stats_types import _GameTimes
from steam_backlog_enforcer.config import SNAPSHOT_FILE
from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.hltb import fetch_hltb_detail_missing
from steam_backlog_enforcer.protondb import (
ProtonDBRating,
fetch_protondb_ratings,
)
from steam_backlog_enforcer.steam_api import (
GameInfo,
SteamAPIClient,
SteamAPIError,
)
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
logger = logging.getLogger(__name__)
def _filter_qualifying_games(
games: list[GameInfo],
state: State,
) -> tuple[list[_GameTimes], int, int, int]:
"""Return qualifying incomplete games with their time estimates.
Applies the same HLTB-confidence and Linux-compatibility filters as the
game picker. The current game and already-finished games are excluded.
Returns:
(qualified_list, hltb_skipped, linux_skipped, no_data_skipped)
"""
rush_cache = load_hltb_rush_cache()
leisure_100h_cache = load_hltb_leisure_100h_cache()
game_id_cache = load_hltb_game_id_cache()
hours_cache = load_hltb_cache()
exclude = set(state.finished_app_ids)
if state.current_app_id is not None:
exclude.add(state.current_app_id)
candidates = [g for g in games if not g.is_complete and g.app_id not in exclude]
_apply_cached_confidence_to_candidates(candidates)
_refresh_candidate_confidence_batch(candidates)
hltb_skipped = 0
linux_skipped = 0
no_data_skipped = 0
app_ids_to_check: list[int] = []
conf_ok: list[GameInfo] = []
for game in candidates:
if _confidence_fail_reasons(game):
hltb_skipped += 1
continue
conf_ok.append(game)
app_ids_to_check.append(game.app_id)
ratings: dict[int, ProtonDBRating] = {}
if app_ids_to_check:
ratings = fetch_protondb_ratings(app_ids_to_check)
qualified: list[_GameTimes] = []
for game in conf_ok:
rating = ratings.get(game.app_id, ProtonDBRating(app_id=game.app_id))
if not rating.is_playable:
linux_skipped += 1
continue
rush = rush_cache.get(game.app_id, -1)
leisure = leisure_100h_cache.get(game.app_id, -1)
# worst_hours = max of: snapshot completionist, HLTB hours cache (fallback
# when snapshot is stale/missing), and leisure_100h (slowest 100% time).
snap_hours = game.completionist_hours if game.completionist_hours > 0 else -1
cache_hours = hours_cache.get(game.app_id, -1)
worst_candidates = [v for v in (snap_hours, cache_hours, leisure) if v > 0]
worst = max(worst_candidates) if worst_candidates else -1
if worst <= 0 and rush <= 0 and leisure <= 0:
no_data_skipped += 1
continue
qualified.append(
_GameTimes(
game=game,
worst_hours=worst,
rush_hours=rush,
leisure_100h=leisure,
hltb_game_id=game_id_cache.get(game.app_id, 0),
)
)
return qualified, hltb_skipped, linux_skipped, no_data_skipped
def _ensure_rush_data(qualified: list[_GameTimes]) -> bool:
"""Auto-fetch rush/leisure detail for games that are missing it.
Returns True when a fetch was performed; the caller should then re-run
``_filter_qualifying_games`` to pick up the updated caches.
"""
total_q = len(qualified)
missing = sum(1 for e in qualified if e.rush_hours <= 0)
if not qualified or not missing:
return False
_echo(f"Fetching HLTB detail for {missing}/{total_q} games missing rush/leisure...")
game_pairs = [(e.game.app_id, e.game.name) for e in qualified]
fetch_hltb_detail_missing(game_pairs)
return True
def _ensure_completed_rush_data(games: list[GameInfo]) -> bool:
"""Fetch rush/leisure detail for completed games used for pace calibration.
Completed games aren't processed by ``_ensure_rush_data`` (which only
handles incomplete qualifying games), so this separate pass fills in
their rush/leisure data for ``compute_pace_vs_hltb``.
Returns True when at least one new fetch was performed.
"""
pairs = [
(g.app_id, g.name) for g in games if g.is_complete and g.playtime_minutes > 0
]
if not pairs:
return False
_echo(
f"Fetching HLTB detail for {len(pairs)} completed games (pace calibration)..."
)
fetched = fetch_hltb_detail_missing(pairs)
return fetched > 0
def _refresh_recently_played_completions(
games: list[GameInfo],
config: Config,
) -> list[GameInfo]:
"""Refresh achievement data for incomplete games played since last scan.
Makes 1 ``GetOwnedGames`` request + 1 ``GetPlayerAchievements`` per
recently-played incomplete game. Finds games newly completed since the
last ``scan`` without re-scanning the whole library.
Returns a new list with updated GameInfo objects for any game that was
played after the snapshot was written; all other games are unchanged.
"""
try:
snapshot_mtime = SNAPSHOT_FILE.stat().st_mtime
except OSError:
return games
try:
client = SteamAPIClient(config.steam_api_key, config.steam_id)
owned_raw = client.get_owned_games()
except SteamAPIError:
logger.debug("Steam API unavailable; skipping completion refresh.")
return games
last_played_map = {g["appid"]: g.get("rtime_last_played", 0) for g in owned_raw}
to_refresh = [
g
for g in games
if not g.is_complete and last_played_map.get(g.app_id, 0) > snapshot_mtime
]
if not to_refresh:
return games
_echo(
f"Refreshing {len(to_refresh)} recently-played game(s)"
" for up-to-date completion status..."
)
game_map = {g.app_id: g for g in games}
def _refresh_one(game: GameInfo) -> GameInfo:
achievements = client.get_achievement_details(game.app_id)
if not achievements:
return game
unlocked = sum(1 for a in achievements if a.achieved)
return GameInfo(
app_id=game.app_id,
name=game.name,
total_achievements=len(achievements),
unlocked_achievements=unlocked,
playtime_minutes=game.playtime_minutes,
achievements=achievements,
completionist_hours=game.completionist_hours,
comp_100_count=game.comp_100_count,
count_comp=game.count_comp,
)
with ThreadPoolExecutor(max_workers=20) as pool:
futures = {pool.submit(_refresh_one, g): g for g in to_refresh}
for future in as_completed(futures):
refreshed = future.result()
game_map[refreshed.app_id] = refreshed
return list(game_map.values())

View File

@ -0,0 +1,26 @@
"""Shared value types for the ``stats`` command.
A leaf module: imported by :mod:`steam_backlog_enforcer._stats` and by its
helper modules, so it must not import either of them back.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from steam_backlog_enforcer.steam_api import GameInfo
_HLTB_SEARCH_BASE = "https://howlongtobeat.com/?q="
@dataclass
class _GameTimes:
"""Per-game time estimates for stats display."""
game: GameInfo
worst_hours: float
rush_hours: float
leisure_100h: float
hltb_game_id: int = field(default=0)

View File

@ -0,0 +1,201 @@
"""HTTP client for the Steam Web API.
Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, as_completed
import logging
import threading
import time
from typing import TYPE_CHECKING, Any
import requests
from steam_backlog_enforcer._steam_models import (
MAX_WORKERS,
STEAM_API_BASE,
AchievementInfo,
GameInfo,
)
if TYPE_CHECKING:
from collections.abc import Callable
logger = logging.getLogger(__name__)
class SteamAPIError(Exception):
"""Raised when the Steam API returns an error."""
class SteamAPIClient:
"""Client for interacting with the Steam Web API."""
def __init__(self, api_key: str, steam_id: str) -> None:
"""Initialize the Steam API client.
Args:
api_key: Steam Web API key.
steam_id: Steam64 ID of the user.
"""
self.api_key = api_key
self.steam_id = steam_id
self.session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
pool_maxsize=MAX_WORKERS,
pool_connections=MAX_WORKERS,
)
self.session.mount("https://", adapter)
self.session.headers["Accept"] = "application/json"
self._rate_lock = threading.Lock()
self._request_times: list[float] = []
self._max_rps = 18
def _rate_limit(self) -> None:
"""Enforce rate limit across threads."""
while True:
with self._rate_lock:
now = time.time()
self._request_times = [t for t in self._request_times if now - t < 1.0]
if len(self._request_times) < self._max_rps:
self._request_times.append(now)
return
time.sleep(0.06)
def _get(self, url: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
"""Rate-limited GET request."""
self._rate_limit()
if params is None:
params = {}
params["key"] = self.api_key
try:
resp = self.session.get(url, params=params, timeout=30)
resp.raise_for_status()
result: dict[str, Any] = resp.json()
except requests.RequestException as e:
msg = f"Steam API request failed: {e}"
raise SteamAPIError(msg) from e
else:
return result
def get_owned_games(self) -> list[dict[str, Any]]:
"""Fetch all games owned by the user."""
url = f"{STEAM_API_BASE}/IPlayerService/GetOwnedGames/v1/"
data = self._get(
url,
{
"steamid": self.steam_id,
"include_appinfo": "true",
"include_played_free_games": "true",
"format": "json",
},
)
games: list[dict[str, Any]] = data.get("response", {}).get("games", [])
logger.info("Found %d owned games.", len(games))
return games
def get_achievement_details(self, app_id: int) -> list[AchievementInfo]:
"""Fetch per-achievement detail for a game."""
url = f"{STEAM_API_BASE}/ISteamUserStats/GetPlayerAchievements/v1/"
try:
data = self._get(
url,
{
"steamid": self.steam_id,
"appid": str(app_id),
"l": "english",
"format": "json",
},
)
except SteamAPIError:
return []
stats = data.get("playerstats", {})
if not stats.get("success", False):
return []
raw: list[dict[str, Any]] = stats.get("achievements", [])
return [
AchievementInfo(
api_name=a.get("apiname", ""),
display_name=a.get("name", a.get("apiname", "")),
achieved=bool(a.get("achieved", 0)),
unlock_time=a.get("unlocktime", 0),
)
for a in raw
]
def _fetch_one_game(self, game_dict: dict[str, Any]) -> GameInfo | None:
"""Fetch achievement data for one game. Thread-safe."""
app_id = game_dict["appid"]
achievements = self.get_achievement_details(app_id)
if not achievements:
return None
name = game_dict.get("name", f"Unknown ({app_id})")
total = len(achievements)
unlocked = sum(1 for a in achievements if a.achieved)
return GameInfo(
app_id=app_id,
name=name,
total_achievements=total,
unlocked_achievements=unlocked,
playtime_minutes=game_dict.get("playtime_forever", 0),
achievements=achievements,
)
def build_game_list(
self,
progress_callback: Callable[[int, int], None] | None = None,
) -> list[GameInfo]:
"""Build full game list with achievement data (parallel)."""
owned = self.get_owned_games()
games: list[GameInfo] = []
done_count = 0
total = len(owned)
lock = threading.Lock()
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
futures = {pool.submit(self._fetch_one_game, g): g for g in owned}
for future in as_completed(futures):
try:
result = future.result()
except (
KeyError,
TypeError,
ValueError,
SteamAPIError,
requests.RequestException,
):
result = None
with lock:
done_count += 1
if progress_callback:
progress_callback(done_count, total)
if result is not None:
games.append(result)
games.sort(key=lambda g: g.name.lower())
return games
def refresh_single_game(
self, app_id: int, name: str, playtime: int = 0
) -> GameInfo | None:
"""Re-fetch achievement data for one game."""
achievements = self.get_achievement_details(app_id)
if not achievements:
return None
total = len(achievements)
unlocked = sum(1 for a in achievements if a.achieved)
return GameInfo(
app_id=app_id,
name=name,
total_achievements=total,
unlocked_achievements=unlocked,
playtime_minutes=playtime,
achievements=achievements,
)

View File

@ -0,0 +1,123 @@
"""Starting the Steam client as the desktop user, and install-state queries.
Split out of :mod:`steam_backlog_enforcer.game_install` to keep it under the
250-line cap. The enforcer runs as root, so everything here is about resolving
*which* user to become before touching the desktop session.
"""
from __future__ import annotations
import logging
import os
import pwd
import subprocess
import time
from steam_backlog_enforcer._desktop_env import (
desktop_env_args,
desktop_runtime_dir,
desktop_session_ready,
resolve_desktop_user,
)
from steam_backlog_enforcer._steam_launch import steam_is_installed
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH
logger = logging.getLogger(__name__)
def _get_real_user() -> str | None:
"""Get the desktop user to drop privileges to.
Delegates to the shared resolver so this module honours
STEAM_ENFORCER_DESKTOP_USER. Reading only SUDO_USER/USER returned None
under systemd (which sets neither), so every ``geteuid() == 0 and
real_user`` guard below silently fell through to running as root.
"""
return resolve_desktop_user()
def _get_uid_gid_for_user(username: str) -> tuple[int, int]:
"""Get (uid, gid) for a username."""
try:
pw = pwd.getpwnam(username)
except KeyError:
return 1000, 1000
else:
return pw.pw_uid, pw.pw_gid
def is_game_installed(app_id: int) -> bool:
"""Check if a game is installed by looking for its appmanifest.
A manifest with StateFlags != 4 (FullyInstalled) means the game is
still downloading or queued, which still counts as "install triggered".
"""
manifest = STEAMAPPS_PATH / f"appmanifest_{app_id}.acf"
return manifest.exists()
def _ensure_steam_running() -> None:
"""Start the Steam client if it is not already running.
Does nothing if Steam is not installed - there is no client to start, and
trying anyway only sleeps 15s waiting on a process that died on exec.
"""
if not steam_is_installed():
logger.info("Steam is not installed — skipping client start.")
return
# Check if any steam process is running (main client, not just helpers).
try:
result = subprocess.run(
["/usr/bin/pgrep", "-f", "steam.sh"],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
logger.debug("Steam client already running")
return
except FileNotFoundError:
pass
real_user = _get_real_user()
logger.info("Starting Steam client...")
try:
if os.geteuid() == 0 and real_user and real_user != "root":
uid, _ = _get_uid_gid_for_user(real_user)
# Defer rather than launch a Steam that would come up without a
# runtime dir, and so without working audio, for the session.
if not desktop_session_ready(uid):
logger.info(
"Deferring Steam start: %s does not exist yet.",
desktop_runtime_dir(uid),
)
return
cmd = [
"sudo",
"-u",
real_user,
"env",
*desktop_env_args(real_user, uid),
"steam",
"-silent",
]
else:
cmd = ["steam", "-silent"]
subprocess.Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# Give Steam time to initialize and start scanning manifests.
time.sleep(15)
except FileNotFoundError:
logger.exception("Steam executable not found")
# Latches the "no Steam library" warning so a 3s enforce loop logs it once
# rather than once per game per pass. A set (rather than a module-level bool
# reassigned via `global`) keeps the mutation local to the container.
_LIBRARY_WARNED: set[str] = set()

View File

@ -0,0 +1,40 @@
"""Errors raised when Steam cannot be driven.
A leaf module so both :mod:`steam_backlog_enforcer.library_hider` and
:mod:`steam_backlog_enforcer._steam_launch` can raise and catch these without
importing each other. Split out to keep both under the 250-line cap.
"""
from __future__ import annotations
class SteamUnavailableError(RuntimeError):
"""Raised when Steam cannot be driven over CDP.
Covers both "Steam is not installed" and "Steam is installed but never
opened its debug port". Callers are expected to degrade gracefully rather
than abort: an unreachable Steam means there is no library to hide, which
is not a fatal condition for the enforcer.
"""
class SteamUpdateInProgressError(SteamUnavailableError):
"""Raised to defer a Steam restart while a game update is in flight.
Subclasses :class:`SteamUnavailableError` so existing callers already
degrade gracefully (skip this pass, retry next loop). Restarting Steam
mid-update suspends and can corrupt the transfer, so the enforcer waits
for updates to finish before bouncing Steam to open the CDP port.
"""
class DesktopSessionNotReadyError(SteamUnavailableError):
"""Raised to defer a Steam launch until the user's session exists.
Subclasses :class:`SteamUnavailableError` so existing callers already
degrade gracefully (skip this pass, retry next loop). Launching Steam
before ``/run/user/<uid>`` exists hands every Wine child a runtime dir
that is not there, so it falls back from winepulse to winealsa and stays
that way for the whole session — the Kingdom Come: Deliverance II startup
crash. Waiting a pass costs 3s; getting it wrong costs a reboot.
"""

View File

@ -0,0 +1,248 @@
"""Getting Steam running with its devtools port open.
Split out of :mod:`steam_backlog_enforcer.library_hider` to keep both files
under the 250-line cap: this module owns the Steam *lifecycle* (is it up, does
it have a CDP port, restart it as the desktop user), not what to do with it.
"""
from __future__ import annotations
import logging
import os
from pathlib import Path
import shutil
import subprocess
import time
from steam_backlog_enforcer._cdp import (
_CDP_PORT,
_cdp_result_value,
_evaluate_js,
_get_shared_js_ws_url,
)
from steam_backlog_enforcer._desktop_env import (
desktop_runtime_dir,
desktop_session_ready,
desktop_uid,
)
from steam_backlog_enforcer._steam_errors import (
DesktopSessionNotReadyError,
SteamUnavailableError,
SteamUpdateInProgressError,
)
from steam_backlog_enforcer._steam_process import _run_as_user
from steam_backlog_enforcer._steam_state import steam_update_in_progress
logger = logging.getLogger(__name__)
_CDP_TIMEOUT = 120
_STEAM_STARTUP_WAIT = 45
# Real Steam client binary, as shipped by the distro's `steam` package.
#
# Deliberately NOT probed with shutil.which("steam"): a launcher wrapper on
# $PATH (e.g. /usr/local/bin/steam adding -cef-* flags) keeps `which` truthy
# long after the package itself is gone - as happens when a total block
# uninstalls Steam. Checking the real binary is what actually answers
# "can we launch Steam at all?".
_STEAM_BINARY = "/usr/bin/steam"
def steam_is_installed() -> bool:
"""Return True if the real Steam client binary is present."""
return Path(_STEAM_BINARY).exists()
# Handles for fire-and-forget launches, kept only so they can be reaped.
_SPAWNED: list[subprocess.Popen[bytes]] = []
# ──────────────────────────────────────────────────────────────
# Ensure Steam is running with devtools port
# ──────────────────────────────────────────────────────────────
def _is_steam_running() -> bool:
"""Check whether any Steam process is alive."""
pgrep = shutil.which("pgrep") or "/usr/bin/pgrep"
result = subprocess.run(
[pgrep, "-x", "steam"],
capture_output=True,
check=False,
)
return result.returncode == 0
def _steam_has_debug_port() -> bool:
"""Check whether steamwebhelper is listening on the CDP port."""
return _get_shared_js_ws_url() is not None
def _wait_for_cdp_ready() -> bool:
"""Wait up to *_STEAM_STARTUP_WAIT* seconds for CDP to become ready."""
for _ in range(_STEAM_STARTUP_WAIT):
if _get_shared_js_ws_url() is not None:
return True
time.sleep(1)
return False
def _wait_for_collections_ready() -> bool:
"""Wait until ``collectionStore`` is fully initialised.
Right after Steam starts, the CDP port may be open but the
internal collection data hasn't loaded yet. Poll a lightweight
JS check until ``GetCollection`` stops throwing.
"""
js = (
"(() => { try { collectionStore.GetCollection('hidden');"
" return 'ok'; } catch(e) { return 'not_ready'; } })()"
)
for _ in range(_STEAM_STARTUP_WAIT):
try:
result = _evaluate_js(js)
if _cdp_result_value(result) == "ok":
return True
except RuntimeError:
pass
time.sleep(1)
return False
def _resolve_desktop_user() -> str | None:
"""Resolve which desktop user owns the Steam/X11 session.
Prefers the explicit STEAM_ENFORCER_DESKTOP_USER (set by the systemd
unit, which has no SUDO_USER/USER of its own since it is started
directly by systemd rather than via `sudo`), then falls back to
SUDO_USER/USER for interactive `sudo` invocations.
"""
return (
os.environ.get("STEAM_ENFORCER_DESKTOP_USER")
or os.environ.get("SUDO_USER")
or os.environ.get("USER")
)
def _shutdown_steam() -> None:
"""Send ``steam -shutdown`` and wait for the process to exit."""
real_user = _resolve_desktop_user()
try:
_run_as_user(["steam", "-shutdown"], real_user)
except FileNotFoundError:
return
pgrep = shutil.which("pgrep") or "/usr/bin/pgrep"
for _ in range(30):
result = subprocess.run(
[pgrep, "-x", "steam"],
capture_output=True,
check=False,
)
if result.returncode != 0:
return
time.sleep(1)
def _launch_steam_with_debug() -> None:
"""Launch Steam with CEF debugging enabled."""
real_user = _resolve_desktop_user()
_run_as_user(
[
"steam",
"-cef-enable-debugging",
f"-devtools-port={_CDP_PORT}",
"-silent",
],
real_user,
)
def ensure_steam_debug_port() -> None:
"""Make sure Steam is running with the CDP debug port open.
If Steam is running without the port, it is restarted.
If Steam is not running, it is launched.
Raises:
SteamUnavailableError: If Steam is not installed, or is installed but
never opens its debug port.
"""
if _steam_has_debug_port():
logger.debug("Steam CDP port already available.")
return
# Bail out before the ~45s launch-and-wait: with no binary to exec there
# is nothing to wait for, and retrying every pass only burns time and
# leaves dead processes behind.
if not steam_is_installed():
msg = f"Steam is not installed ({_STEAM_BINARY} does not exist)"
raise SteamUnavailableError(msg)
# Never launch Steam into a session that does not exist yet: it would get
# a missing XDG_RUNTIME_DIR, silently fall back to winealsa, and stay
# audio-broken until the next restart. Defer instead — the loop retries.
real_user = _resolve_desktop_user()
if os.geteuid() == 0 and not desktop_session_ready(desktop_uid(real_user)):
msg = (
"Deferring Steam launch: the desktop session's runtime directory "
f"({desktop_runtime_dir(desktop_uid(real_user))}) does not exist "
"yet. Launching now would leave Steam without audio; will retry."
)
logger.info(msg)
raise DesktopSessionNotReadyError(msg)
logger.info("Steam CDP port not available — (re)starting Steam...")
if _is_steam_running():
# Never bounce a running Steam while a game update is downloading or
# committing: the shutdown suspends it and can leave a partially
# written install (the root cause of the AoE2 launch crash). Defer and
# retry on the next enforce pass.
if steam_update_in_progress():
msg = (
"Deferring Steam restart: a game update is in progress. "
"Restarting now would interrupt and can corrupt it; will "
"retry once the update settles."
)
logger.info(msg)
raise SteamUpdateInProgressError(msg)
_shutdown_steam()
_launch_steam_with_debug()
if not _wait_for_cdp_ready():
msg = "Timed out waiting for Steam CDP port to become ready"
raise SteamUnavailableError(msg)
logger.info("Steam CDP port ready.")
if not _wait_for_collections_ready():
msg = "Timed out waiting for Steam collections to initialise"
raise SteamUnavailableError(msg)
logger.info("Steam collection store ready.")
# ──────────────────────────────────────────────────────────────
# Steam restart helper
# ──────────────────────────────────────────────────────────────
def restart_steam() -> None:
"""Gracefully restart the Steam client with CEF debugging enabled.
Skips the restart if a game update is downloading or committing, so the
update is not interrupted (interrupting it can corrupt the install).
"""
if steam_update_in_progress():
logger.warning(
"Skipping Steam restart — a game update is in progress; "
"restarting now could corrupt it.",
)
return
logger.info("Restarting Steam client with debug port...")
_shutdown_steam()
_launch_steam_with_debug()
if not _wait_for_cdp_ready():
logger.warning("Steam restarted but CDP port not ready.")
else:
logger.info("Steam restarted with CDP port ready.")

View File

@ -0,0 +1,98 @@
"""Steam Web API client for fetching games and achievement data."""
from __future__ import annotations
from dataclasses import dataclass, field
import logging
from typing import Any
logger = logging.getLogger(__name__)
STEAM_API_BASE = "https://api.steampowered.com"
MAX_WORKERS = 20
@dataclass
class AchievementInfo:
"""Single achievement state."""
api_name: str
display_name: str
achieved: bool
unlock_time: int
@dataclass
class GameInfo:
"""Info about an owned Steam game."""
app_id: int
name: str
total_achievements: int
unlocked_achievements: int
playtime_minutes: int
achievements: list[AchievementInfo] = field(default_factory=list)
completionist_hours: float = -1
comp_100_count: int = 0
count_comp: int = 0
@property
def completion_pct(self) -> float:
"""Achievement completion percentage."""
if self.total_achievements == 0:
return 100.0
return (self.unlocked_achievements / self.total_achievements) * 100.0
@property
def is_complete(self) -> bool:
"""True if all achievements are unlocked."""
return (
self.total_achievements > 0
and self.unlocked_achievements >= self.total_achievements
)
def to_snapshot(self) -> dict[str, Any]:
"""Serialize to JSON-safe dict."""
return {
"app_id": self.app_id,
"name": self.name,
"total_achievements": self.total_achievements,
"unlocked_achievements": self.unlocked_achievements,
"playtime_minutes": self.playtime_minutes,
"completionist_hours": self.completionist_hours,
"comp_100_count": self.comp_100_count,
"count_comp": self.count_comp,
"achievements": [
{
"api_name": a.api_name,
"display_name": a.display_name,
"achieved": a.achieved,
"unlock_time": a.unlock_time,
}
for a in self.achievements
],
}
@classmethod
def from_snapshot(cls, data: dict[str, Any]) -> GameInfo:
"""Deserialize from a cached snapshot dict."""
achievements = [
AchievementInfo(
api_name=a["api_name"],
display_name=a.get("display_name", a["api_name"]),
achieved=a["achieved"],
unlock_time=a.get("unlock_time", 0),
)
for a in data.get("achievements", [])
]
return cls(
app_id=data["app_id"],
name=data["name"],
total_achievements=data["total_achievements"],
unlocked_achievements=data["unlocked_achievements"],
playtime_minutes=data.get("playtime_minutes", 0),
completionist_hours=data.get("completionist_hours", -1),
comp_100_count=data.get("comp_100_count", 0),
count_comp=data.get("count_comp", 0),
achievements=achievements,
)

View File

@ -0,0 +1,58 @@
"""Spawning processes as the desktop user, and reaping them.
Split out of :mod:`steam_backlog_enforcer._steam_launch` to keep both under
the 250-line cap. Owns the fire-and-forget process registry so it has a single
owner rather than a global shared across responsibilities.
"""
from __future__ import annotations
import logging
import os
import subprocess
from steam_backlog_enforcer._desktop_env import desktop_user_cmd
logger = logging.getLogger(__name__)
# Handles for fire-and-forget launches, kept only so they can be reaped.
_SPAWNED: list[subprocess.Popen[bytes]] = []
def _reap_spawned() -> None:
"""Clear out previously launched processes that have since exited.
Launches here are fire-and-forget: Steam is meant to outlive the call, so
it is never waited on. That leaves any launch which dies immediately - a
missing binary, a broken wrapper - sitting as a zombie that still carries
the name ``steam``, which anything scanning /proc reads as "Steam is
running". Polling the old handles reaps them and retires the name.
"""
_SPAWNED[:] = [proc for proc in _SPAWNED if proc.poll() is None]
def _run_as_user(cmd: list[str], user: str | None) -> None:
"""Run a command, dropping to *user* if currently root.
Refuses to run at all when root and no desktop user resolves: the command
would otherwise execute *as root* on the user's session, which is how the
enforcer put a root Steam ("Cannot run as root user") on screen.
Failing closed costs one skipped pass; failing open costs a modal.
"""
_reap_spawned()
if os.geteuid() == 0 and (not user or user == "root"):
logger.error(
"Refusing to run %s as root: no desktop user resolved "
"(is STEAM_ENFORCER_DESKTOP_USER set?)",
cmd[0] if cmd else "<empty>",
)
return
full_cmd = desktop_user_cmd(cmd, user)
_SPAWNED.append(
subprocess.Popen(
full_cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
)

View File

@ -8,11 +8,50 @@ Steam library location.
from __future__ import annotations
import os
from pathlib import Path
import re
STEAMAPPS_PATH = Path("~/.local/share/Steam/steamapps").expanduser()
# The real library path, captured before any test fixture redirects
# STEAMAPPS_PATH, so destructive helpers can refuse to touch it.
_REAL_STEAMAPPS = Path("~/.local/share/Steam/steamapps").expanduser()
def _assert_not_real_steam(path: Path) -> None:
"""Raise if *path* is inside the real Steam directory during tests.
Defence-in-depth guard: when running under pytest, even if test
fixtures fail to redirect ``STEAMAPPS_PATH``, destructive
operations (uninstall, rmtree, unlink) will refuse to touch
real files. In production runs this is a no-op.
"""
if "PYTEST_CURRENT_TEST" not in os.environ:
return # production run — real Steam paths are expected
try:
path.resolve().relative_to(_REAL_STEAMAPPS.resolve())
except ValueError:
return # path is NOT under real Steam — safe to proceed
if STEAMAPPS_PATH.resolve() == _REAL_STEAMAPPS.resolve():
msg = (
f"SAFETY: refusing destructive operation on real Steam path "
f"{path!s} — STEAMAPPS_PATH was not redirected by test fixtures"
)
raise RuntimeError(msg)
def steam_library_ready() -> bool:
"""Return True if Steam has an initialised library directory.
When ``steamapps`` does not exist Steam has never completed first-run
setup, so an install cannot succeed by any route: the ``steam://`` handler
has nowhere to install to, and writing an appmanifest raises
FileNotFoundError. Callers use this to skip provably-futile work rather
than retrying it on every enforce pass.
"""
return STEAMAPPS_PATH.is_dir()
def _manifest_transfer_active(manifest: Path) -> bool:
"""Return True if *manifest* shows unfinished download or staging bytes.

View File

@ -0,0 +1,175 @@
"""Steam-store blocking at the iptables/DNS layer.
These call nothing else in the blocker, so they extract cleanly: the
one-way dependency is what keeps store_blocker importable.
Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
import contextlib
import logging
from pathlib import Path
import shutil
import socket
import subprocess
from steam_backlog_enforcer.config import (
BLOCKED_DOMAINS,
)
logger = logging.getLogger(__name__)
# Path to the hosts install script. _REPO_ROOT resolves to $HOME (this
# module lives two levels below it); the script itself is in the
# linux_configuration checkout under testsAndMisc, not directly under $HOME.
_REPO_ROOT = Path(__file__).resolve().parents[2]
HOSTS_INSTALL_SCRIPT = (
_REPO_ROOT
/ "testsAndMisc"
/ "linux_configuration"
/ "scripts"
/ "periodic_background"
/ "hosts"
/ "install.sh"
)
# iptables chain name for our blocking rules.
IPTABLES_CHAIN = "STEAM_ENFORCER"
# Resolved absolute paths for executables (avoids S607 partial-path warnings).
_SUDO = shutil.which("sudo") or "/usr/bin/sudo"
_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables"
_BASH = shutil.which("bash") or "/usr/bin/bash"
_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl"
_TEE = shutil.which("tee") or "/usr/bin/tee"
# IP address used in /etc/hosts for blocking domains.
_HOSTS_REDIRECT_IP = ".".join(["0"] * 4)
def _is_iptables_blocked() -> bool:
"""Check if our iptables chain exists and has rules."""
try:
result = subprocess.run(
[_SUDO, _IPTABLES, "-L", IPTABLES_CHAIN, "-n"],
capture_output=True,
text=True,
timeout=5,
check=False,
)
except (OSError, subprocess.SubprocessError):
return False
else:
return result.returncode == 0 and "DROP" in result.stdout
def _block_store_iptables() -> bool:
"""Block Steam Store domains using iptables (IP-based)."""
try:
# Create chain if it doesn't exist.
subprocess.run(
[_SUDO, _IPTABLES, "-N", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
# Flush existing rules in our chain.
subprocess.run(
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=True,
)
# Resolve domains and block their IPs.
blocked_ips: set[str] = set()
for domain in BLOCKED_DOMAINS:
with contextlib.suppress(socket.gaierror):
ips = socket.getaddrinfo(domain, 443, socket.AF_INET)
for _, _, _, _, addr in ips:
blocked_ips.add(addr[0])
for ip in blocked_ips:
subprocess.run(
[
_SUDO,
_IPTABLES,
"-A",
IPTABLES_CHAIN,
"-d",
ip,
"-j",
"DROP",
],
capture_output=True,
timeout=5,
check=True,
)
# Hook our chain into OUTPUT if not already there.
result = subprocess.run(
[_SUDO, _IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
if result.returncode != 0:
subprocess.run(
[_SUDO, _IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=True,
)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to block store via iptables")
return False
else:
logger.info("Steam Store blocked via iptables (%d IPs).", len(blocked_ips))
return True
def _unblock_store_iptables() -> bool:
"""Remove iptables-based block."""
try:
subprocess.run(
[_SUDO, _IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-X", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to unblock iptables")
return False
else:
logger.info("Steam Store unblocked from iptables.")
return True
def flush_dns_cache() -> None:
"""Flush the system DNS cache."""
commands = [
["systemd-resolve", "--flush-caches"],
["resolvectl", "flush-caches"],
["nscd", "--invalidate=hosts"],
]
for cmd in commands:
with contextlib.suppress(FileNotFoundError, OSError):
subprocess.run(
cmd,
capture_output=True,
timeout=5,
check=False,
)

View File

@ -1,189 +1,56 @@
"""Total gaming block: no in-app command to lift it early.
"""Total gaming block: the lock, its status, and the lifecycle that drives it.
Uninstalls Steam, kills all game/launcher processes, blocks all Steam +
game-website domains, purges known Steam/Proton filesystem remnants, and
uninstalls Proton helper packages, for a fixed number of days.
This module owns the *state* of a total block -- the guard-lib-protected lock
file and the status derived from it -- and orchestrates the two independent
mechanisms that enforce it:
Tamper-resistance is provided by guard-lib (~/guard-lib): the lock file's
``until`` timestamp is protected by a bind-mounted, chattr-immutable
file-guard instance, and pacman itself refuses to reinstall/upgrade the
``steam`` package while the lock is active (package-block).
* :mod:`steam_backlog_enforcer._total_block_purge` makes Steam not installed;
* :mod:`steam_backlog_enforcer._total_block_hosts` and
:mod:`steam_backlog_enforcer._total_block_iptables` make it unreachable.
There is no in-app command to lift a block early. Tamper-resistance comes
from guard-lib (~/guard-lib): the lock file's ``until`` timestamp is
protected by a bind-mounted, chattr-immutable file-guard instance, and pacman
itself refuses to reinstall/upgrade the ``steam`` package while the lock is
active (package-block).
"""
from __future__ import annotations
import contextlib
from dataclasses import dataclass
from datetime import datetime, timezone
import json
import logging
from pathlib import Path
import shutil
import socket
import subprocess
from steam_backlog_enforcer.config import (
BLOCKED_DOMAINS,
CONFIG_DIR,
HOSTS_FILE,
_atomic_write,
from steam_backlog_enforcer._total_block_hosts import (
apply_total_block_hosts,
remove_total_block_hosts,
)
from steam_backlog_enforcer.enforcer import (
get_pids_by_process_names,
kill_processes_by_name,
from steam_backlog_enforcer._total_block_iptables import (
apply_total_block_iptables,
remove_total_block_iptables,
)
from steam_backlog_enforcer.store_blocker import (
_disable_hosts_protection,
_enable_hosts_protection,
_sudo_write_hosts,
flush_dns_cache,
from steam_backlog_enforcer._total_block_launchers import LAUNCHER_PROCESS_NAMES
from steam_backlog_enforcer._total_block_purge import (
STEAM_PACKAGE,
is_steam_installed,
kill_steam_and_launchers,
purge_steam_and_proton,
uninstall_steam_package,
)
from steam_backlog_enforcer.config import CONFIG_DIR
from steam_backlog_enforcer.store_blocker import flush_dns_cache
logger = logging.getLogger(__name__)
TOTAL_BLOCK_LOCK_FILE = CONFIG_DIR / "total_block_lock.json"
_IPTABLES_IP_CACHE_FILE = CONFIG_DIR / "total_block_ip_cache.json"
_PACKAGE_BLOCK_NAME = "steam-block"
_STEAM_PACKAGE = "steam"
# Steam's own client processes.
STEAM_CLIENT_PROCESS_NAMES = frozenset({"steam", "steamwebhelper", "steam.sh"})
# Third-party game launchers, best-effort match by process name.
LAUNCHER_PROCESS_NAMES = frozenset(
{
"EpicGamesLauncher",
"legendary",
"lutris",
"heroic",
"GalaxyClient",
"itch",
"bottles",
"minecraft-launcher",
"prismlauncher",
"multimc",
"polymc",
"ATLauncher",
"GDLauncher",
"gdlauncher-carbon",
"TLauncher",
"modrinth-app",
}
)
# Known limitation, not engineered around in this pass: any launcher run
# via an interpreter rather than its own compiled binary shows up in
# /proc/*/comm as the INTERPRETER's name, not its own - process-name
# matching won't catch those. Confirmed live for "lutris" (a Python
# script, appears as `python3`), and documented upstream for some
# Minecraft launchers (TLauncher, ATLauncher, GDLauncher - exec'd as
# `java -jar ...`, appear as `java`). Matching the interpreter name
# itself is NOT a fix: kill_processes_by_name runs inside this very
# enforcer process, which is itself `python3` - adding it to the set
# would SIGTERM the daemon and every other Python process on the system.
# Consistent with the "best-effort" framing already agreed for non-Steam
# blocking; the hosts+iptables domain blocking below is the backstop for
# launchers this can't catch by process name.
TOTAL_BLOCK_DOMAINS = [
*BLOCKED_DOMAINS,
"steamcommunity.com",
"api.steampowered.com",
"login.steampowered.com",
"help.steampowered.com",
"steamcontent.com",
"steamstatic.com",
"steamusercontent.com",
"cdn.steamstatic.com",
]
# Browser/flash game sites. Note itch.io overlaps with the "itch" desktop
# app process kill above (web storefront vs. desktop client).
GAME_WEBSITE_DOMAINS = [
"newgrounds.com",
"armorgames.com",
"kongregate.com",
"crazygames.com",
"poki.com",
"miniclip.com",
"addictinggames.com",
"y8.com",
"coolmathgames.com",
"itch.io",
]
def _expand_with_www(domains: list[str]) -> list[str]:
"""Add a ``www.`` variant for each bare second-level domain.
Most of these sites 301-redirect their apex domain to ``www.<domain>``
(confirmed live for newgrounds.com) - blocking only the apex leaves the
www subdomain reachable through both the hosts-file entry and the
iptables IP block. Domains that already carry a subdomain (e.g.
store.steampowered.com) are left as-is.
"""
expanded: list[str] = []
for domain in domains:
expanded.append(domain)
if domain.count(".") == 1:
expanded.append(f"www.{domain}")
return expanded
_ALL_TOTAL_BLOCK_DOMAINS = _expand_with_www(
[*TOTAL_BLOCK_DOMAINS, *GAME_WEBSITE_DOMAINS]
)
_HOSTS_BLOCK_BEGIN = "# BEGIN steam-backlog-enforcer total-block\n"
_HOSTS_BLOCK_END = "# END steam-backlog-enforcer total-block\n"
_SUDO = shutil.which("sudo") or "/usr/bin/sudo"
_GUARDCTL = shutil.which("guardctl") or "/usr/local/bin/guardctl"
# Call pacman.orig directly (bypassing pacman_wrapper's interactive
# word-unscramble challenge for "steam") - this is the tool's own
# authorized action, not a user bypass attempt, and enforce_total_block_tick
# must be able to run unattended.
_PACMAN = (
shutil.which("pacman.orig") or shutil.which("pacman") or "/usr/bin/pacman.orig"
)
_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables"
IPTABLES_CHAIN = "STEAM_TOTAL_BLOCK"
# The /etc/hosts null-route redirect target used to make a blocked domain
# resolve nowhere - built from parts rather than the literal so linters don't
# mistake it for a socket bind-all-interfaces address (it never is one).
_NULL_ROUTE_IP = ".".join(["0"] * 4)
_STEAM_PURGE_LOG_FILE = CONFIG_DIR / "total_block_purge_log.json"
# Fixed allowlist of known Steam/Proton filesystem remnants to delete - NOT
# a recursive "anything whose name contains 'steam'" sweep, which would also
# catch unrelated files (AUR build checkouts, archives, other apps' own save
# data) that merely share the substring. Confirmed present on the reference
# machine: ~/.steam (symlink farm), ~/steam (secondary/portable install),
# ~/.local/share/Steam (the real install - steamapps, userdata, screenshots,
# and compatibilitytools.d's GE-Proton builds all live under here).
_STEAM_REMNANT_PATHS: tuple[Path, ...] = (
Path.home() / ".steam",
Path.home() / "steam",
Path.home() / ".local" / "share" / "Steam",
Path.home() / ".steampath",
Path.home() / ".steampid",
Path.home() / ".config" / "steamtinkerlaunch",
Path.home() / ".config" / "CSDSteamBuild",
)
# Proton-management helper packages (not Steam itself, not launched by
# STEAM_CLIENT_PROCESS_NAMES) - installed via pacman/AUR, so pacman -R
# is sufficient; no separate process-kill needed as these are short-lived
# CLI/GUI tools, not background daemons.
_PROTON_HELPER_PACKAGES: tuple[str, ...] = (
"protondb-tags-git",
"protonhax-git",
"protontricks-git",
"protonup-ng-git",
"protonup-qt",
)
@dataclass
@ -271,442 +138,6 @@ def get_total_block_status() -> TotalBlockStatus:
)
# ──────────────────────────────────────────────────────────────
# Process killing + launcher package removal
# ──────────────────────────────────────────────────────────────
def _pacman_owner(path: str) -> str | None:
"""Return the pacman package name that owns *path*, or None."""
result = subprocess.run(
[_PACMAN, "-Qo", path],
capture_output=True,
text=True,
timeout=10,
check=False,
)
if result.returncode != 0:
return None
marker = " is owned by "
if marker not in result.stdout:
return None
tail = result.stdout.split(marker, 1)[1].strip()
return tail.split()[0] if tail else None
def _uninstall_package(package: str) -> bool:
"""Remove *package* via pacman. Returns True on success or if absent."""
try:
result = subprocess.run(
[_SUDO, _PACMAN, "-R", "--noconfirm", package],
capture_output=True,
text=True,
timeout=120,
check=False,
)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to run pacman -R %s", package)
return False
if result.returncode == 0:
return True
if "target not found" in (result.stderr or "").lower():
return True
logger.error(
"pacman -R %s failed (rc=%d): %s",
package,
result.returncode,
result.stderr[-500:] if result.stderr else "",
)
return False
def _kill_and_uninstall_launchers() -> list[tuple[int, str]]:
"""Kill running third-party launchers and uninstall their pacman package.
Resolves each PID's ``/proc/<pid>/exe`` target *before* sending SIGTERM,
since the symlink stops resolving once the process has exited. Package
removal is best-effort: launchers installed outside pacman (flatpak,
AppImage, a wine prefix) simply have no owning package and are just
killed again next tick, same as before this existed.
"""
pids = get_pids_by_process_names(LAUNCHER_PROCESS_NAMES)
exe_paths: dict[int, str] = {}
for pid in pids:
with contextlib.suppress(OSError):
exe_paths[pid] = str(Path(f"/proc/{pid}/exe").resolve(strict=True))
killed = kill_processes_by_name(LAUNCHER_PROCESS_NAMES)
packages: set[str] = set()
for pid, _name in killed:
exe_path = exe_paths.get(pid)
if exe_path is not None:
package = _pacman_owner(exe_path)
if package is not None:
packages.add(package)
for package in packages:
if not _uninstall_package(package):
logger.warning(
"Total block: failed to uninstall launcher package %s", package
)
return killed
def _kill_steam_and_launchers() -> list[tuple[int, str]]:
"""Kill Steam client and known third-party launcher processes."""
steam_killed = kill_processes_by_name(STEAM_CLIENT_PROCESS_NAMES)
launcher_killed = _kill_and_uninstall_launchers()
return steam_killed + launcher_killed
# ──────────────────────────────────────────────────────────────
# Steam package removal
# ──────────────────────────────────────────────────────────────
def _is_package_installed(package: str) -> bool:
"""Return True if *package* is currently installed via pacman."""
result = subprocess.run(
[_PACMAN, "-Qi", package],
capture_output=True,
timeout=10,
check=False,
)
return result.returncode == 0
def _is_steam_installed() -> bool:
"""Return True if the ``steam`` pacman package is currently installed."""
return _is_package_installed(_STEAM_PACKAGE)
def _uninstall_steam_package() -> bool:
"""Remove the ``steam`` pacman package.
Returns True on success or if it was already absent.
"""
return _uninstall_package(_STEAM_PACKAGE)
def _uninstall_proton_helpers() -> list[str]:
"""Uninstall known Proton-management helper packages that are present.
Returns the subset of :data:`_PROTON_HELPER_PACKAGES` that were actually
installed and successfully removed (for logging), not the full fixed
list.
"""
removed: list[str] = []
for package in _PROTON_HELPER_PACKAGES:
if not _is_package_installed(package):
continue
if _uninstall_package(package):
removed.append(package)
else:
logger.warning("Total block: failed to uninstall proton helper %s", package)
return removed
def _remove_steam_remnants() -> list[str]:
"""Delete the curated Steam/Proton filesystem remnants that exist.
Symlinks are unlinked directly rather than following them into
:func:`shutil.rmtree`, since e.g. ``~/.steampath`` -> a file inside
``~/.steam``, which this same pass may already have removed.
"""
removed: list[str] = []
for path in _STEAM_REMNANT_PATHS:
if not (path.is_symlink() or path.exists()):
continue
try:
if path.is_symlink() or path.is_file():
path.unlink()
else:
shutil.rmtree(path)
except OSError:
logger.exception("Failed to remove steam remnant %s", path)
continue
removed.append(str(path))
return removed
def _log_steam_purge(removed_paths: list[str], removed_packages: list[str]) -> None:
"""Append a timestamped record of a Steam/Proton purge to disk.
A no-op when nothing was actually removed, so the log only grows on
ticks that did real work (this runs every enforce tick while the block
is active - see :func:`enforce_total_block_tick`).
"""
if not removed_paths and not removed_packages:
return
try:
existing = json.loads(_STEAM_PURGE_LOG_FILE.read_text(encoding="utf-8"))
if not isinstance(existing, list):
existing = []
except (OSError, json.JSONDecodeError, ValueError):
existing = []
existing.append(
{
"timestamp": datetime.now(timezone.utc).isoformat(),
"removed_paths": removed_paths,
"removed_packages": removed_packages,
}
)
_atomic_write(_STEAM_PURGE_LOG_FILE, json.dumps(existing, indent=2) + "\n")
def _purge_steam_and_proton() -> None:
"""Remove curated Steam/Proton filesystem remnants and helper packages.
Best-effort and re-run every enforce tick, same as the Steam-package
reappearance check: a stat() per fixed path and a ``pacman -Qi`` per
helper package are cheap even when there is nothing left to do.
"""
removed_paths = _remove_steam_remnants()
removed_packages = _uninstall_proton_helpers()
if removed_paths or removed_packages:
logger.info(
"Total block: purged steam path(s) %s, proton package(s) %s",
removed_paths,
removed_packages,
)
_log_steam_purge(removed_paths, removed_packages)
# ──────────────────────────────────────────────────────────────
# Domain blocking (hosts + iptables) - separate from store_blocker's own
# BLOCKED_DOMAINS/STEAM_ENFORCER state, so ending the total block never
# touches normal config.block_store entries.
# ──────────────────────────────────────────────────────────────
def _apply_total_block_hosts() -> bool:
"""Append the total-block domain block to /etc/hosts, if not present."""
try:
content = HOSTS_FILE.read_text(encoding="utf-8")
except OSError:
logger.exception("Failed to read /etc/hosts")
return False
if _HOSTS_BLOCK_BEGIN in content:
return True
block_lines = [_HOSTS_BLOCK_BEGIN]
block_lines += [
f"{_NULL_ROUTE_IP} {domain}\n" for domain in _ALL_TOTAL_BLOCK_DOMAINS
]
block_lines.append(_HOSTS_BLOCK_END)
new_content = content if content.endswith("\n") else content + "\n"
new_content += "".join(block_lines)
try:
_disable_hosts_protection()
_sudo_write_hosts(new_content)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to write total-block hosts entries")
return False
finally:
_enable_hosts_protection()
return True
def _remove_total_block_hosts() -> bool:
"""Remove the total-block domain block from /etc/hosts, if present."""
try:
content = HOSTS_FILE.read_text(encoding="utf-8")
except OSError:
logger.exception("Failed to read /etc/hosts")
return False
if _HOSTS_BLOCK_BEGIN not in content:
return True
start = content.index(_HOSTS_BLOCK_BEGIN)
end_marker_at = content.index(_HOSTS_BLOCK_END, start)
end = end_marker_at + len(_HOSTS_BLOCK_END)
new_content = content[:start] + content[end:]
try:
_disable_hosts_protection()
_sudo_write_hosts(new_content)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to remove total-block hosts entries")
return False
finally:
_enable_hosts_protection()
return True
def _load_cached_ips() -> set[str]:
"""Return the accumulated set of previously-resolved total-block IPs."""
if not _IPTABLES_IP_CACHE_FILE.exists():
return set()
try:
data = json.loads(_IPTABLES_IP_CACHE_FILE.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError, ValueError):
return set()
if not isinstance(data, list):
return set()
return {str(ip) for ip in data}
def _save_cached_ips(ips: set[str]) -> None:
"""Persist the accumulated total-block IP set to disk."""
_atomic_write(_IPTABLES_IP_CACHE_FILE, json.dumps(sorted(ips)) + "\n")
def _iptables_chain_intact(expected_ips: set[str]) -> bool:
"""Cheap check for whether the chain and its OUTPUT hook are intact.
One `-S` + one `-C` call (two forks), versus the ~30 forks a full
rebuild costs - this is what keeps :func:`_apply_total_block_iptables`
from re-resolving DNS and re-forking a subprocess per IP on every
3-second enforce tick.
"""
listing = subprocess.run(
[_SUDO, _IPTABLES, "-S", IPTABLES_CHAIN],
capture_output=True,
text=True,
timeout=5,
check=False,
)
if listing.returncode != 0:
return False
current_ips: set[str] = set()
for line in listing.stdout.splitlines():
parts = line.split()
if "-d" in parts:
idx = parts.index("-d")
if idx + 1 < len(parts):
current_ips.add(parts[idx + 1].split("/")[0])
if not expected_ips.issubset(current_ips):
return False
hook = subprocess.run(
[_SUDO, _IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
return hook.returncode == 0
def _apply_total_block_iptables() -> bool:
"""Ensure the total-block iptables chain blocks the known domain IPs.
Resolves domains and (re)builds the chain only when a cheap check
(:func:`_iptables_chain_intact`) shows it's actually needed - an
already-intact chain returns immediately. This matters for two
reasons: re-resolving via DNS every enforce tick (every 3s) would
otherwise fork ~30 subprocesses/tick indefinitely for a multi-day
block, and once /etc/hosts's entries take effect, these same domains
resolve to 0.0.0.0 locally, which would collapse a from-scratch
rebuild to that one trivial address and silently drop the real
upstream IPs blocked on the first, pre-hosts-block resolution -
resolving only when actually needed keeps the accumulated IP cache
from growing unboundedly too.
Callers MUST call this before :func:`_apply_total_block_hosts` the
first time (see :func:`start_total_block`): once the hosts entries
are in place, DNS resolution for every blocked domain returns 0.0.0.0
right here on this machine, and no real upstream IP is ever learned.
"""
cached = _load_cached_ips()
if cached and _iptables_chain_intact(cached):
return True
resolved_ips: set[str] = set()
try:
subprocess.run(
[_SUDO, _IPTABLES, "-N", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=True,
)
for domain in _ALL_TOTAL_BLOCK_DOMAINS:
with contextlib.suppress(socket.gaierror):
for _, _, _, _, addr in socket.getaddrinfo(domain, 443, socket.AF_INET):
resolved_ips.add(str(addr[0]))
blocked_ips = (cached | resolved_ips) - {_NULL_ROUTE_IP}
_save_cached_ips(blocked_ips)
for ip in blocked_ips:
subprocess.run(
[_SUDO, _IPTABLES, "-A", IPTABLES_CHAIN, "-d", ip, "-j", "DROP"],
capture_output=True,
timeout=5,
check=True,
)
result = subprocess.run(
[_SUDO, _IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
if result.returncode != 0:
subprocess.run(
[_SUDO, _IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=True,
)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to apply total-block iptables rules")
return False
else:
logger.info(
"Total block: %d domain IP(s) blocked via iptables.", len(blocked_ips)
)
return True
def _remove_total_block_iptables() -> bool:
"""Remove the total-block iptables chain and its OUTPUT hook."""
try:
subprocess.run(
[_SUDO, _IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-X", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to remove total-block iptables rules")
return False
else:
_IPTABLES_IP_CACHE_FILE.unlink(missing_ok=True)
return True
# ──────────────────────────────────────────────────────────────
# Public lifecycle API
# ──────────────────────────────────────────────────────────────
def start_total_block(days: int) -> bool:
"""Start a total gaming block for *days* days.
@ -729,7 +160,7 @@ def start_total_block(days: int) -> bool:
"start",
_PACKAGE_BLOCK_NAME,
"--package",
_STEAM_PACKAGE,
STEAM_PACKAGE,
"--lock-file",
str(TOTAL_BLOCK_LOCK_FILE),
"--days",
@ -745,21 +176,21 @@ def start_total_block(days: int) -> bool:
logger.error("Failed to start package-block lock: %s", result.stderr)
return False
killed = _kill_steam_and_launchers()
killed = kill_steam_and_launchers(LAUNCHER_PROCESS_NAMES)
if killed:
logger.info("Total block: killed %d process(es): %s", len(killed), killed)
if not _uninstall_steam_package():
if not uninstall_steam_package():
logger.warning("Total block: failed to uninstall steam (will retry each tick)")
_purge_steam_and_proton()
purge_steam_and_proton()
# iptables MUST be applied before hosts: it resolves real upstream IPs,
# and once the hosts block is written, local resolution for these same
# domains collapses to 0.0.0.0 (see _apply_total_block_iptables).
if not _apply_total_block_iptables():
if not apply_total_block_iptables():
logger.warning("Total block: failed to apply iptables rules")
if not _apply_total_block_hosts():
if not apply_total_block_hosts():
logger.warning("Total block: failed to apply hosts entries")
flush_dns_cache()
@ -772,16 +203,16 @@ def enforce_total_block_tick() -> None:
Called every enforce-loop iteration while :func:`is_total_block_active`
is True.
"""
_kill_steam_and_launchers()
kill_steam_and_launchers(LAUNCHER_PROCESS_NAMES)
if _is_steam_installed():
if is_steam_installed():
logger.warning("Steam reappeared during total block - removing again")
_uninstall_steam_package()
uninstall_steam_package()
_purge_steam_and_proton()
purge_steam_and_proton()
_apply_total_block_iptables()
_apply_total_block_hosts()
apply_total_block_iptables()
apply_total_block_hosts()
def end_total_block_cleanup() -> None:
@ -804,9 +235,9 @@ def end_total_block_cleanup() -> None:
"package-block end failed (may already be ended): %s", result.stderr
)
if not _remove_total_block_hosts():
if not remove_total_block_hosts():
logger.warning("Failed to remove total-block hosts entries")
if not _remove_total_block_iptables():
if not remove_total_block_iptables():
logger.warning("Failed to remove total-block iptables rules")
flush_dns_cache()

View File

@ -0,0 +1,64 @@
"""The domain lists a total gaming block makes unreachable.
A data table, versioned separately from the hosts/iptables mechanism that
consumes it in :mod:`steam_backlog_enforcer._total_block_net` -- adding a
storefront here should not mean touching blocking code.
"""
from __future__ import annotations
from steam_backlog_enforcer.config import BLOCKED_DOMAINS
TOTAL_BLOCK_DOMAINS = [
*BLOCKED_DOMAINS,
"steamcommunity.com",
"api.steampowered.com",
"login.steampowered.com",
"help.steampowered.com",
"steamcontent.com",
"steamstatic.com",
"steamusercontent.com",
"cdn.steamstatic.com",
]
# Browser/flash game sites. Note itch.io overlaps with the "itch" desktop
# app process kill above (web storefront vs. desktop client).
GAME_WEBSITE_DOMAINS = [
"newgrounds.com",
"armorgames.com",
"kongregate.com",
"crazygames.com",
"poki.com",
"miniclip.com",
"addictinggames.com",
"y8.com",
"coolmathgames.com",
"itch.io",
]
def _expand_with_www(domains: list[str]) -> list[str]:
"""Add a ``www.`` variant for each bare second-level domain.
Most of these sites 301-redirect their apex domain to ``www.<domain>``
(confirmed live for newgrounds.com) - blocking only the apex leaves the
www subdomain reachable through both the hosts-file entry and the
iptables IP block. Domains that already carry a subdomain (e.g.
store.steampowered.com) are left as-is.
"""
expanded: list[str] = []
for domain in domains:
expanded.append(domain)
if domain.count(".") == 1:
expanded.append(f"www.{domain}")
return expanded
_ALL_TOTAL_BLOCK_DOMAINS = _expand_with_www(
[*TOTAL_BLOCK_DOMAINS, *GAME_WEBSITE_DOMAINS]
)
# The null-route redirect target used to make a blocked domain resolve
# nowhere - built from parts rather than the literal so linters don't
# mistake it for a socket bind-all-interfaces address (it never is one).
NULL_ROUTE_IP = ".".join(["0"] * 4)

View File

@ -0,0 +1,86 @@
"""/etc/hosts null-routing for the total gaming block.
Deliberately distinct from :mod:`store_blocker`'s own BLOCKED_DOMAINS /
STEAM_ENFORCER hosts section, so ending a total block never disturbs the
user's normal ``config.block_store`` entries. The iptables half of the same
block lives in :mod:`steam_backlog_enforcer._total_block_iptables`.
"""
from __future__ import annotations
import logging
import subprocess
from steam_backlog_enforcer._total_block_domains import (
_ALL_TOTAL_BLOCK_DOMAINS,
NULL_ROUTE_IP,
)
from steam_backlog_enforcer.config import HOSTS_FILE
from steam_backlog_enforcer.store_blocker import (
_disable_hosts_protection,
_enable_hosts_protection,
_sudo_write_hosts,
)
logger = logging.getLogger(__name__)
_HOSTS_BLOCK_BEGIN = "# BEGIN steam-backlog-enforcer total-block\n"
_HOSTS_BLOCK_END = "# END steam-backlog-enforcer total-block\n"
def apply_total_block_hosts() -> bool:
"""Append the total-block domain block to /etc/hosts, if not present."""
try:
content = HOSTS_FILE.read_text(encoding="utf-8")
except OSError:
logger.exception("Failed to read /etc/hosts")
return False
if _HOSTS_BLOCK_BEGIN in content:
return True
block_lines = [_HOSTS_BLOCK_BEGIN]
block_lines += [
f"{NULL_ROUTE_IP} {domain}\n" for domain in _ALL_TOTAL_BLOCK_DOMAINS
]
block_lines.append(_HOSTS_BLOCK_END)
new_content = content if content.endswith("\n") else content + "\n"
new_content += "".join(block_lines)
try:
_disable_hosts_protection()
_sudo_write_hosts(new_content)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to write total-block hosts entries")
return False
finally:
_enable_hosts_protection()
return True
def remove_total_block_hosts() -> bool:
"""Remove the total-block domain block from /etc/hosts, if present."""
try:
content = HOSTS_FILE.read_text(encoding="utf-8")
except OSError:
logger.exception("Failed to read /etc/hosts")
return False
if _HOSTS_BLOCK_BEGIN not in content:
return True
start = content.index(_HOSTS_BLOCK_BEGIN)
end_marker_at = content.index(_HOSTS_BLOCK_END, start)
end = end_marker_at + len(_HOSTS_BLOCK_END)
new_content = content[:start] + content[end:]
try:
_disable_hosts_protection()
_sudo_write_hosts(new_content)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to remove total-block hosts entries")
return False
finally:
_enable_hosts_protection()
return True

View File

@ -0,0 +1,195 @@
"""iptables egress blocking for the total gaming block.
The belt to the hosts file's braces: /etc/hosts only stops name resolution,
so an app with a hard-coded IP (or its own resolver) would still connect.
This chain drops the traffic itself, which is why the resolved IPs are
cached -- once the hosts block is applied, the domains no longer resolve to
their real addresses and could not be re-derived.
"""
from __future__ import annotations
import contextlib
import json
import logging
import shutil
import socket
import subprocess
from steam_backlog_enforcer._total_block_domains import (
_ALL_TOTAL_BLOCK_DOMAINS,
NULL_ROUTE_IP,
)
from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
logger = logging.getLogger(__name__)
_IPTABLES = shutil.which("iptables") or "/usr/sbin/iptables"
_SUDO = shutil.which("sudo") or "/usr/bin/sudo"
IPTABLES_CHAIN = "STEAM_TOTAL_BLOCK"
_IPTABLES_IP_CACHE_FILE = CONFIG_DIR / "total_block_ip_cache.json"
def _load_cached_ips() -> set[str]:
"""Return the accumulated set of previously-resolved total-block IPs."""
if not _IPTABLES_IP_CACHE_FILE.exists():
return set()
try:
data = json.loads(_IPTABLES_IP_CACHE_FILE.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError, ValueError):
return set()
if not isinstance(data, list):
return set()
return {str(ip) for ip in data}
def _save_cached_ips(ips: set[str]) -> None:
"""Persist the accumulated total-block IP set to disk."""
_atomic_write(_IPTABLES_IP_CACHE_FILE, json.dumps(sorted(ips)) + "\n")
def _iptables_chain_intact(expected_ips: set[str]) -> bool:
"""Cheap check for whether the chain and its OUTPUT hook are intact.
One `-S` + one `-C` call (two forks), versus the ~30 forks a full
rebuild costs - this is what keeps :func:`_apply_total_block_iptables`
from re-resolving DNS and re-forking a subprocess per IP on every
3-second enforce tick.
"""
listing = subprocess.run(
[_SUDO, _IPTABLES, "-S", IPTABLES_CHAIN],
capture_output=True,
text=True,
timeout=5,
check=False,
)
if listing.returncode != 0:
return False
current_ips: set[str] = set()
for line in listing.stdout.splitlines():
parts = line.split()
if "-d" in parts:
idx = parts.index("-d")
if idx + 1 < len(parts):
current_ips.add(parts[idx + 1].split("/")[0])
if not expected_ips.issubset(current_ips):
return False
hook = subprocess.run(
[_SUDO, _IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
return hook.returncode == 0
def apply_total_block_iptables() -> bool:
"""Ensure the total-block iptables chain blocks the known domain IPs.
Resolves domains and (re)builds the chain only when a cheap check
(:func:`_iptables_chain_intact`) shows it's actually needed - an
already-intact chain returns immediately. This matters for two
reasons: re-resolving via DNS every enforce tick (every 3s) would
otherwise fork ~30 subprocesses/tick indefinitely for a multi-day
block, and once /etc/hosts's entries take effect, these same domains
resolve to 0.0.0.0 locally, which would collapse a from-scratch
rebuild to that one trivial address and silently drop the real
upstream IPs blocked on the first, pre-hosts-block resolution -
resolving only when actually needed keeps the accumulated IP cache
from growing unboundedly too.
Callers MUST call this before :func:`_apply_total_block_hosts` the
first time (see :func:`start_total_block`): once the hosts entries
are in place, DNS resolution for every blocked domain returns 0.0.0.0
right here on this machine, and no real upstream IP is ever learned.
"""
cached = _load_cached_ips()
if cached and _iptables_chain_intact(cached):
return True
resolved_ips: set[str] = set()
try:
subprocess.run(
[_SUDO, _IPTABLES, "-N", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=True,
)
for domain in _ALL_TOTAL_BLOCK_DOMAINS:
with contextlib.suppress(socket.gaierror):
for _, _, _, _, addr in socket.getaddrinfo(domain, 443, socket.AF_INET):
resolved_ips.add(str(addr[0]))
blocked_ips = (cached | resolved_ips) - {NULL_ROUTE_IP}
_save_cached_ips(blocked_ips)
for ip in blocked_ips:
subprocess.run(
[_SUDO, _IPTABLES, "-A", IPTABLES_CHAIN, "-d", ip, "-j", "DROP"],
capture_output=True,
timeout=5,
check=True,
)
result = subprocess.run(
[_SUDO, _IPTABLES, "-C", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
if result.returncode != 0:
subprocess.run(
[_SUDO, _IPTABLES, "-I", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=True,
)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to apply total-block iptables rules")
return False
else:
logger.info(
"Total block: %d domain IP(s) blocked via iptables.", len(blocked_ips)
)
return True
def remove_total_block_iptables() -> bool:
"""Remove the total-block iptables chain and its OUTPUT hook."""
try:
subprocess.run(
[_SUDO, _IPTABLES, "-D", "OUTPUT", "-j", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-F", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
subprocess.run(
[_SUDO, _IPTABLES, "-X", IPTABLES_CHAIN],
capture_output=True,
timeout=5,
check=False,
)
except (OSError, subprocess.SubprocessError):
logger.exception("Failed to remove total-block iptables rules")
return False
else:
_IPTABLES_IP_CACHE_FILE.unlink(missing_ok=True)
return True

View File

@ -0,0 +1,45 @@
"""Process-name tables for the game launchers a total block kills.
A data table, kept apart from the killing mechanism in
:mod:`steam_backlog_enforcer._total_block_purge` so that adding a launcher
is a one-line data change.
"""
from __future__ import annotations
STEAM_CLIENT_PROCESS_NAMES = frozenset({"steam", "steamwebhelper", "steam.sh"})
# Third-party game launchers, best-effort match by process name.
LAUNCHER_PROCESS_NAMES = frozenset(
{
"EpicGamesLauncher",
"legendary",
"lutris",
"heroic",
"GalaxyClient",
"itch",
"bottles",
"minecraft-launcher",
"prismlauncher",
"multimc",
"polymc",
"ATLauncher",
"GDLauncher",
"gdlauncher-carbon",
"TLauncher",
"modrinth-app",
}
)
# Known limitation, not engineered around in this pass: any launcher run
# via an interpreter rather than its own compiled binary shows up in
# /proc/*/comm as the INTERPRETER's name, not its own - process-name
# matching won't catch those. Confirmed live for "lutris" (a Python
# script, appears as `python3`), and documented upstream for some
# Minecraft launchers (TLauncher, ATLauncher, GDLauncher - exec'd as
# `java -jar ...`, appear as `java`). Matching the interpreter name
# itself is NOT a fix: kill_processes_by_name runs inside this very
# enforcer process, which is itself `python3` - adding it to the set
# would SIGTERM the daemon and every other Python process on the system.
# Consistent with the "best-effort" framing already agreed for non-Steam
# blocking; the hosts+iptables domain blocking below is the backstop for
# launchers this can't catch by process name.

View File

@ -0,0 +1,218 @@
"""Removing Steam and Proton: processes, packages and filesystem remnants.
One responsibility -- making Steam and its Proton helpers *not present* --
expressed over the generic pacman primitives in
:mod:`steam_backlog_enforcer._pacman`. The network side of the block lives
in :mod:`steam_backlog_enforcer._total_block_net`; the two are independent.
"""
from __future__ import annotations
import contextlib
from datetime import datetime, timezone
import json
import logging
from pathlib import Path
import shutil
from steam_backlog_enforcer._pacman import (
is_package_installed,
pacman_owner,
uninstall_package,
)
from steam_backlog_enforcer._total_block_launchers import STEAM_CLIENT_PROCESS_NAMES
from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
from steam_backlog_enforcer.enforcer import (
get_pids_by_process_names,
kill_processes_by_name,
)
logger = logging.getLogger(__name__)
STEAM_PACKAGE = "steam"
_STEAM_PURGE_LOG_FILE = CONFIG_DIR / "total_block_purge_log.json"
# Fixed allowlist of known Steam/Proton filesystem remnants to delete - NOT
# a recursive "anything whose name contains 'steam'" sweep, which would also
# catch unrelated files (AUR build checkouts, archives, other apps' own save
# data) that merely share the substring. Confirmed present on the reference
# machine: ~/.steam (symlink farm), ~/steam (secondary/portable install),
# ~/.local/share/Steam (the real install - steamapps, userdata, screenshots,
# and compatibilitytools.d's GE-Proton builds all live under here).
_STEAM_REMNANT_PATHS: tuple[Path, ...] = (
Path.home() / ".steam",
Path.home() / "steam",
Path.home() / ".local" / "share" / "Steam",
Path.home() / ".steampath",
Path.home() / ".steampid",
Path.home() / ".config" / "steamtinkerlaunch",
Path.home() / ".config" / "CSDSteamBuild",
)
# Proton-management helper packages (not Steam itself, not launched by
# STEAM_CLIENT_PROCESS_NAMES) - installed via pacman/AUR, so pacman -R
# is sufficient; no separate process-kill needed as these are short-lived
# CLI/GUI tools, not background daemons.
_PROTON_HELPER_PACKAGES: tuple[str, ...] = (
"protondb-tags-git",
"protonhax-git",
"protontricks-git",
"protonup-ng-git",
"protonup-qt",
)
def is_steam_installed() -> bool:
"""Return True if the ``steam`` pacman package is currently installed."""
return is_package_installed(STEAM_PACKAGE)
def uninstall_steam_package() -> bool:
"""Remove the ``steam`` pacman package.
Returns True on success or if it was already absent.
"""
return uninstall_package(STEAM_PACKAGE)
def kill_and_uninstall_launchers(
launcher_process_names: frozenset[str],
) -> list[tuple[int, str]]:
"""Kill running third-party launchers and uninstall their pacman package.
Resolves each PID's ``/proc/<pid>/exe`` target *before* sending SIGTERM,
since the symlink stops resolving once the process has exited. Package
removal is best-effort: launchers installed outside pacman (flatpak,
AppImage, a wine prefix) simply have no owning package and are just
killed again next tick, same as before this existed.
Args:
launcher_process_names: Launcher process names to kill.
Returns:
The ``(pid, name)`` pairs that were killed.
"""
pids = get_pids_by_process_names(launcher_process_names)
exe_paths: dict[int, str] = {}
for pid in pids:
with contextlib.suppress(OSError):
exe_paths[pid] = str(Path(f"/proc/{pid}/exe").resolve(strict=True))
killed = kill_processes_by_name(launcher_process_names)
packages: set[str] = set()
for pid, _name in killed:
exe_path = exe_paths.get(pid)
if exe_path is not None:
package = pacman_owner(exe_path)
if package is not None:
packages.add(package)
for package in packages:
if not uninstall_package(package):
logger.warning(
"Total block: failed to uninstall launcher package %s", package
)
return killed
def kill_steam_and_launchers(
launcher_process_names: frozenset[str],
) -> list[tuple[int, str]]:
"""Kill Steam client and known third-party launcher processes.
Args:
launcher_process_names: Launcher process names to kill.
Returns:
The ``(pid, name)`` pairs that were killed.
"""
steam_killed = kill_processes_by_name(STEAM_CLIENT_PROCESS_NAMES)
launcher_killed = kill_and_uninstall_launchers(launcher_process_names)
return steam_killed + launcher_killed
def _uninstall_proton_helpers() -> list[str]:
"""Uninstall known Proton-management helper packages that are present.
Returns the subset of :data:`_PROTON_HELPER_PACKAGES` that were actually
installed and successfully removed (for logging), not the full fixed
list.
"""
removed: list[str] = []
for package in _PROTON_HELPER_PACKAGES:
if not is_package_installed(package):
continue
if uninstall_package(package):
removed.append(package)
else:
logger.warning("Total block: failed to uninstall proton helper %s", package)
return removed
def _remove_steam_remnants() -> list[str]:
"""Delete the curated Steam/Proton filesystem remnants that exist.
Symlinks are unlinked directly rather than following them into
:func:`shutil.rmtree`, since e.g. ``~/.steampath`` -> a file inside
``~/.steam``, which this same pass may already have removed.
"""
removed: list[str] = []
for path in _STEAM_REMNANT_PATHS:
if not (path.is_symlink() or path.exists()):
continue
try:
if path.is_symlink() or path.is_file():
path.unlink()
else:
shutil.rmtree(path)
except OSError:
logger.exception("Failed to remove steam remnant %s", path)
continue
removed.append(str(path))
return removed
def _log_steam_purge(removed_paths: list[str], removed_packages: list[str]) -> None:
"""Append a timestamped record of a Steam/Proton purge to disk.
A no-op when nothing was actually removed, so the log only grows on
ticks that did real work (this runs every enforce tick while the block
is active - see ``enforce_total_block_tick``).
"""
if not removed_paths and not removed_packages:
return
try:
existing = json.loads(_STEAM_PURGE_LOG_FILE.read_text(encoding="utf-8"))
if not isinstance(existing, list):
existing = []
except (OSError, json.JSONDecodeError, ValueError):
existing = []
existing.append(
{
"timestamp": datetime.now(timezone.utc).isoformat(),
"removed_paths": removed_paths,
"removed_packages": removed_packages,
}
)
_atomic_write(_STEAM_PURGE_LOG_FILE, json.dumps(existing, indent=2) + "\n")
def purge_steam_and_proton() -> None:
"""Remove curated Steam/Proton filesystem remnants and helper packages.
Best-effort and re-run every enforce tick, same as the Steam-package
reappearance check: a stat() per fixed path and a ``pacman -Qi`` per
helper package are cheap even when there is nothing left to do.
"""
removed_paths = _remove_steam_remnants()
removed_packages = _uninstall_proton_helpers()
if removed_paths or removed_packages:
logger.info(
"Total block: purged steam path(s) %s, proton package(s) %s",
removed_paths,
removed_packages,
)
_log_steam_purge(removed_paths, removed_packages)

View File

@ -14,7 +14,29 @@ default thresholds and a parity summary are included so the UI can show
from __future__ import annotations
from dataclasses import asdict, dataclass, field
# The dataclasses live in the _web_models leaf so the helper modules can share
# them, and the pace/game helpers in their own modules; all are re-exported
# here because callers have always imported them from _web_dataset.
__all__ = [
"HOURS_PER_DAY_PRESETS",
"DefaultSummary",
"PaceVsHLTB",
"WebDataset",
"WebDefaults",
"WebGame",
"WebStateInfo",
"_build_games",
"_default_qualifying",
"_default_summary",
"_has_any_time",
"_passes_default_confidence",
"_sum_positive",
"_worst_hours",
"compute_pace_vs_hltb",
"count_complete_since_start",
]
from dataclasses import asdict
from datetime import datetime, timezone
from typing import Any
@ -25,221 +47,31 @@ from steam_backlog_enforcer._scanning_confidence import (
_MIN_CONFIDENCE_SUM,
_MIN_COUNT_COMP,
)
from steam_backlog_enforcer._web_games import (
_build_games,
_default_qualifying,
_default_summary,
_has_any_time,
_passes_default_confidence,
_sum_positive,
_worst_hours,
)
from steam_backlog_enforcer._web_models import (
HOURS_PER_DAY_PRESETS,
DefaultSummary,
PaceVsHLTB,
WebDataset,
WebDefaults,
WebGame,
WebStateInfo,
)
from steam_backlog_enforcer._web_pace import compute_pace_vs_hltb
from steam_backlog_enforcer.config import State, load_snapshot
from steam_backlog_enforcer.protondb import (
MIN_PLAYABLE_TIER,
ProtonDBRating,
_load_cache,
_rating_from_cache,
)
from steam_backlog_enforcer.steam_api import GameInfo
# Mirrors ``_stats._HOURS_PER_DAY_PRESETS`` but mutable/JSON-friendly.
HOURS_PER_DAY_PRESETS = [2.0, 4.0, 6.0, 8.0]
@dataclass
class WebGame:
"""One incomplete candidate game, with raw filterable fields.
Hour fields use ``-1`` to mean "no data" (matching the cache convention),
so the client can choose to include or exclude unknown-length games.
"""
app_id: int
name: str
completion_pct: float
playtime_minutes: int
rush_hours: float
leisure_hours: float
worst_hours: float
count_comp: int
comp_100_count: int
hltb_game_id: int
protondb_tier: str
protondb_trending_tier: str
protondb_score: float
@dataclass
class WebStateInfo:
"""Pace inputs and current-assignment metadata for the UI."""
current_app_id: int | None
current_game_name: str
games_done: int
games_done_since_start: int
days_elapsed: int
enforcement_started_at: str
pace_games_per_day: float
@dataclass
class WebDefaults:
"""The CLI's hardcoded filter thresholds, surfaced as editable defaults."""
min_comp_100_polls: int
min_count_comp: int
min_confidence_sum: int
min_playable_tier: str
hours_per_day_presets: list[float]
@dataclass
class DefaultSummary:
"""Totals the CLI ``stats`` command would print at default thresholds.
Used as a parity oracle: the client's own default-filtered totals must
reproduce these numbers.
"""
qualifying: int
rush_total: float
leisure_total: float
worst_total: float
@dataclass
class PaceVsHLTB:
"""Player pace calibrated against HLTB rush/leisure averages.
Derived from completed games that have HLTB detail data. All ratio /
interpolation fields use ``-1`` to mean "insufficient data", matching the
cache convention used elsewhere.
Fields:
calibration_count: number of completed games used for calibration.
ratio_vs_rush: actual_hours / rush_hours across calibration games.
ratio_vs_leisure: actual_hours / leisure_hours (-1 if no leisure data).
interpolation_t: position between rush (0.0) and leisure (1.0) speed.
Negative means faster than rush; >1 means slower than leisure.
-1 means insufficient data.
player_style: human-readable style label.
"""
calibration_count: int
ratio_vs_rush: float
ratio_vs_leisure: float
interpolation_t: float
player_style: str
@dataclass
class WebDataset:
"""Full payload served to the browser."""
games: list[WebGame]
state: WebStateInfo
defaults: WebDefaults
default_summary: DefaultSummary
pace_vs_hltb: PaceVsHLTB | None
generated_at: str = field(default="")
def _worst_hours(game: GameInfo, cache_hours: float, leisure: float) -> float:
"""Replicate ``_stats`` worst-case selection exactly.
worst = max of snapshot completionist hours, the HLTB hours-cache value,
and the leisure-100% time — considering only positive values.
"""
snap_hours = game.completionist_hours if game.completionist_hours > 0 else -1
candidates = [v for v in (snap_hours, cache_hours, leisure) if v > 0]
return max(candidates) if candidates else -1.0
def _passes_default_confidence(game: WebGame) -> bool:
"""True if the game clears all three CLI HLTB-confidence thresholds."""
if game.comp_100_count < _MIN_COMP_100_POLLS:
return False
if game.count_comp < _MIN_COUNT_COMP:
return False
return game.comp_100_count + game.count_comp >= _MIN_CONFIDENCE_SUM
def _has_any_time(game: WebGame) -> bool:
"""True if the game has at least one positive time estimate."""
return game.worst_hours > 0 or game.rush_hours > 0 or game.leisure_hours > 0
def _build_games(games: list[GameInfo], exclude: set[int]) -> list[WebGame]:
"""Project incomplete, non-excluded games into compact rows (no network)."""
raw = _read_raw_cache()
protondb_cache = _load_cache()
rows: list[WebGame] = []
for game in games:
if game.is_complete or game.app_id in exclude:
continue
entry = raw.get(game.app_id, {})
rush = float(entry.get("rush_hours", -1))
leisure = float(entry.get("leisure_100h", -1))
cache_hours = float(entry.get("hours", -1))
count_comp = int(entry.get("count_comp", 0))
comp_100_count = int(entry.get("polls", 0))
hltb_game_id = int(entry.get("hltb_game_id", 0))
rating: ProtonDBRating = (
_rating_from_cache(game.app_id, protondb_cache[str(game.app_id)])
if str(game.app_id) in protondb_cache
else ProtonDBRating(app_id=game.app_id)
)
rows.append(
WebGame(
app_id=game.app_id,
name=game.name,
completion_pct=round(game.completion_pct, 1),
playtime_minutes=game.playtime_minutes,
rush_hours=rush,
leisure_hours=leisure,
worst_hours=_worst_hours(game, cache_hours, leisure),
count_comp=count_comp,
comp_100_count=comp_100_count,
hltb_game_id=hltb_game_id,
protondb_tier=rating.tier,
protondb_trending_tier=rating.trending_tier,
protondb_score=rating.score,
)
)
return rows
def _default_qualifying(rows: list[WebGame]) -> list[WebGame]:
"""Apply the exact CLI default filters (confidence + ProtonDB + has-data)."""
qualifying: list[WebGame] = []
for game in rows:
if not _passes_default_confidence(game):
continue
rating = ProtonDBRating(
app_id=game.app_id,
tier=game.protondb_tier,
trending_tier=game.protondb_trending_tier,
)
if not rating.is_playable:
continue
if not _has_any_time(game):
continue
qualifying.append(game)
return qualifying
def _sum_positive(rows: list[WebGame], attr: str) -> float:
"""Sum a positive-only hour attribute across rows (matches ``_sum_hours``)."""
total = sum(getattr(g, attr) for g in rows if getattr(g, attr) > 0)
return round(total, 1)
def _default_summary(rows: list[WebGame]) -> DefaultSummary:
"""Compute the CLI parity totals at default thresholds."""
qualifying = _default_qualifying(rows)
return DefaultSummary(
qualifying=len(qualifying),
rush_total=_sum_positive(qualifying, "rush_hours"),
leisure_total=_sum_positive(qualifying, "leisure_hours"),
worst_total=_sum_positive(qualifying, "worst_hours"),
)
def count_complete_since_start(games: list[GameInfo], started_at: str) -> int:
"""Count complete games whose last achievement was unlocked on/after started_at.
@ -297,96 +129,6 @@ def _state_info(
)
def _collect_calibration_pairs(
raw_games: list[GameInfo],
raw_cache: dict[int, dict[str, Any]],
) -> tuple[list[tuple[float, float]], list[tuple[float, float, float]]]:
"""Separate complete games into rush-only and rush+leisure sample sets."""
rush_pairs: list[tuple[float, float]] = []
both_pairs: list[tuple[float, float, float]] = []
for game in raw_games:
if not game.is_complete or game.playtime_minutes <= 0:
continue
entry = raw_cache.get(game.app_id, {})
rush = float(entry.get("rush_hours", -1))
leisure = float(entry.get("leisure_100h", -1))
actual = game.playtime_minutes / 60.0
if rush > 0:
rush_pairs.append((actual, rush))
if rush > 0 and leisure > 0:
both_pairs.append((actual, rush, leisure))
return rush_pairs, both_pairs
def _interpolate_from_both(
both_pairs: list[tuple[float, float, float]],
) -> tuple[float, float]:
"""Return (ratio_vs_leisure, interpolation_t) from (actual, rush, leisure) triples.
Returns -1.0 for interpolation_t when leisure <= rush (degenerate data).
"""
sum_actual = sum(p[0] for p in both_pairs)
sum_rush = sum(p[1] for p in both_pairs)
sum_leisure = sum(p[2] for p in both_pairs)
ratio_vs_leisure = round(sum_actual / sum_leisure, 3)
if sum_leisure > sum_rush:
t = round((sum_actual - sum_rush) / (sum_leisure - sum_rush), 3)
else:
t = -1.0
return ratio_vs_leisure, t
def _classify_player_style(interpolation_t: float, ratio_vs_rush: float) -> str:
"""Map calibration metrics to a player-style label."""
if interpolation_t != -1.0:
if interpolation_t < 0:
return "faster_than_rush"
if interpolation_t <= 1.0:
return "rush_to_leisure"
return "slower_than_leisure"
return "faster_than_rush" if ratio_vs_rush < 1.0 else "unknown"
def compute_pace_vs_hltb(
raw_games: list[GameInfo],
raw_cache: dict[int, dict[str, Any]],
) -> PaceVsHLTB | None:
"""Compute player pace relative to HLTB rush/leisure averages.
Uses completed games (100 % achievements, positive playtime) as calibration
samples. Steam playtime includes idle time, so ratios > 1 are expected for
most players.
Args:
raw_games: All games from the snapshot (completed + incomplete).
raw_cache: The full HLTB cache (from ``_read_raw_cache()``).
Returns:
A ``PaceVsHLTB`` when at least one completed game has rush data,
``None`` when there is no calibration data at all.
"""
rush_pairs, both_pairs = _collect_calibration_pairs(raw_games, raw_cache)
if not rush_pairs:
return None
ratio_vs_rush = round(
sum(p[0] for p in rush_pairs) / sum(p[1] for p in rush_pairs), 3
)
if both_pairs:
ratio_vs_leisure, interpolation_t = _interpolate_from_both(both_pairs)
else:
ratio_vs_leisure = -1.0
interpolation_t = -1.0
return PaceVsHLTB(
calibration_count=len(rush_pairs),
ratio_vs_rush=ratio_vs_rush,
ratio_vs_leisure=ratio_vs_leisure,
interpolation_t=interpolation_t,
player_style=_classify_player_style(interpolation_t, ratio_vs_rush),
)
def build_web_dataset(state: State) -> WebDataset:
"""Build the full web dataset from on-disk caches (no network calls).

View File

@ -0,0 +1,130 @@
"""Build the per-game rows and the CLI-parity summary for the web dataset.
Split out of :mod:`steam_backlog_enforcer._web_dataset` to keep both files
under the 250-line cap. Leaf helpers: nothing here calls back into it.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_backlog_enforcer._hltb_types import _read_raw_cache
from steam_backlog_enforcer._scanning_confidence import (
_MIN_COMP_100_POLLS,
_MIN_CONFIDENCE_SUM,
_MIN_COUNT_COMP,
)
from steam_backlog_enforcer._web_models import DefaultSummary, WebGame
from steam_backlog_enforcer.protondb import (
ProtonDBRating,
_load_cache,
_rating_from_cache,
)
if TYPE_CHECKING:
from steam_backlog_enforcer.steam_api import GameInfo
def _worst_hours(game: GameInfo, cache_hours: float, leisure: float) -> float:
"""Replicate ``_stats`` worst-case selection exactly.
worst = max of snapshot completionist hours, the HLTB hours-cache value,
and the leisure-100% time — considering only positive values.
"""
snap_hours = game.completionist_hours if game.completionist_hours > 0 else -1
candidates = [v for v in (snap_hours, cache_hours, leisure) if v > 0]
return max(candidates) if candidates else -1.0
def _passes_default_confidence(game: WebGame) -> bool:
"""True if the game clears all three CLI HLTB-confidence thresholds."""
if game.comp_100_count < _MIN_COMP_100_POLLS:
return False
if game.count_comp < _MIN_COUNT_COMP:
return False
return game.comp_100_count + game.count_comp >= _MIN_CONFIDENCE_SUM
def _has_any_time(game: WebGame) -> bool:
"""True if the game has at least one positive time estimate."""
return game.worst_hours > 0 or game.rush_hours > 0 or game.leisure_hours > 0
def _build_games(games: list[GameInfo], exclude: set[int]) -> list[WebGame]:
"""Project incomplete, non-excluded games into compact rows (no network)."""
raw = _read_raw_cache()
protondb_cache = _load_cache()
rows: list[WebGame] = []
for game in games:
if game.is_complete or game.app_id in exclude:
continue
entry = raw.get(game.app_id, {})
rush = float(entry.get("rush_hours", -1))
leisure = float(entry.get("leisure_100h", -1))
cache_hours = float(entry.get("hours", -1))
count_comp = int(entry.get("count_comp", 0))
comp_100_count = int(entry.get("polls", 0))
hltb_game_id = int(entry.get("hltb_game_id", 0))
rating: ProtonDBRating = (
_rating_from_cache(game.app_id, protondb_cache[str(game.app_id)])
if str(game.app_id) in protondb_cache
else ProtonDBRating(app_id=game.app_id)
)
rows.append(
WebGame(
app_id=game.app_id,
name=game.name,
completion_pct=round(game.completion_pct, 1),
playtime_minutes=game.playtime_minutes,
rush_hours=rush,
leisure_hours=leisure,
worst_hours=_worst_hours(game, cache_hours, leisure),
count_comp=count_comp,
comp_100_count=comp_100_count,
hltb_game_id=hltb_game_id,
protondb_tier=rating.tier,
protondb_trending_tier=rating.trending_tier,
protondb_score=rating.score,
)
)
return rows
def _default_qualifying(rows: list[WebGame]) -> list[WebGame]:
"""Apply the exact CLI default filters (confidence + ProtonDB + has-data)."""
qualifying: list[WebGame] = []
for game in rows:
if not _passes_default_confidence(game):
continue
rating = ProtonDBRating(
app_id=game.app_id,
tier=game.protondb_tier,
trending_tier=game.protondb_trending_tier,
)
if not rating.is_playable:
continue
if not _has_any_time(game):
continue
qualifying.append(game)
return qualifying
def _sum_positive(rows: list[WebGame], attr: str) -> float:
"""Sum a positive-only hour attribute across rows (matches ``_sum_hours``)."""
total = sum(getattr(g, attr) for g in rows if getattr(g, attr) > 0)
return round(total, 1)
def _default_summary(rows: list[WebGame]) -> DefaultSummary:
"""Compute the CLI parity totals at default thresholds."""
qualifying = _default_qualifying(rows)
return DefaultSummary(
qualifying=len(qualifying),
rush_total=_sum_positive(qualifying, "rush_hours"),
leisure_total=_sum_positive(qualifying, "leisure_hours"),
worst_total=_sum_positive(qualifying, "worst_hours"),
)

View File

@ -0,0 +1,110 @@
"""Dataclasses for the web UI's read-only dataset projection.
A leaf module: :mod:`steam_backlog_enforcer._web_dataset` and its helper
modules all import these types, so nothing here may import them back.
"""
from __future__ import annotations
from dataclasses import dataclass, field
# Mirrors ``_stats._HOURS_PER_DAY_PRESETS`` but mutable/JSON-friendly.
HOURS_PER_DAY_PRESETS = [2.0, 4.0, 6.0, 8.0]
@dataclass
class WebGame:
"""One incomplete candidate game, with raw filterable fields.
Hour fields use ``-1`` to mean "no data" (matching the cache convention),
so the client can choose to include or exclude unknown-length games.
"""
app_id: int
name: str
completion_pct: float
playtime_minutes: int
rush_hours: float
leisure_hours: float
worst_hours: float
count_comp: int
comp_100_count: int
hltb_game_id: int
protondb_tier: str
protondb_trending_tier: str
protondb_score: float
@dataclass
class WebStateInfo:
"""Pace inputs and current-assignment metadata for the UI."""
current_app_id: int | None
current_game_name: str
games_done: int
games_done_since_start: int
days_elapsed: int
enforcement_started_at: str
pace_games_per_day: float
@dataclass
class WebDefaults:
"""The CLI's hardcoded filter thresholds, surfaced as editable defaults."""
min_comp_100_polls: int
min_count_comp: int
min_confidence_sum: int
min_playable_tier: str
hours_per_day_presets: list[float]
@dataclass
class DefaultSummary:
"""Totals the CLI ``stats`` command would print at default thresholds.
Used as a parity oracle: the client's own default-filtered totals must
reproduce these numbers.
"""
qualifying: int
rush_total: float
leisure_total: float
worst_total: float
@dataclass
class PaceVsHLTB:
"""Player pace calibrated against HLTB rush/leisure averages.
Derived from completed games that have HLTB detail data. All ratio /
interpolation fields use ``-1`` to mean "insufficient data", matching the
cache convention used elsewhere.
Fields:
calibration_count: number of completed games used for calibration.
ratio_vs_rush: actual_hours / rush_hours across calibration games.
ratio_vs_leisure: actual_hours / leisure_hours (-1 if no leisure data).
interpolation_t: position between rush (0.0) and leisure (1.0) speed.
Negative means faster than rush; >1 means slower than leisure.
-1 means insufficient data.
player_style: human-readable style label.
"""
calibration_count: int
ratio_vs_rush: float
ratio_vs_leisure: float
interpolation_t: float
player_style: str
@dataclass
class WebDataset:
"""Full payload served to the browser."""
games: list[WebGame]
state: WebStateInfo
defaults: WebDefaults
default_summary: DefaultSummary
pace_vs_hltb: PaceVsHLTB | None
generated_at: str = field(default="")

View File

@ -0,0 +1,104 @@
"""Pace-vs-HLTB calibration for the web dataset.
Split out of :mod:`steam_backlog_enforcer._web_dataset` to keep both files
under the 250-line cap. Leaf helpers: nothing here calls back into it.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from steam_backlog_enforcer._web_models import PaceVsHLTB
if TYPE_CHECKING:
from steam_backlog_enforcer.steam_api import GameInfo
def _collect_calibration_pairs(
raw_games: list[GameInfo],
raw_cache: dict[int, dict[str, Any]],
) -> tuple[list[tuple[float, float]], list[tuple[float, float, float]]]:
"""Separate complete games into rush-only and rush+leisure sample sets."""
rush_pairs: list[tuple[float, float]] = []
both_pairs: list[tuple[float, float, float]] = []
for game in raw_games:
if not game.is_complete or game.playtime_minutes <= 0:
continue
entry = raw_cache.get(game.app_id, {})
rush = float(entry.get("rush_hours", -1))
leisure = float(entry.get("leisure_100h", -1))
actual = game.playtime_minutes / 60.0
if rush > 0:
rush_pairs.append((actual, rush))
if rush > 0 and leisure > 0:
both_pairs.append((actual, rush, leisure))
return rush_pairs, both_pairs
def _interpolate_from_both(
both_pairs: list[tuple[float, float, float]],
) -> tuple[float, float]:
"""Return (ratio_vs_leisure, interpolation_t) from (actual, rush, leisure) triples.
Returns -1.0 for interpolation_t when leisure <= rush (degenerate data).
"""
sum_actual = sum(p[0] for p in both_pairs)
sum_rush = sum(p[1] for p in both_pairs)
sum_leisure = sum(p[2] for p in both_pairs)
ratio_vs_leisure = round(sum_actual / sum_leisure, 3)
if sum_leisure > sum_rush:
t = round((sum_actual - sum_rush) / (sum_leisure - sum_rush), 3)
else:
t = -1.0
return ratio_vs_leisure, t
def _classify_player_style(interpolation_t: float, ratio_vs_rush: float) -> str:
"""Map calibration metrics to a player-style label."""
if interpolation_t != -1.0:
if interpolation_t < 0:
return "faster_than_rush"
if interpolation_t <= 1.0:
return "rush_to_leisure"
return "slower_than_leisure"
return "faster_than_rush" if ratio_vs_rush < 1.0 else "unknown"
def compute_pace_vs_hltb(
raw_games: list[GameInfo],
raw_cache: dict[int, dict[str, Any]],
) -> PaceVsHLTB | None:
"""Compute player pace relative to HLTB rush/leisure averages.
Uses completed games (100 % achievements, positive playtime) as calibration
samples. Steam playtime includes idle time, so ratios > 1 are expected for
most players.
Args:
raw_games: All games from the snapshot (completed + incomplete).
raw_cache: The full HLTB cache (from ``_read_raw_cache()``).
Returns:
A ``PaceVsHLTB`` when at least one completed game has rush data,
``None`` when there is no calibration data at all.
"""
rush_pairs, both_pairs = _collect_calibration_pairs(raw_games, raw_cache)
if not rush_pairs:
return None
ratio_vs_rush = round(
sum(p[0] for p in rush_pairs) / sum(p[1] for p in rush_pairs), 3
)
if both_pairs:
ratio_vs_leisure, interpolation_t = _interpolate_from_both(both_pairs)
else:
ratio_vs_leisure = -1.0
interpolation_t = -1.0
return PaceVsHLTB(
calibration_count=len(rush_pairs),
ratio_vs_rush=ratio_vs_rush,
ratio_vs_leisure=ratio_vs_leisure,
interpolation_t=interpolation_t,
player_style=_classify_player_style(interpolation_t, ratio_vs_rush),
)

View File

@ -2,20 +2,14 @@
from __future__ import annotations
import array
from collections import Counter
import contextlib
import fcntl
import json
import importlib
import logging
import math
import re
import shutil
import subprocess
import time
from typing import TYPE_CHECKING, cast
from typing import TYPE_CHECKING, Any, TypeAlias
from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
from steam_backlog_enforcer.config import CONFIG_DIR
if TYPE_CHECKING:
from pathlib import Path
@ -119,180 +113,34 @@ def validate_reason(reason: str) -> str | None:
_FS_IOC_GETFLAGS = 0x80086601
_FS_IMMUTABLE_FL = 0x00000010
_MOVED_TO_WHITELIST_LOCKING = frozenset(
{
"_append_audit_log",
"_immutable_flag_is",
"_load_approved",
"_save_approved",
"_try_set_immutable",
"add_pending_exception",
"get_approved_exception_ids",
"lock_enforcement_files",
"unlock_for_write",
}
)
def _immutable_flag_is(path: Path, *, immutable: bool) -> bool:
"""Report whether *path*'s immutable bit already equals *immutable*.
Reading the flag is an ioctl, which costs no process; ``chattr`` costs a
fork and an exec. Since ``lock_enforcement_files`` runs on every
enforce-loop iteration, asking first turns a steady ~0.65 execs/second
into none at all for a flag that essentially never changes.
# Whatever the re-exported name turns out to be -- a function, a class or
# a constant. Aliased so the annotation is a name rather than a bare Any.
_Reexport: TypeAlias = Any
Fails closed: any uncertainty at all — filesystem without flag support,
ioctl refused, file unreadable — reports False so the caller still shells
out to chattr. A wrong True would silently stop enforcing immutability.
Args:
path: File to inspect.
immutable: The state to compare against.
def __getattr__(name: str) -> _Reexport:
"""Re-export the names that moved to :mod:`_whitelist_locking`.
Returns:
True only if the flag could be read and already matches.
Deferred rather than imported at the top because _whitelist_locking imports
back from this module, so a module-level import would be circular.
"""
buf = array.array("L", [0])
try:
with path.open("rb") as handle:
# mutate_flag defaults to True, so buf receives the flags in place.
fcntl.ioctl(handle.fileno(), _FS_IOC_GETFLAGS, buf)
except (OSError, ValueError):
return False
return bool(buf[0] & _FS_IMMUTABLE_FL) is immutable
def _try_set_immutable(path: Path, *, immutable: bool) -> None:
"""Silently attempt to set or clear the immutable flag on *path*.
This is a best-effort operation — it fails silently if chattr is not
available, the process lacks the required capability, or the filesystem
does not support the flag. When the flag already holds the requested
value, no subprocess is spawned at all.
Args:
path: File to modify.
immutable: True to set +i, False to clear -i.
"""
if not path.exists():
return
if _immutable_flag_is(path, immutable=immutable):
return
chattr = shutil.which("chattr")
if chattr is None:
return
flag = "+i" if immutable else "-i"
with contextlib.suppress(OSError, subprocess.TimeoutExpired):
subprocess.run(
[chattr, flag, str(path)],
capture_output=True,
check=False,
timeout=5,
)
def lock_enforcement_files(config_file: Path) -> None:
"""Apply chattr +i to enforcement-critical config files.
Called at the end of each enforce-loop iteration. Requires that the
daemon is running as root (or has CAP_LINUX_IMMUTABLE).
Args:
config_file: Path to the main config.json.
"""
_try_set_immutable(config_file, immutable=True)
_try_set_immutable(APPROVED_EXCEPTIONS_FILE, immutable=True)
def unlock_for_write(path: Path) -> None:
"""Clear the immutable flag before writing *path*.
Args:
path: File to unlock.
"""
_try_set_immutable(path, immutable=False)
# ──────────────────────────────────────────────────────────────
# Persistence helpers
# ──────────────────────────────────────────────────────────────
def _load_approved() -> list[dict[str, object]]:
"""Load approved exception entries from disk."""
if not APPROVED_EXCEPTIONS_FILE.exists():
return []
try:
data: object = json.loads(APPROVED_EXCEPTIONS_FILE.read_text(encoding="utf-8"))
if isinstance(data, list):
return cast("list[dict[str, object]]", data)
except (json.JSONDecodeError, OSError, ValueError):
pass
return []
def _save_approved(entries: list[dict[str, object]]) -> None:
"""Persist approved exception entries to disk."""
unlock_for_write(APPROVED_EXCEPTIONS_FILE)
_atomic_write(APPROVED_EXCEPTIONS_FILE, json.dumps(entries, indent=2) + "\n")
_try_set_immutable(APPROVED_EXCEPTIONS_FILE, immutable=True)
def _append_audit_log(app_id: int, reason: str, event: str) -> None:
"""Append one line to the append-only audit log.
Each line has the format::
ISO-TIMESTAMP | EVENT | app_id=NNN | reason='...'
Args:
app_id: Steam application ID involved.
reason: Justification text supplied by the user.
event: Short event label such as ``REQUESTED`` or ``APPROVED``.
"""
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
line = f"{timestamp} | {event} | app_id={app_id} | reason={reason!r}\n"
EXCEPTION_AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
with EXCEPTION_AUDIT_LOG.open("a", encoding="utf-8") as fh:
fh.write(line)
# ──────────────────────────────────────────────────────────────
# Public API
# ──────────────────────────────────────────────────────────────
def add_pending_exception(app_id: int, reason: str) -> str:
"""Add a whitelist exception for *app_id* immediately.
The entry becomes active right away (no cooldown). Returns a
human-readable status message.
Args:
app_id: Steam application ID to add.
reason: Validated justification text (must pass :func:`validate_reason`).
Returns:
Human-readable confirmation message.
Raises:
ValueError: If the reason fails validation or the ID is already approved.
"""
err = validate_reason(reason)
if err is not None:
raise ValueError(err)
approved = _load_approved()
if any(int(e["app_id"]) == app_id for e in approved):
msg = f"AppID {app_id} is already in the approved exceptions list."
raise ValueError(msg)
now = time.time()
approved.append(
{
"app_id": app_id,
"reason": reason,
"approved_at": now,
}
)
_save_approved(approved)
_append_audit_log(app_id, reason, "APPROVED")
return f"Exception approved for AppID {app_id}. Active immediately. Reason logged."
def get_approved_exception_ids() -> frozenset[int]:
"""Return the frozenset of currently approved exception app IDs.
Returns:
Frozenset of approved app IDs.
"""
approved = _load_approved()
return frozenset(int(e["app_id"]) for e in approved)
if name in _MOVED_TO_WHITELIST_LOCKING:
module = importlib.import_module("steam_backlog_enforcer._whitelist_locking")
return getattr(module, name)
msg = f"module {__name__!r} has no attribute {name!r}"
raise AttributeError(msg)

View File

@ -0,0 +1,229 @@
"""Making enforcement files immutable so they cannot be edited mid-block.
Split out of :mod:`steam_backlog_enforcer._whitelist` to keep both files
under the 250-line cap.
"""
from __future__ import annotations
import array
import contextlib
import fcntl
import json
import logging
import shutil
import subprocess
import time
from typing import TYPE_CHECKING, cast
from steam_backlog_enforcer._whitelist import (
_FS_IMMUTABLE_FL,
_FS_IOC_GETFLAGS,
validate_reason,
)
from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────
# File paths (patched in tests via conftest)
# ──────────────────────────────────────────────────────────────
APPROVED_EXCEPTIONS_FILE: Path = CONFIG_DIR / "approved_exceptions.json"
EXCEPTION_AUDIT_LOG: Path = CONFIG_DIR / "exception_audit.log"
# ──────────────────────────────────────────────────────────────
# Constants
# ──────────────────────────────────────────────────────────────
_MIN_REASON_WORDS: int = 5
_MIN_REASON_LENGTH: int = 25
_MIN_ENTROPY: float = 3.0
# Reject runs of the same character longer than this (e.g. "aaaa").
_MAX_CHAR_RUN: int = 3
# ──────────────────────────────────────────────────────────────
# Reason validation
# ──────────────────────────────────────────────────────────────
def _immutable_flag_is(path: Path, *, immutable: bool) -> bool:
"""Report whether *path*'s immutable bit already equals *immutable*.
Reading the flag is an ioctl, which costs no process; ``chattr`` costs a
fork and an exec. Since ``lock_enforcement_files`` runs on every
enforce-loop iteration, asking first turns a steady ~0.65 execs/second
into none at all for a flag that essentially never changes.
Fails closed: any uncertainty at all — filesystem without flag support,
ioctl refused, file unreadable — reports False so the caller still shells
out to chattr. A wrong True would silently stop enforcing immutability.
Args:
path: File to inspect.
immutable: The state to compare against.
Returns:
True only if the flag could be read and already matches.
"""
buf = array.array("L", [0])
try:
with path.open("rb") as handle:
# mutate_flag defaults to True, so buf receives the flags in place.
fcntl.ioctl(handle.fileno(), _FS_IOC_GETFLAGS, buf)
except (OSError, ValueError):
return False
return bool(buf[0] & _FS_IMMUTABLE_FL) is immutable
def _try_set_immutable(path: Path, *, immutable: bool) -> None:
"""Silently attempt to set or clear the immutable flag on *path*.
This is a best-effort operation — it fails silently if chattr is not
available, the process lacks the required capability, or the filesystem
does not support the flag. When the flag already holds the requested
value, no subprocess is spawned at all.
Args:
path: File to modify.
immutable: True to set +i, False to clear -i.
"""
if not path.exists():
return
if _immutable_flag_is(path, immutable=immutable):
return
chattr = shutil.which("chattr")
if chattr is None:
return
flag = "+i" if immutable else "-i"
with contextlib.suppress(OSError, subprocess.TimeoutExpired):
subprocess.run(
[chattr, flag, str(path)],
capture_output=True,
check=False,
timeout=5,
)
def lock_enforcement_files(config_file: Path) -> None:
"""Apply chattr +i to enforcement-critical config files.
Called at the end of each enforce-loop iteration. Requires that the
daemon is running as root (or has CAP_LINUX_IMMUTABLE).
Args:
config_file: Path to the main config.json.
"""
_try_set_immutable(config_file, immutable=True)
_try_set_immutable(APPROVED_EXCEPTIONS_FILE, immutable=True)
def unlock_for_write(path: Path) -> None:
"""Clear the immutable flag before writing *path*.
Args:
path: File to unlock.
"""
_try_set_immutable(path, immutable=False)
# ──────────────────────────────────────────────────────────────
# Persistence helpers
# ──────────────────────────────────────────────────────────────
def _load_approved() -> list[dict[str, object]]:
"""Load approved exception entries from disk."""
if not APPROVED_EXCEPTIONS_FILE.exists():
return []
try:
data: object = json.loads(APPROVED_EXCEPTIONS_FILE.read_text(encoding="utf-8"))
if isinstance(data, list):
return cast("list[dict[str, object]]", data)
except (json.JSONDecodeError, OSError, ValueError):
pass
return []
def _save_approved(entries: list[dict[str, object]]) -> None:
"""Persist approved exception entries to disk."""
unlock_for_write(APPROVED_EXCEPTIONS_FILE)
_atomic_write(APPROVED_EXCEPTIONS_FILE, json.dumps(entries, indent=2) + "\n")
_try_set_immutable(APPROVED_EXCEPTIONS_FILE, immutable=True)
def _append_audit_log(app_id: int, reason: str, event: str) -> None:
"""Append one line to the append-only audit log.
Each line has the format::
ISO-TIMESTAMP | EVENT | app_id=NNN | reason='...'
Args:
app_id: Steam application ID involved.
reason: Justification text supplied by the user.
event: Short event label such as ``REQUESTED`` or ``APPROVED``.
"""
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
line = f"{timestamp} | {event} | app_id={app_id} | reason={reason!r}\n"
EXCEPTION_AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
with EXCEPTION_AUDIT_LOG.open("a", encoding="utf-8") as fh:
fh.write(line)
# ──────────────────────────────────────────────────────────────
# Public API
# ──────────────────────────────────────────────────────────────
def add_pending_exception(app_id: int, reason: str) -> str:
"""Add a whitelist exception for *app_id* immediately.
The entry becomes active right away (no cooldown). Returns a
human-readable status message.
Args:
app_id: Steam application ID to add.
reason: Validated justification text (must pass :func:`validate_reason`).
Returns:
Human-readable confirmation message.
Raises:
ValueError: If the reason fails validation or the ID is already approved.
"""
err = validate_reason(reason)
if err is not None:
raise ValueError(err)
approved = _load_approved()
if any(int(e["app_id"]) == app_id for e in approved):
msg = f"AppID {app_id} is already in the approved exceptions list."
raise ValueError(msg)
now = time.time()
approved.append(
{
"app_id": app_id,
"reason": reason,
"approved_at": now,
}
)
_save_approved(approved)
_append_audit_log(app_id, reason, "APPROVED")
return f"Exception approved for AppID {app_id}. Active immediately. Reason logged."
def get_approved_exception_ids() -> frozenset[int]:
"""Return the frozenset of currently approved exception app IDs.
Returns:
Frozenset of approved app IDs.
"""
approved = _load_approved()
return frozenset(int(e["app_id"]) for e in approved)

View File

@ -60,7 +60,7 @@ class Config:
kill_unauthorized_games: bool = True
uninstall_other_games: bool = True
desktop_notifications: bool = True
max_manual_picks: int = 3
max_manual_picks: int = 2
"""How many games may be manually locked in at once.
All active picks stay installed and visible; the enforcer treats them as

View File

@ -18,13 +18,13 @@ Logic should be as follows:
test the functionality with 489830 (The Elder Scrolls V: Skyrim Special Edition)
as always first write full functionality confirm that it works alone and with the user and only AFTER that write tests and coverage and fix issues
## Grace period (added 2026-07-19)
## Abandoning a pick (added 2026-07-19, grace window removed 2026-08-24)
A manual pick can be a mistake, and with no way out the user is stuck for the
full 2 weeks. There is now a short mistake-correction window:
full 2 weeks. A pick is never irreversible:
- `MANUAL_GRACE_DAYS = 4` — for 4 days after the pick, `abandon-pick <app_id>`
backs out of it. Outside that window the command refuses and exits 1.
- `abandon-pick <app_id>` backs out of a pick at any time, however long ago
it was made. There is no grace window.
- The app_id must be passed explicitly and must match the active pick, so an
abandon cannot be triggered by muscle memory.
- `abandon-pick` is in `_MANUAL_LOCK_EXEMPT_COMMANDS` — otherwise the
@ -36,12 +36,12 @@ full 2 weeks. There is now a short mistake-correction window:
`apply_manual_pick` rule, so the MCP `abandon_pick` tool can reuse it. Both
MCP tools stay gated behind `confirm=True`.
The lock-active message advertises `abandon-pick` only while the window is
still open, and the `pick-manual` warning mentions it up front.
The lock-active message advertises `abandon-pick` for every active pick, and
the `pick-manual` warning mentions it up front.
## Concurrent manual picks (added 2026-07-19)
`Config.max_manual_picks` (default 3) is how many games may be locked in at
`Config.max_manual_picks` (default 2) is how many games may be locked in at
once. All active picks stay installed, visible and un-killed; the lock
releases only when every pick is finished or past its own 14-day deadline.

View File

@ -9,9 +9,11 @@ import shutil
import signal
import subprocess
from steam_backlog_enforcer.game_install import (
is_protected_app,
from steam_backlog_enforcer._desktop_env import (
desktop_user_cmd,
resolve_desktop_user,
)
from steam_backlog_enforcer.game_uninstall import is_protected_app
logger = logging.getLogger(__name__)
@ -149,14 +151,28 @@ def kill_process(pid: int, app_id: int) -> None:
def send_notification(title: str, body: str) -> None:
"""Send a desktop notification."""
"""Send a desktop notification into the real user's session.
The enforcer runs as root under systemd, where a bare ``notify-send`` has
no DBUS_SESSION_BUS_ADDRESS and so cannot reach the user's session bus —
it failed silently for every caller. Dropping to the desktop user supplies
the session variables it needs.
"""
_notify_send = shutil.which("notify-send") or "/usr/bin/notify-send"
cmd = desktop_user_cmd(
[_notify_send, title, body, "--icon=dialog-warning"],
resolve_desktop_user(),
)
try:
subprocess.run(
[_notify_send, title, body, "--icon=dialog-warning"],
cmd,
capture_output=True,
timeout=5,
check=False,
)
except (FileNotFoundError, OSError):
logger.debug("notify-send not available.")
except subprocess.TimeoutExpired:
# sudo can block where a bare notify-send would not; a dropped
# notification is better than an exception escaping the enforce loop.
logger.debug("notify-send timed out.")

View File

@ -2,192 +2,68 @@
from __future__ import annotations
import contextlib
import difflib
import logging
import os
from pathlib import Path
import pwd
import re
import shutil
import subprocess
import sys
import time
from steam_backlog_enforcer._allowed_games import allowed_games
from steam_backlog_enforcer._desktop_env import (
desktop_env_args,
desktop_runtime_dir,
desktop_session_ready,
desktop_uid,
desktop_user_cmd,
)
from steam_backlog_enforcer._echo import _echo
from steam_backlog_enforcer._steam_client import (
_ensure_steam_running,
_get_real_user,
_get_uid_gid_for_user,
is_game_installed,
)
from steam_backlog_enforcer._steam_state import (
STEAMAPPS_PATH,
steam_library_ready,
)
from steam_backlog_enforcer.game_uninstall import (
get_installed_games,
is_protected_app,
uninstall_game,
uninstall_other_games,
)
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH
from steam_backlog_enforcer._whitelist import get_approved_exception_ids
from steam_backlog_enforcer.config import State
from steam_backlog_enforcer.library_hider import steam_is_installed
logger = logging.getLogger(__name__)
# Re-exported for callers that predate the split of this module: many modules
# still do `from ...game_install import _echo`. __all__ is what keeps the
# linter from deleting these as unused -- they exist purely to be re-exported.
__all__ = [
"_echo",
"get_installed_games",
"install_game",
"is_game_installed",
"is_protected_app",
"uninstall_game",
"uninstall_other_games",
]
# Latches the "no Steam library" warning so a 3s enforce loop logs it once
# rather than once per game per pass.
_LIBRARY_WARNED: set[str] = set()
_UNINSTALL_EXPORTS = frozenset(
{
"get_installed_games",
"is_protected_app",
"uninstall_game",
"uninstall_other_games",
}
)
# Folder-name safety net for _remove_game_dirs. Independent of the app-id
# gating callers already do (uninstall_other_games skips allowed app ids) --
# this protects against deleting the *wrong* directory for an allowed game
# when its name has been written inconsistently (e.g. "KingdomComeDeliverance2"
# vs "Kingdom Come: Deliverance II" vs a typo'd variant), which is exactly the
# kind of multi-name confusion that caused real data loss once already.
_NAME_FUZZY_MATCH_THRESHOLD = 0.82
_NUMBER_WORDS = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"ten": "10",
}
_ROMAN_NUMERALS = {
"i": "1",
"ii": "2",
"iii": "3",
"iv": "4",
"v": "5",
"vi": "6",
"vii": "7",
"viii": "8",
"ix": "9",
"x": "10",
}
def _normalize_game_name(name: str) -> str:
"""Canonicalize a game/folder name for fuzzy comparison.
Splits into alphanumeric words, maps spelled-out numbers ("two") and
roman numerals ("II") to digits, then joins with no separators. Makes
"Kingdom Come: Deliverance II", "KingdomComeDeliverance2", and "kingdom
come deliverance two" all normalize to the same string.
"""
words = re.findall(r"[A-Za-z0-9]+", name.lower())
mapped = [_NUMBER_WORDS.get(w) or _ROMAN_NUMERALS.get(w) or w for w in words]
return "".join(mapped)
def _protected_name_stems() -> list[str]:
"""Every name of every currently-allowed game, for the deletion safety net.
Returns [] (protects nothing extra beyond exact matches already checked
by callers) if state can't be loaded -- this is a best-effort safety net,
not a hard dependency.
"""
try:
return [name for _, name in allowed_games(State.load()) if name]
except Exception:
logger.exception("Could not load allowed games for the deletion safety net")
return []
def _is_protected_name(candidate: str) -> bool:
"""True if *candidate* plausibly names one of the currently-allowed games.
Errs toward over-matching on purpose: a false positive here just skips a
deletion that can be done manually; a false negative deletes real files.
"""
normalized_candidate = _normalize_game_name(candidate)
if not normalized_candidate:
return False
for protected in _protected_name_stems():
normalized_protected = _normalize_game_name(protected)
if not normalized_protected:
continue
if normalized_candidate == normalized_protected:
return True
ratio = difflib.SequenceMatcher(
None, normalized_candidate, normalized_protected
).ratio()
if ratio >= _NAME_FUZZY_MATCH_THRESHOLD:
return True
return False
# Real Steam directory — used as a safety check to block destructive
# operations that leak through during testing.
_REAL_STEAMAPPS = Path("~/.local/share/Steam/steamapps").expanduser()
def _assert_not_real_steam(path: Path) -> None:
"""Raise if *path* is inside the real Steam directory during tests.
Defence-in-depth guard: when running under pytest, even if test
fixtures fail to redirect ``STEAMAPPS_PATH``, destructive
operations (uninstall, rmtree, unlink) will refuse to touch
real files. In production runs this is a no-op.
"""
if "PYTEST_CURRENT_TEST" not in os.environ:
return # production run — real Steam paths are expected
try:
path.resolve().relative_to(_REAL_STEAMAPPS.resolve())
except ValueError:
return # path is NOT under real Steam — safe to proceed
if STEAMAPPS_PATH.resolve() == _REAL_STEAMAPPS.resolve():
msg = (
f"SAFETY: refusing destructive operation on real Steam path "
f"{path!s} — STEAMAPPS_PATH was not redirected by test fixtures"
)
raise RuntimeError(msg)
def _echo(msg: str = "", *, end: str = "\n", flush: bool = False) -> None:
"""Write user-facing CLI output to stdout.
Args:
msg: Text to output.
end: String appended after the message.
flush: Whether to flush stdout immediately.
"""
sys.stdout.write(msg + end)
if flush:
sys.stdout.flush()
# Steam infrastructure app IDs that should NEVER be uninstalled.
PROTECTED_APP_IDS = {
# Steam runtimes and tooling (never uninstall these)
228980, # Steamworks Common Redistributables
1070560, # Steam Linux Runtime 1.0 (scout)
1391110, # Steam Linux Runtime 2.0 (soldier)
1628350, # Steam Linux Runtime 3.0 (sniper)
4183110, # Steam Linux Runtime 4.0
4185400, # Steam Linux Runtime 4.0 - Arm64
961940, # Steam Linux Runtime (legacy)
4690330, # Legacy Steam Runtime
613220, # Steam 360 Video Player
250820, # SteamVR
1007, # Steamworks SDK Redist
# Proton versions (never uninstall these)
858280, # Proton 3.7 (Beta)
930400, # Proton 3.16 (Beta)
1054830, # Proton 4.2
1113280, # Proton 4.11
1245040, # Proton 5.0
1420170, # Proton 5.13
1580130, # Proton 6.3
1887720, # Proton 7.0
2230260, # Proton 7.0 (alt)
2348590, # Proton 8.0
2805730, # Proton 9.0
3201940, # Proton 9.0 (alt)
3658110, # Proton 10.0
4628710, # Proton 11.0
4628740, # Proton 11.0 (ARM64)
2180100, # Proton Hotfix
1493710, # Proton Experimental
1161040, # Proton BattlEye Runtime
1007020, # Proton EasyAntiCheat Runtime
1826330, # Proton EasyAntiCheat Runtime
}
def _trigger_steam_install(app_id: int, label: str) -> bool:
@ -196,9 +72,17 @@ def _trigger_steam_install(app_id: int, label: str) -> bool:
Returns True if the URI handler was invoked successfully.
"""
xdg_open = shutil.which("xdg-open") or "/usr/bin/xdg-open"
real_user = _get_real_user()
# Without the drop this opens steam://install as root, and Steam answers
# with a "Cannot run as root user" modal on the user's display.
if os.geteuid() == 0 and not desktop_session_ready(desktop_uid(real_user)):
logger.debug("Deferring Steam install for %s: no desktop session.", label)
return False
try:
subprocess.run(
[xdg_open, f"steam://install/{app_id}"],
desktop_user_cmd([xdg_open, f"steam://install/{app_id}"], real_user),
capture_output=True,
timeout=15,
check=False,
@ -215,92 +99,6 @@ def _trigger_steam_install(app_id: int, label: str) -> bool:
# ──────────────────────────────────────────────────────────────
def _get_real_user() -> str | None:
"""Get the real (non-root) user when running under sudo."""
return os.environ.get("SUDO_USER") or os.environ.get("USER")
def _get_uid_gid_for_user(username: str) -> tuple[int, int]:
"""Get (uid, gid) for a username."""
try:
pw = pwd.getpwnam(username)
except KeyError:
return 1000, 1000
else:
return pw.pw_uid, pw.pw_gid
def is_game_installed(app_id: int) -> bool:
"""Check if a game is installed by looking for its appmanifest.
A manifest with StateFlags != 4 (FullyInstalled) means the game is
still downloading or queued, which still counts as "install triggered".
"""
manifest = STEAMAPPS_PATH / f"appmanifest_{app_id}.acf"
return manifest.exists()
def _ensure_steam_running() -> None:
"""Start the Steam client if it is not already running.
Does nothing if Steam is not installed - there is no client to start, and
trying anyway only sleeps 15s waiting on a process that died on exec.
"""
if not steam_is_installed():
logger.info("Steam is not installed — skipping client start.")
return
# Check if any steam process is running (main client, not just helpers).
try:
result = subprocess.run(
["/usr/bin/pgrep", "-f", "steam.sh"],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
logger.debug("Steam client already running")
return
except FileNotFoundError:
pass
real_user = _get_real_user()
logger.info("Starting Steam client...")
try:
if os.geteuid() == 0 and real_user and real_user != "root":
uid, _ = _get_uid_gid_for_user(real_user)
# Defer rather than launch a Steam that would come up without a
# runtime dir, and so without working audio, for the session.
if not desktop_session_ready(uid):
logger.info(
"Deferring Steam start: %s does not exist yet.",
desktop_runtime_dir(uid),
)
return
cmd = [
"sudo",
"-u",
real_user,
"env",
*desktop_env_args(real_user, uid),
"steam",
"-silent",
]
else:
cmd = ["steam", "-silent"]
subprocess.Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# Give Steam time to initialize and start scanning manifests.
time.sleep(15)
except FileNotFoundError:
logger.exception("Steam executable not found")
def install_game(
app_id: int,
game_name: str,
@ -332,10 +130,30 @@ def install_game(
"""
label = game_name or f"AppID={app_id}"
# Re-arm the one-shot warning before any early return, so a library that
# comes back (Steam finally signed in) is reported again if it vanishes.
if steam_library_ready():
_LIBRARY_WARNED.discard("missing")
if is_game_installed(app_id):
logger.info("Game already installed: %s", label)
return True
# No library means no install can succeed — neither the steam:// handler
# nor the appmanifest write below. Without this the enforce loop retried
# every allowed game every pass (measured: 1656 times in 30 minutes).
if not steam_library_ready():
if "missing" not in _LIBRARY_WARNED:
logger.warning(
"Steam library not initialised (%s missing) — skipping installs "
"until Steam has been signed in to at least once.",
STEAMAPPS_PATH,
)
_LIBRARY_WARNED.add("missing")
else:
logger.debug("Skipping install of %s: no Steam library.", label)
return False
if use_steam_protocol:
_ensure_steam_running()
if _trigger_steam_install(app_id, label):
@ -401,153 +219,3 @@ def install_game(
_ensure_steam_running()
return True
# ──────────────────────────────────────────────────────────────
# Game uninstall management
# ──────────────────────────────────────────────────────────────
def get_installed_games() -> list[tuple[int, str]]:
"""Parse appmanifest files to find installed games.
Returns: list of (app_id, game_name) tuples.
"""
installed: list[tuple[int, str]] = []
for manifest_file in STEAMAPPS_PATH.glob("appmanifest_*.acf"):
with contextlib.suppress(OSError):
content = manifest_file.read_text(encoding="utf-8")
app_id_match = re.search(r'"appid"\s+"(\d+)"', content)
name_match = re.search(r'"name"\s+"([^"]+)"', content)
if app_id_match:
app_id = int(app_id_match.group(1))
name = name_match.group(1) if name_match else f"Unknown ({app_id})"
installed.append((app_id, name))
installed.sort(key=lambda x: x[1].lower())
return installed
def _read_install_dir(manifest: Path) -> Path | None:
"""Read installdir from a game's appmanifest file."""
if not manifest.exists():
return None
try:
content = manifest.read_text(encoding="utf-8")
match = re.search(r'"installdir"\s+"([^"]+)"', content)
if match:
return STEAMAPPS_PATH / "common" / match.group(1)
except OSError:
pass
return None
def _remove_manifest(manifest: Path, game_name: str, app_id: int) -> bool:
"""Remove a game manifest file.
Args:
manifest: Path to the appmanifest file.
game_name: Human-readable game name for logging.
app_id: Steam application ID.
"""
_assert_not_real_steam(manifest)
try:
if manifest.exists():
manifest.unlink()
logger.info(
"Removed manifest for %s (AppID=%d)", game_name or app_id, app_id
)
except OSError:
logger.exception("Failed to remove manifest for AppID=%d", app_id)
return False
return True
def _remove_game_dirs(install_dir: Path | None, app_id: int) -> bool:
"""Remove game installation directory and cache directories.
Args:
install_dir: Path to the game's install directory, or None.
app_id: Steam application ID.
"""
success = True
if install_dir and install_dir.is_dir():
_assert_not_real_steam(install_dir)
if _is_protected_name(install_dir.name):
logger.warning(
"Refusing to remove %s: name matches an allowed game", install_dir
)
return False
try:
shutil.rmtree(install_dir)
logger.info("Removed game files: %s", install_dir)
except OSError:
logger.exception("Failed to remove game dir %s", install_dir)
success = False
for subdir in ("shadercache", "compatdata"):
cache_path = STEAMAPPS_PATH / subdir / str(app_id)
if cache_path.is_dir():
_assert_not_real_steam(cache_path)
with contextlib.suppress(OSError):
shutil.rmtree(cache_path)
logger.debug("Removed %s/%d", subdir, app_id)
return success
def uninstall_game(app_id: int, game_name: str = "") -> bool:
"""Uninstall a single game by removing its manifest and game files.
Uses direct file removal instead of ``steam://uninstall`` URI to avoid
GUI popups and to work when Steam is not running.
"""
manifest = STEAMAPPS_PATH / f"appmanifest_{app_id}.acf"
install_dir = _read_install_dir(manifest)
success = _remove_manifest(manifest, game_name, app_id)
if not _remove_game_dirs(install_dir, app_id):
success = False
return success
def uninstall_other_games(allowed_app_ids: set[int]) -> int:
"""Uninstall all installed games except the allowed ones and protected IDs.
Args:
allowed_app_ids: Every app id that must survive — the assignment plus
any concurrent manual picks. Empty means "keep nothing".
Returns: number of games uninstalled.
"""
installed = get_installed_games()
count = 0
for app_id, name in installed:
if app_id in allowed_app_ids:
logger.info("KEEPING allowed game: %s (AppID=%d)", name, app_id)
continue
if is_protected_app(app_id):
logger.debug("Skipping protected: %s (AppID=%d)", name, app_id)
continue
logger.info("UNINSTALLING: %s (AppID=%d)", name, app_id)
if uninstall_game(app_id, name):
count += 1
return count
def is_protected_app(app_id: int) -> bool:
"""Return True if *app_id* must never be uninstalled.
Combines the hardcoded Steam infrastructure set with any app IDs that
have been approved via the time-locked exception mechanism.
Args:
app_id: Steam application ID to check.
Returns:
True if the app should be left alone by the enforcer.
"""
return app_id in PROTECTED_APP_IDS or app_id in get_approved_exception_ids()

View File

@ -0,0 +1,174 @@
"""Uninstalling games and querying what is installed.
Split out of :mod:`steam_backlog_enforcer.game_install` to keep both files
under the 250-line cap: that module owns getting a game *onto* disk, this one
owns taking it off and reporting what is there.
"""
from __future__ import annotations
import contextlib
import logging
import re
import shutil
from typing import TYPE_CHECKING
from steam_backlog_enforcer._game_names import _is_protected_name
from steam_backlog_enforcer._protected_apps import PROTECTED_APP_IDS
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH, _assert_not_real_steam
from steam_backlog_enforcer._whitelist import get_approved_exception_ids
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────
# Game uninstall management
# ──────────────────────────────────────────────────────────────
def get_installed_games() -> list[tuple[int, str]]:
"""Parse appmanifest files to find installed games.
Returns: list of (app_id, game_name) tuples.
"""
installed: list[tuple[int, str]] = []
for manifest_file in STEAMAPPS_PATH.glob("appmanifest_*.acf"):
with contextlib.suppress(OSError):
content = manifest_file.read_text(encoding="utf-8")
app_id_match = re.search(r'"appid"\s+"(\d+)"', content)
name_match = re.search(r'"name"\s+"([^"]+)"', content)
if app_id_match:
app_id = int(app_id_match.group(1))
name = name_match.group(1) if name_match else f"Unknown ({app_id})"
installed.append((app_id, name))
installed.sort(key=lambda x: x[1].lower())
return installed
def _read_install_dir(manifest: Path) -> Path | None:
"""Read installdir from a game's appmanifest file."""
if not manifest.exists():
return None
try:
content = manifest.read_text(encoding="utf-8")
match = re.search(r'"installdir"\s+"([^"]+)"', content)
if match:
return STEAMAPPS_PATH / "common" / match.group(1)
except OSError:
pass
return None
def _remove_manifest(manifest: Path, game_name: str, app_id: int) -> bool:
"""Remove a game manifest file.
Args:
manifest: Path to the appmanifest file.
game_name: Human-readable game name for logging.
app_id: Steam application ID.
"""
_assert_not_real_steam(manifest)
try:
if manifest.exists():
manifest.unlink()
logger.info(
"Removed manifest for %s (AppID=%d)", game_name or app_id, app_id
)
except OSError:
logger.exception("Failed to remove manifest for AppID=%d", app_id)
return False
return True
def _remove_game_dirs(install_dir: Path | None, app_id: int) -> bool:
"""Remove game installation directory and cache directories.
Args:
install_dir: Path to the game's install directory, or None.
app_id: Steam application ID.
"""
success = True
if install_dir and install_dir.is_dir():
_assert_not_real_steam(install_dir)
if _is_protected_name(install_dir.name):
logger.warning(
"Refusing to remove %s: name matches an allowed game", install_dir
)
return False
try:
shutil.rmtree(install_dir)
logger.info("Removed game files: %s", install_dir)
except OSError:
logger.exception("Failed to remove game dir %s", install_dir)
success = False
for subdir in ("shadercache", "compatdata"):
cache_path = STEAMAPPS_PATH / subdir / str(app_id)
if cache_path.is_dir():
_assert_not_real_steam(cache_path)
with contextlib.suppress(OSError):
shutil.rmtree(cache_path)
logger.debug("Removed %s/%d", subdir, app_id)
return success
def uninstall_game(app_id: int, game_name: str = "") -> bool:
"""Uninstall a single game by removing its manifest and game files.
Uses direct file removal instead of ``steam://uninstall`` URI to avoid
GUI popups and to work when Steam is not running.
"""
manifest = STEAMAPPS_PATH / f"appmanifest_{app_id}.acf"
install_dir = _read_install_dir(manifest)
success = _remove_manifest(manifest, game_name, app_id)
if not _remove_game_dirs(install_dir, app_id):
success = False
return success
def uninstall_other_games(allowed_app_ids: set[int]) -> int:
"""Uninstall all installed games except the allowed ones and protected IDs.
Args:
allowed_app_ids: Every app id that must survive — the assignment plus
any concurrent manual picks. Empty means "keep nothing".
Returns: number of games uninstalled.
"""
installed = get_installed_games()
count = 0
for app_id, name in installed:
if app_id in allowed_app_ids:
logger.info("KEEPING allowed game: %s (AppID=%d)", name, app_id)
continue
if is_protected_app(app_id):
logger.debug("Skipping protected: %s (AppID=%d)", name, app_id)
continue
logger.info("UNINSTALLING: %s (AppID=%d)", name, app_id)
if uninstall_game(app_id, name):
count += 1
return count
def is_protected_app(app_id: int) -> bool:
"""Return True if *app_id* must never be uninstalled.
Combines the hardcoded Steam infrastructure set with any app IDs that
have been approved via the time-locked exception mechanism.
Args:
app_id: Steam application ID to check.
Returns:
True if the app should be left alone by the enforcer.
"""
return app_id in PROTECTED_APP_IDS or app_id in get_approved_exception_ids()

View File

@ -13,8 +13,9 @@ Fetches leisure completionist hour estimates from howlongtobeat.com with:
from __future__ import annotations
import asyncio
import importlib
import logging
import time
from typing import Any, TypeAlias
import aiohttp
@ -26,18 +27,10 @@ from steam_backlog_enforcer._hltb_search import (
_SearchCtx,
)
from steam_backlog_enforcer._hltb_types import (
HLTB_BASE_URL,
MAX_CONCURRENT,
HLTBResult,
ProgressCb,
_HLTBExtras,
load_hltb_cache,
load_hltb_count_comp_cache,
load_hltb_game_id_cache,
load_hltb_leisure_100h_cache,
load_hltb_polls_cache,
load_hltb_rush_cache,
save_hltb_cache,
)
logger = logging.getLogger(__name__)
@ -176,209 +169,39 @@ def fetch_hltb_confidence(
)
def fetch_hltb_times_cached(
games: list[tuple[int, str]],
progress_cb: ProgressCb | None = None,
) -> dict[int, float]:
"""Fetch HLTB times, using disk cache for already-known games.
_REEXPORTED = {
"HLTB_BASE_URL": "steam_backlog_enforcer._hltb_types",
"MAX_CONCURRENT": "steam_backlog_enforcer._hltb_types",
"HLTBResult": "steam_backlog_enforcer._hltb_types",
"ProgressCb": "steam_backlog_enforcer._hltb_types",
"_HLTBExtras": "steam_backlog_enforcer._hltb_types",
"load_hltb_cache": "steam_backlog_enforcer._hltb_types",
"load_hltb_count_comp_cache": "steam_backlog_enforcer._hltb_types",
"load_hltb_game_id_cache": "steam_backlog_enforcer._hltb_types",
"load_hltb_leisure_100h_cache": "steam_backlog_enforcer._hltb_types",
"load_hltb_polls_cache": "steam_backlog_enforcer._hltb_types",
"load_hltb_rush_cache": "steam_backlog_enforcer._hltb_types",
"save_hltb_cache": "steam_backlog_enforcer._hltb_types",
"fetch_hltb_times_cached": "steam_backlog_enforcer._hltb_cached",
"fetch_hltb_confidence_cached": "steam_backlog_enforcer._hltb_confidence",
"fetch_hltb_detail_missing": "steam_backlog_enforcer._hltb_confidence",
"get_hltb_submit_url": "steam_backlog_enforcer._hltb_confidence",
}
Args:
games: list of (app_id, name) tuples to look up.
progress_cb: optional callback(done, total, found, game_name).
Returns: dict mapping app_id -> completionist_hours.
# Whatever the re-exported name turns out to be -- a function, a class or
# a constant. Aliased so the annotation is a name rather than a bare Any.
_Reexport: TypeAlias = Any
def __getattr__(name: str) -> _Reexport:
"""Serve names that moved out of this module when it was split.
Deferred via importlib rather than imported at the top: the modules below
import back from here, so a module-level import would be circular.
"""
cache = load_hltb_cache()
polls = load_hltb_polls_cache()
extras = _HLTBExtras(
count_comp=load_hltb_count_comp_cache(),
rush=load_hltb_rush_cache(),
leisure_100h=load_hltb_leisure_100h_cache(),
)
uncached = [(app_id, name) for app_id, name in games if app_id not in cache]
if uncached:
logger.info(
"Fetching HLTB data for %d uncached games (%d cached)...",
len(uncached),
len(games) - len(uncached),
)
t0 = time.monotonic()
fetch_hltb_times(
uncached,
cache=cache,
polls=polls,
progress_cb=progress_cb,
extras=extras,
)
elapsed = time.monotonic() - t0
# Final save.
save_hltb_cache(cache, polls, extras)
found = sum(1 for aid, _ in uncached if cache.get(aid, -1) > 0)
rate = len(uncached) / elapsed if elapsed > 0 else 0
logger.info(
"HLTB fetch done: %d/%d found in %.1fs (%.0f games/s)",
found,
len(uncached),
elapsed,
rate,
)
else:
logger.info("All %d games found in HLTB cache.", len(games))
return cache
def fetch_hltb_confidence_cached(
games: list[tuple[int, str]],
progress_cb: ProgressCb | None = None,
) -> dict[int, float]:
"""Fetch HLTB search-level confidence data, using disk cache for known IDs."""
cache = load_hltb_cache()
polls = load_hltb_polls_cache()
count_comp = load_hltb_count_comp_cache()
uncached = [(app_id, name) for app_id, name in games if app_id not in cache]
if uncached:
logger.info(
"Fetching HLTB confidence for %d uncached games (%d cached)...",
len(uncached),
len(games) - len(uncached),
)
t0 = time.monotonic()
fetch_hltb_confidence(
uncached,
cache=cache,
polls=polls,
progress_cb=progress_cb,
count_comp=count_comp,
)
elapsed = time.monotonic() - t0
save_hltb_cache(cache, polls, _HLTBExtras(count_comp=count_comp))
found = sum(1 for aid, _ in uncached if cache.get(aid, -1) > 0)
rate = len(uncached) / elapsed if elapsed > 0 else 0
logger.info(
"HLTB confidence fetch done: %d/%d found in %.1fs (%.0f games/s)",
found,
len(uncached),
elapsed,
rate,
)
else:
logger.info("All %d games found in HLTB cache.", len(games))
return cache
def fetch_hltb_detail_missing(
games: list[tuple[int, str]],
progress_cb: ProgressCb | None = None,
) -> int:
"""Fetch HLTB detail (rush + leisure) for games that are missing it.
Also backfills ``hltb_game_id`` for any game that already has rush/leisure
data but whose HLTB game ID was never stored (e.g. from an old cache).
Games with both rush data and a game_id are skipped entirely. For the
rest, temporarily removes them from the hours cache so ``fetch_hltb_times``
will visit their detail pages. Restores prior hours for any game the
re-fetch doesn't find.
Args:
games: list of (app_id, name) tuples to check.
progress_cb: optional progress callback.
Returns:
Number of games that now have rush-hour data after the fetch.
"""
rush = load_hltb_rush_cache()
game_id_cache = load_hltb_game_id_cache()
missing_rush = [
(app_id, name) for app_id, name in games if rush.get(app_id, -1) <= 0
]
# Also re-search games that have rush data but no HLTB game ID yet so the
# direct URL can be shown in stats output.
missing_id_only = [
(app_id, name)
for app_id, name in games
if rush.get(app_id, -1) > 0 and game_id_cache.get(app_id, 0) == 0
]
missing = missing_rush + missing_id_only
if not missing:
return 0
cache = load_hltb_cache()
polls = load_hltb_polls_cache()
extras = _HLTBExtras(
count_comp=load_hltb_count_comp_cache(),
rush=rush,
leisure_100h=load_hltb_leisure_100h_cache(),
hltb_game_id=game_id_cache,
)
# Remove from hours cache so fetch_hltb_times will visit the detail page.
prior_hours: dict[int, float] = {}
for app_id, _ in missing:
prior_hours[app_id] = cache.pop(app_id, -1.0)
n_rush = len(missing_rush)
n_id = len(missing_id_only)
if n_rush and n_id:
logger.info(
"Fetching HLTB detail for %d games missing rush/leisure data"
" + %d games missing game ID...",
n_rush,
n_id,
)
elif n_rush:
logger.info(
"Fetching HLTB detail for %d games missing rush/leisure data...", n_rush
)
else:
logger.info("Backfilling HLTB game ID for %d game(s)...", n_id)
t0 = time.monotonic()
fetch_hltb_times(
missing,
cache=cache,
polls=polls,
progress_cb=progress_cb,
extras=extras,
)
elapsed = time.monotonic() - t0
# Restore prior hours for games the detail fetch didn't re-find.
for app_id, old_hours in prior_hours.items():
if old_hours > 0 and cache.get(app_id, -1.0) <= 0:
cache[app_id] = old_hours
save_hltb_cache(cache, polls, extras)
fetched = sum(1 for app_id, _ in missing_rush if extras.rush.get(app_id, -1) > 0)
rate = len(missing) / elapsed if elapsed > 0 else 0
logger.info(
"HLTB detail fetch done: %d/%d got rush data in %.1fs (%.0f games/s)",
fetched,
len(missing_rush),
elapsed,
rate,
)
return fetched
def get_hltb_submit_url(game_name: str) -> str | None:
"""Look up a game on HLTB and return its submit page URL.
Args:
game_name: Name of the game to search for.
Returns:
URL like ``https://howlongtobeat.com/submit/game/12345``,
or ``None`` if the game wasn't found.
"""
results = fetch_hltb_times([(0, game_name)])
if results and results[0].hltb_game_id:
return f"{HLTB_BASE_URL}/submit/game/{results[0].hltb_game_id}"
return None
home = _REEXPORTED.get(name)
if home is not None:
return getattr(importlib.import_module(home), name)
msg = f"module {__name__!r} has no attribute {name!r}"
raise AttributeError(msg)

View File

@ -16,328 +16,35 @@ will shut Steam down and relaunch it with the required flags.
from __future__ import annotations
import asyncio
import json
import logging
import os
from pathlib import Path
import pwd
import shutil
import subprocess
import time
import requests
import websockets
from steam_backlog_enforcer._desktop_env import (
desktop_env_args,
desktop_runtime_dir,
desktop_session_ready,
from steam_backlog_enforcer._cdp import _cdp_result_value, _evaluate_js
from steam_backlog_enforcer._steam_errors import (
SteamUnavailableError,
)
from steam_backlog_enforcer._steam_launch import (
ensure_steam_debug_port,
restart_steam,
steam_is_installed,
)
from steam_backlog_enforcer._steam_state import steam_update_in_progress
logger = logging.getLogger(__name__)
# Re-exported: the Steam lifecycle now lives in _steam_launch, but callers
# still import these from here. __all__ stops the linter deleting them.
__all__ = [
"hide_other_games",
"restart_steam",
"steam_is_installed",
"try_hide_other_games",
"unhide_all_games",
]
_CDP_PORT = 9222
# NOTE: was 8080, which collided with a different local service (Open WebUI)
# already bound to 0.0.0.0:8080. requests to 127.0.0.1:8080 resolved to that
# service instead of steamwebhelper's CDP endpoint (which only bound
# [::1]:8080), so CDP detection silently never worked. 9222 is the
# conventional Chrome DevTools debug port and was confirmed free.
_CDP_TIMEOUT = 120
_STEAM_STARTUP_WAIT = 45
# Real Steam client binary, as shipped by the distro's `steam` package.
#
# Deliberately NOT probed with shutil.which("steam"): a launcher wrapper on
# $PATH (e.g. /usr/local/bin/steam adding -cef-* flags) keeps `which` truthy
# long after the package itself is gone - as happens when a total block
# uninstalls Steam. Checking the real binary is what actually answers
# "can we launch Steam at all?".
_STEAM_BINARY = "/usr/bin/steam"
# Handles for fire-and-forget launches, kept only so they can be reaped.
_SPAWNED: list[subprocess.Popen[bytes]] = []
class SteamUnavailableError(RuntimeError):
"""Raised when Steam cannot be driven over CDP.
Covers both "Steam is not installed" and "Steam is installed but never
opened its debug port". Callers are expected to degrade gracefully rather
than abort: an unreachable Steam means there is no library to hide, which
is not a fatal condition for the enforcer.
"""
class SteamUpdateInProgressError(SteamUnavailableError):
"""Raised to defer a Steam restart while a game update is in flight.
Subclasses :class:`SteamUnavailableError` so existing callers already
degrade gracefully (skip this pass, retry next loop). Restarting Steam
mid-update suspends and can corrupt the transfer, so the enforcer waits
for updates to finish before bouncing Steam to open the CDP port.
"""
class DesktopSessionNotReadyError(SteamUnavailableError):
"""Raised to defer a Steam launch until the user's session exists.
Subclasses :class:`SteamUnavailableError` so existing callers already
degrade gracefully (skip this pass, retry next loop). Launching Steam
before ``/run/user/<uid>`` exists hands every Wine child a runtime dir
that is not there, so it falls back from winepulse to winealsa and stays
that way for the whole session — the Kingdom Come: Deliverance II startup
crash. Waiting a pass costs 3s; getting it wrong costs a reboot.
"""
def _desktop_uid(user: str | None) -> int:
"""Resolve *user* to a uid, defaulting to the usual first desktop uid."""
if user:
try:
return pwd.getpwnam(user).pw_uid
except KeyError:
pass
return 1000
def steam_is_installed() -> bool:
"""Return True if the real Steam client binary is present."""
return Path(_STEAM_BINARY).exists()
# ──────────────────────────────────────────────────────────────
# CDP (Chrome DevTools Protocol) helpers
# ──────────────────────────────────────────────────────────────
def _get_shared_js_ws_url() -> str | None:
"""Query the CDP HTTP endpoint and return the SharedJSContext WS URL."""
try:
resp = requests.get(f"http://127.0.0.1:{_CDP_PORT}/json", timeout=5)
targets = resp.json()
except (OSError, ValueError):
return None
for target in targets:
if target.get("title") == "SharedJSContext":
ws_url: str = target["webSocketDebuggerUrl"]
return ws_url
return None
async def _evaluate_js_async(ws_url: str, expression: str) -> dict:
"""Connect to a CDP WebSocket target and evaluate *expression*."""
async with websockets.connect(ws_url) as ws:
msg = json.dumps(
{
"id": 1,
"method": "Runtime.evaluate",
"params": {
"expression": expression,
"returnByValue": True,
"awaitPromise": True,
},
}
)
await ws.send(msg)
resp = await asyncio.wait_for(ws.recv(), timeout=_CDP_TIMEOUT)
return json.loads(resp)
def _evaluate_js(expression: str) -> dict:
"""Synchronous wrapper around :func:`_evaluate_js_async`."""
ws_url = _get_shared_js_ws_url()
if ws_url is None:
msg = "SharedJSContext not found on CDP port"
raise RuntimeError(msg)
return asyncio.run(_evaluate_js_async(ws_url, expression))
def _cdp_result_value(result: dict) -> str:
"""Extract the return value from a CDP Runtime.evaluate response."""
outer = result.get("result", {})
inner = outer.get("result", {})
if "exceptionDetails" in outer:
exc_details = outer["exceptionDetails"]
exc = exc_details.get("exception", {})
desc = (
inner.get("description")
or exc.get("description")
or exc_details.get("text")
or repr(exc_details)
)
logger.debug("CDP exception details: %s", exc_details)
msg = f"JS evaluation error: {desc}"
raise RuntimeError(msg)
value: str = inner.get("value", "")
return value
# ──────────────────────────────────────────────────────────────
# Ensure Steam is running with devtools port
# ──────────────────────────────────────────────────────────────
def _is_steam_running() -> bool:
"""Check whether any Steam process is alive."""
pgrep = shutil.which("pgrep") or "/usr/bin/pgrep"
result = subprocess.run(
[pgrep, "-x", "steam"],
capture_output=True,
check=False,
)
return result.returncode == 0
def _steam_has_debug_port() -> bool:
"""Check whether steamwebhelper is listening on the CDP port."""
return _get_shared_js_ws_url() is not None
def _wait_for_cdp_ready() -> bool:
"""Wait up to *_STEAM_STARTUP_WAIT* seconds for CDP to become ready."""
for _ in range(_STEAM_STARTUP_WAIT):
if _get_shared_js_ws_url() is not None:
return True
time.sleep(1)
return False
def _wait_for_collections_ready() -> bool:
"""Wait until ``collectionStore`` is fully initialised.
Right after Steam starts, the CDP port may be open but the
internal collection data hasn't loaded yet. Poll a lightweight
JS check until ``GetCollection`` stops throwing.
"""
js = (
"(() => { try { collectionStore.GetCollection('hidden');"
" return 'ok'; } catch(e) { return 'not_ready'; } })()"
)
for _ in range(_STEAM_STARTUP_WAIT):
try:
result = _evaluate_js(js)
if _cdp_result_value(result) == "ok":
return True
except RuntimeError:
pass
time.sleep(1)
return False
def _resolve_desktop_user() -> str | None:
"""Resolve which desktop user owns the Steam/X11 session.
Prefers the explicit STEAM_ENFORCER_DESKTOP_USER (set by the systemd
unit, which has no SUDO_USER/USER of its own since it is started
directly by systemd rather than via `sudo`), then falls back to
SUDO_USER/USER for interactive `sudo` invocations.
"""
return (
os.environ.get("STEAM_ENFORCER_DESKTOP_USER")
or os.environ.get("SUDO_USER")
or os.environ.get("USER")
)
def _shutdown_steam() -> None:
"""Send ``steam -shutdown`` and wait for the process to exit."""
real_user = _resolve_desktop_user()
try:
_run_as_user(["steam", "-shutdown"], real_user)
except FileNotFoundError:
return
pgrep = shutil.which("pgrep") or "/usr/bin/pgrep"
for _ in range(30):
result = subprocess.run(
[pgrep, "-x", "steam"],
capture_output=True,
check=False,
)
if result.returncode != 0:
return
time.sleep(1)
def _launch_steam_with_debug() -> None:
"""Launch Steam with CEF debugging enabled."""
real_user = _resolve_desktop_user()
_run_as_user(
[
"steam",
"-cef-enable-debugging",
f"-devtools-port={_CDP_PORT}",
"-silent",
],
real_user,
)
def ensure_steam_debug_port() -> None:
"""Make sure Steam is running with the CDP debug port open.
If Steam is running without the port, it is restarted.
If Steam is not running, it is launched.
Raises:
SteamUnavailableError: If Steam is not installed, or is installed but
never opens its debug port.
"""
if _steam_has_debug_port():
logger.debug("Steam CDP port already available.")
return
# Bail out before the ~45s launch-and-wait: with no binary to exec there
# is nothing to wait for, and retrying every pass only burns time and
# leaves dead processes behind.
if not steam_is_installed():
msg = f"Steam is not installed ({_STEAM_BINARY} does not exist)"
raise SteamUnavailableError(msg)
# Never launch Steam into a session that does not exist yet: it would get
# a missing XDG_RUNTIME_DIR, silently fall back to winealsa, and stay
# audio-broken until the next restart. Defer instead — the loop retries.
real_user = _resolve_desktop_user()
if os.geteuid() == 0 and not desktop_session_ready(_desktop_uid(real_user)):
msg = (
"Deferring Steam launch: the desktop session's runtime directory "
f"({desktop_runtime_dir(_desktop_uid(real_user))}) does not exist "
"yet. Launching now would leave Steam without audio; will retry."
)
logger.info(msg)
raise DesktopSessionNotReadyError(msg)
logger.info("Steam CDP port not available — (re)starting Steam...")
if _is_steam_running():
# Never bounce a running Steam while a game update is downloading or
# committing: the shutdown suspends it and can leave a partially
# written install (the root cause of the AoE2 launch crash). Defer and
# retry on the next enforce pass.
if steam_update_in_progress():
msg = (
"Deferring Steam restart: a game update is in progress. "
"Restarting now would interrupt and can corrupt it; will "
"retry once the update settles."
)
logger.info(msg)
raise SteamUpdateInProgressError(msg)
_shutdown_steam()
_launch_steam_with_debug()
if not _wait_for_cdp_ready():
msg = "Timed out waiting for Steam CDP port to become ready"
raise SteamUnavailableError(msg)
logger.info("Steam CDP port ready.")
if not _wait_for_collections_ready():
msg = "Timed out waiting for Steam collections to initialise"
raise SteamUnavailableError(msg)
logger.info("Steam collection store ready.")
# ──────────────────────────────────────────────────────────────
# Hide / unhide logic
@ -488,68 +195,3 @@ def unhide_all_games(owned_app_ids: list[int]) -> int:
count: int = parsed["count"]
logger.info("Unhidden %d games via CDP.", count)
return count
# ──────────────────────────────────────────────────────────────
# Steam restart helper
# ──────────────────────────────────────────────────────────────
def restart_steam() -> None:
"""Gracefully restart the Steam client with CEF debugging enabled.
Skips the restart if a game update is downloading or committing, so the
update is not interrupted (interrupting it can corrupt the install).
"""
if steam_update_in_progress():
logger.warning(
"Skipping Steam restart — a game update is in progress; "
"restarting now could corrupt it.",
)
return
logger.info("Restarting Steam client with debug port...")
_shutdown_steam()
_launch_steam_with_debug()
if not _wait_for_cdp_ready():
logger.warning("Steam restarted but CDP port not ready.")
else:
logger.info("Steam restarted with CDP port ready.")
def _reap_spawned() -> None:
"""Clear out previously launched processes that have since exited.
Launches here are fire-and-forget: Steam is meant to outlive the call, so
it is never waited on. That leaves any launch which dies immediately - a
missing binary, a broken wrapper - sitting as a zombie that still carries
the name ``steam``, which anything scanning /proc reads as "Steam is
running". Polling the old handles reaps them and retires the name.
"""
_SPAWNED[:] = [proc for proc in _SPAWNED if proc.poll() is None]
def _run_as_user(cmd: list[str], user: str | None) -> None:
"""Run a command, dropping to *user* if currently root."""
_reap_spawned()
if os.geteuid() == 0 and user and user != "root":
uid = _desktop_uid(user)
full_cmd = [
"sudo",
"-u",
user,
"env",
*desktop_env_args(user, uid),
*cmd,
]
else:
full_cmd = cmd
_SPAWNED.append(
subprocess.Popen(
full_cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,235 @@
"""Main CLI for Steam Backlog Enforcer.
The command implementations live in sibling modules (``status``, ``install``,
``picks``, ``abandon``, ``misc``) and are re-exported here, so
``steam_backlog_enforcer.main`` stays the single import surface it was when
this was one module. ``python -m steam_backlog_enforcer.main`` still works via
:mod:`steam_backlog_enforcer.main.__main__`.
"""
from __future__ import annotations
import logging
import sys
from typing import TYPE_CHECKING
from steam_backlog_enforcer._allowed_games import (
MANUAL_LOCK_DAYS as _MANUAL_LOCK_DAYS,
)
from steam_backlog_enforcer._cmd_done import cmd_done
from steam_backlog_enforcer._cmd_playtime import (
cmd_enforce,
cmd_gaming_reset,
cmd_gaming_status,
cmd_gaming_unblock,
)
from steam_backlog_enforcer._stats import cmd_stats
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.main._registry import _make_all_commands
from steam_backlog_enforcer.main._registry import (
_print_usage as _print_usage_for,
)
from steam_backlog_enforcer.main._registry import (
_resolve_command as _resolve_command_in,
)
from steam_backlog_enforcer.main._shared import (
_MANUAL_LOCK_EXEMPT_COMMANDS,
_MIN_CLI_ARGS,
_TOTAL_BLOCK_EXEMPT_COMMANDS,
_describe_pick,
_enforce_manual_pick_lock,
_enforce_total_block_lock,
_is_manual_pick_locked,
_show_manual_pick_lock_message,
_show_total_block_lock_message,
)
from steam_backlog_enforcer.main.abandon import cmd_abandon_pick
from steam_backlog_enforcer.main.install import (
cmd_hide,
cmd_install,
cmd_installed,
cmd_unhide,
cmd_uninstall,
)
from steam_backlog_enforcer.main.misc import (
cmd_add_exception,
cmd_block_gaming,
cmd_buy_dlc,
cmd_reset,
cmd_serve,
cmd_setup,
cmd_unblock,
)
from steam_backlog_enforcer.main.picks import (
_resolve_game_name,
cmd_pick,
cmd_pick_manual,
)
from steam_backlog_enforcer.main.status import cmd_list, cmd_status
from steam_backlog_enforcer.scanning import do_check, do_scan
if TYPE_CHECKING:
from collections.abc import Callable
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
# Private helpers are re-exported too: they were importable from this module
# before it became a package, and the test-suite reaches for them by name.
__all__ = [
"COMMANDS",
"_MANUAL_LOCK_DAYS",
"_MANUAL_LOCK_EXEMPT_COMMANDS",
"_TOTAL_BLOCK_EXEMPT_COMMANDS",
"_describe_pick",
"_enforce_manual_pick_lock",
"_enforce_total_block_lock",
"_is_manual_pick_locked",
"_print_usage",
"_resolve_command",
"_resolve_game_name",
"_show_manual_pick_lock_message",
"_show_total_block_lock_message",
"cmd_abandon_pick",
"cmd_add_exception",
"cmd_block_gaming",
"cmd_buy_dlc",
"cmd_done",
"cmd_hide",
"cmd_install",
"cmd_installed",
"cmd_list",
"cmd_pick",
"cmd_pick_manual",
"cmd_reset",
"cmd_serve",
"cmd_setup",
"cmd_stats",
"cmd_status",
"cmd_unblock",
"cmd_unhide",
"cmd_uninstall",
"main",
]
COMMANDS: dict[str, tuple[str, Callable[[Config, State], object]]] = {
"scan": ("Scan library & assign a game", do_scan),
"check": ("Check assigned game completion", do_check),
"status": ("Show current status", cmd_status),
"list": ("List games from snapshot", cmd_list),
"install": ("Install the assigned game", cmd_install),
"hide": ("Hide all non-assigned games in library", cmd_hide),
"unhide": ("Unhide all games in library", cmd_unhide),
"unblock": ("Remove store blocking", cmd_unblock),
"buy-dlc": ("Temporarily unblock store to buy DLC", cmd_buy_dlc),
"reset": ("Reset all state", cmd_reset),
"installed": ("List installed games", cmd_installed),
"uninstall": ("Uninstall all non-assigned games", cmd_uninstall),
"setup": ("Run first-time setup", cmd_setup),
"done": ("Finish game, open HLTB, pick next", cmd_done),
"pick": ("Manually pick your next game from candidates", cmd_pick),
"stats": ("Show backlog completion-time estimates", cmd_stats),
"serve": ("Start the interactive web UI (browser) server", cmd_serve),
"gaming-status": ("Show today's gaming time and block state", cmd_gaming_status),
"gaming-reset": ("Reset today's gaming counter (root + YES)", cmd_gaming_reset),
}
# Extra commands with non-standard arg handling (shown in help but not in COMMANDS).
_EXTRA_COMMAND_DESCRIPTIONS: dict[str, str] = {
"add-exception": "Request 24h-locked whitelist exception (use --reason)",
"pick-manual": f"Pick a game by app_id, lock enforcer for {_MANUAL_LOCK_DAYS} days",
"abandon-pick": "Undo a manual pick at any time (needs app_id)",
"block-gaming": "Block ALL gaming for <days> days, no in-app undo",
"enforce": "Run enforcer: block, uninstall, kill, hide (--demo for a 60s budget)",
"gaming-unblock": "Force-release playtime bind mounts (root; recovery hatch)",
}
_ALL_COMMANDS: dict[str, str] = _make_all_commands(
COMMANDS, _EXTRA_COMMAND_DESCRIPTIONS
)
def _resolve_command(raw: str) -> str | None:
"""Map a raw argv[1] onto a known command name (see :mod:`._registry`)."""
return _resolve_command_in(raw, _ALL_COMMANDS)
def _print_usage(unknown: str | None = None) -> None:
"""Print the command list, optionally explaining a bad command."""
_print_usage_for(_ALL_COMMANDS, unknown)
def _dispatch_extra_command(command: str, config: Config, state: State) -> bool:
"""Dispatch commands whose arguments do not fit the ``COMMANDS`` signature.
Split out of :func:`main` to keep its branch count within the complexity
limit; every entry here takes raw ``sys.argv`` tail arguments rather than
the ``(config, state)`` pair ``COMMANDS`` callables receive.
Args:
command: Canonical command name.
config: Loaded configuration.
state: Loaded state.
Returns:
True if *command* was handled here.
"""
if command == "add-exception":
cmd_add_exception(sys.argv[2:])
return True
if command == "block-gaming":
cmd_block_gaming(sys.argv[2:])
return True
if command == "pick-manual":
cmd_pick_manual(config, state, sys.argv[2:])
return True
if command == "abandon-pick":
cmd_abandon_pick(config, state, sys.argv[2:])
return True
if command == "enforce":
sys.exit(cmd_enforce(config, state, sys.argv[2:]))
if command == "gaming-unblock":
sys.exit(cmd_gaming_unblock(sys.argv[2:]))
return False
def main() -> None:
"""CLI entry point."""
if len(sys.argv) < _MIN_CLI_ARGS:
_print_usage()
sys.exit(1)
# Locks below are always given the canonical name, never raw argv,
# so a dashed spelling can never be used to dodge one.
command = _resolve_command(sys.argv[1])
if command is None:
_print_usage(sys.argv[1])
sys.exit(1)
if command != sys.argv[1]:
_echo(f"Note: treating '{sys.argv[1]}' as '{command}'.")
config = Config.load()
if command not in {"setup", "add-exception"} and not config.steam_api_key:
_echo("Not configured. Run 'setup' first.")
sys.exit(1)
state = State.load()
# Total block is the most restrictive lock - check it first.
_enforce_total_block_lock(command)
# Enforce the manual-pick lock before dispatching any command.
# This also covers add-exception (previously dispatched before state load).
_enforce_manual_pick_lock(command, state)
if _dispatch_extra_command(command, config, state):
return
_, func = COMMANDS[command]
func(config, state)

View File

@ -0,0 +1,12 @@
"""``python -m steam_backlog_enforcer.main`` entry point.
Kept as a separate module so the invocation string baked into ``run.sh`` and
the systemd unit stays byte-identical now that ``main`` is a package.
"""
from __future__ import annotations
from steam_backlog_enforcer.main import main
if __name__ == "__main__":
main()

View File

@ -0,0 +1,64 @@
"""Command registry and argv resolution.
Split out of :mod:`steam_backlog_enforcer.main` to keep every module inside the
250-line cap; the tables here are what ``main()`` dispatches on.
"""
from __future__ import annotations
import difflib
from steam_backlog_enforcer.game_install import _echo
def _make_all_commands(
commands: dict[str, tuple[str, object]],
extra: dict[str, str],
) -> dict[str, str]:
"""Merge the dispatchable commands with the raw-argv ones for help/lookup."""
return {name: desc for name, (desc, _) in commands.items()} | extra
def _resolve_command(raw: str, all_commands: dict[str, str]) -> str | None:
"""Map a raw argv[1] onto a known command name.
Subcommands are bare words, but the CLI does use flags elsewhere
(``add-exception --reason``), so ``--abandon-pick`` is the natural
muscle-memory guess. Leading dashes carry no meaning in this slot,
so they are simply stripped rather than rejected.
Parameters:
raw (str): The first CLI argument, exactly as the user typed it.
Returns:
str | None: The canonical command name, or None if unrecognised.
"""
if raw in all_commands:
return raw
if raw.startswith("-"):
stripped = raw.lstrip("-")
if stripped in all_commands:
return stripped
return None
def _print_usage(all_commands: dict[str, str], unknown: str | None = None) -> None:
"""Print the command list, optionally explaining a bad command.
Parameters:
unknown (str | None): The unrecognised argument to report. When None
(the no-arguments case) only the usage block is printed.
"""
if unknown is not None:
_echo(f"Unknown command: {unknown}")
close = difflib.get_close_matches(
unknown.lstrip("-"), all_commands, n=1, cutoff=0.6
)
if close:
_echo(f"Did you mean '{close[0]}'?")
_echo("")
_echo("Steam Backlog Enforcer\n")
_echo("Usage: python -m steam_backlog_enforcer.main <command> [args]\n")
_echo("Commands:")
for name, desc in all_commands.items():
_echo(f" {name:<14s} {desc}")

View File

@ -0,0 +1,184 @@
"""Constants and lock helpers shared by the CLI command modules.
Leaf module: it imports from the wider package but never from a sibling in
``main``, so the command modules can all depend on it without creating an
import cycle.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import sys
from typing import TYPE_CHECKING
from steam_backlog_enforcer._actions import (
active_manual_picks,
manual_pick_age_days,
)
from steam_backlog_enforcer._actions import (
is_manual_pick_locked as _is_manual_pick_locked,
)
from steam_backlog_enforcer._allowed_games import (
MANUAL_LOCK_DAYS as _MANUAL_LOCK_DAYS,
)
from steam_backlog_enforcer._total_block import (
TotalBlockStatus,
get_total_block_status,
is_total_block_active,
)
from steam_backlog_enforcer.game_install import _echo
if TYPE_CHECKING:
from steam_backlog_enforcer.config import State
_LIST_DISPLAY_LIMIT = 50
_MIN_CLI_ARGS = 2
# Commands that remain usable while the manual pick lock is active.
# Principle: only what is needed to release the lock (done/check) or
# that cannot change the game assignment (status, enforce, setup, serve).
_MANUAL_LOCK_EXEMPT_COMMANDS = frozenset(
{
"done",
"check",
"status",
"enforce",
"setup",
"serve",
"abandon-pick",
# Allowed so a second game can be locked in alongside the first; the
# cap inside cmd_pick_manual is what stops this being a way out.
"pick-manual",
# The daily gaming budget is orthogonal to which game is assigned, and
# gaming-unblock is a recovery hatch for a stuck bind mount - locking
# it behind a manual pick would leave Steam masked with no way back.
"gaming-status",
"gaming-unblock",
"gaming-reset",
}
)
# Commands that remain usable while a total gaming block is active. Far
# stricter than _MANUAL_LOCK_EXEMPT_COMMANDS: no done/pick/reset/
# add-exception - there is no in-app way to shorten a total block.
#
# gaming-unblock is included because a playtime bind mount makes the total
# block's own `pacman -R steam` fail EBUSY - it must stay reachable exactly
# when the two collide. gaming-reset is NOT included: it shortens enforcement.
_TOTAL_BLOCK_EXEMPT_COMMANDS = frozenset(
{"status", "enforce", "gaming-status", "gaming-unblock"}
)
# ──────────────────────────────────────────────────────────────
# Total gaming block lock helpers
# ──────────────────────────────────────────────────────────────
def _show_total_block_lock_message(status: TotalBlockStatus) -> None:
"""Print the total-gaming-block-active message to stdout."""
_echo("\n" + "=" * 60)
_echo(" *** TOTAL GAMING BLOCK ACTIVE ***")
_echo("=" * 60)
if status.until is not None:
_echo(f"\nBlocked until: {status.until.strftime('%Y-%m-%d %H:%M UTC')}")
_echo(f"Days remaining: {status.days_remaining:.1f}")
_echo(
"\nSteam has been uninstalled, all known game/launcher processes are"
"\nbeing killed on sight, and Steam + game-website domains are blocked."
"\nThere is NO in-app command to lift this early."
f"\n\nAllowed commands: {', '.join(sorted(_TOTAL_BLOCK_EXEMPT_COMMANDS))}"
)
_echo("=" * 60 + "\n")
def _enforce_total_block_lock(command: str) -> None:
"""Exit with a lock message if command is blocked by an active total block."""
if not is_total_block_active():
return
if command in _TOTAL_BLOCK_EXEMPT_COMMANDS:
return
_show_total_block_lock_message(get_total_block_status())
sys.exit(1)
# ──────────────────────────────────────────────────────────────
# Manual pick lock helpers
# (the predicate itself lives in _actions so the MCP server can reuse it)
# ──────────────────────────────────────────────────────────────
def _describe_pick(state: State, pick: dict[str, object]) -> bool:
"""Print one manual pick's deadline and grace status; return if abandonable.
Args:
state: Current enforcer state.
pick: One active entry from ``state.manual_picks``.
Returns:
Whether this pick is still inside its grace window.
"""
app_id = pick["app_id"]
_echo(f"\n {pick['game_name']} (AppID={app_id})")
started_at = str(pick.get("started_at") or "")
if started_at:
try:
started = datetime.fromisoformat(started_at)
deadline = started + timedelta(days=_MANUAL_LOCK_DAYS)
days_left = (deadline - datetime.now(timezone.utc)).days
_echo(f" Locked since: {started.strftime('%Y-%m-%d')}")
_echo(
f" Deadline: {deadline.strftime('%Y-%m-%d')}"
f" ({max(0, days_left)} day(s) remaining)"
)
except ValueError:
pass
age_days = manual_pick_age_days(state, int(str(app_id)))
if age_days is not None:
_echo(
f" Undo: abandon-pick {app_id}"
f" (picked {age_days:.1f} day(s) ago)"
)
return True
return False
def _show_manual_pick_lock_message(state: State) -> None:
"""Print the aggressive lock-active message to stdout."""
picks = active_manual_picks(state)
_echo("\n" + "=" * 60)
_echo(" *** MANUAL PICK LOCK ACTIVE ***")
_echo("=" * 60)
_echo(f"\nYou manually picked {len(picks)} game(s):")
any_in_grace = False
for pick in picks:
any_in_grace |= _describe_pick(state, pick)
_echo(
"\nYou CANNOT use any other feature until you finish these games"
"\n(100% achievements) or their 2-week deadlines pass."
"\n\nTo release the lock: finish them, then run 'done' or 'check'."
)
# 'abandon-pick' is dropped from the allowed list once no pick is still
# inside its window, rather than offered as a command that would refuse.
usable = set(_MANUAL_LOCK_EXEMPT_COMMANDS)
if not any_in_grace:
usable.discard("abandon-pick")
_echo(f"\nAllowed commands: {', '.join(sorted(usable))}")
_echo("=" * 60 + "\n")
def _enforce_manual_pick_lock(command: str, state: State) -> None:
"""Exit with a lock message if command is blocked by the manual pick."""
if not _is_manual_pick_locked(state):
return
if command in _MANUAL_LOCK_EXEMPT_COMMANDS:
return
_show_manual_pick_lock_message(state)
sys.exit(1)

View File

@ -0,0 +1,121 @@
"""``abandon-pick``: back out of a manual pick."""
from __future__ import annotations
import sys
from typing import TYPE_CHECKING
from steam_backlog_enforcer._actions import (
ABANDON_COOLDOWN_DAYS as _ABANDON_COOLDOWN_DAYS,
)
from steam_backlog_enforcer._actions import (
abandon_manual_pick,
active_manual_picks,
find_manual_pick,
)
from steam_backlog_enforcer.game_install import (
_echo,
is_game_installed,
uninstall_game,
)
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
_ABANDON_PICK_USAGE = (
"Usage: abandon-pick <app_id>\n"
" app_id : the manually-picked game you want to back out of.\n\n"
"A pick can be abandoned at any time, however long ago it was made."
)
def _abandon_pick_target(state: State, args: list[str]) -> int | None:
"""Validate the abandon-pick argument against the active manual pick.
Requiring the explicit app_id (rather than defaulting to the current pick)
makes an accidental abandon impossible to trigger by muscle memory.
Args:
state: Current enforcer state.
args: Remaining CLI args (first element should be the app_id).
Returns:
The validated app id, or ``None`` if the input was unusable (a message
has already been printed in that case).
"""
if not args:
_echo(_ABANDON_PICK_USAGE)
return None
try:
app_id = int(args[0])
except ValueError:
_echo(f"Error: app_id must be a number, got '{args[0]}'.")
return None
picks = active_manual_picks(state)
if not picks:
_echo("No manual pick is active — nothing to abandon.")
return None
if find_manual_pick(state, app_id) is None:
listed = ", ".join(f"{p['game_name']} (AppID={p['app_id']})" for p in picks)
_echo(
f"Error: AppID={app_id} is not one of your manual picks.\nActive: {listed}."
)
return None
return app_id
def cmd_abandon_pick(_config: Config, state: State, args: list[str]) -> None:
"""Back out of a manual pick, whatever its age.
Args:
_config: Enforcer configuration (unused, kept for dispatch symmetry).
state: Current enforcer state.
args: Remaining CLI args (first element should be the app_id).
"""
app_id = _abandon_pick_target(state, args)
if app_id is None:
sys.exit(1)
pick = find_manual_pick(state, app_id)
game_name = str(pick["game_name"]) if pick else ""
others = [p for p in active_manual_picks(state) if p["app_id"] != app_id]
_echo(f"\nAbandoning manual pick: {game_name} (AppID={app_id})")
_echo(
f"\nThis will:"
f"\n - Drop this pick from your allowed games"
f"\n - Uninstall {game_name}"
f"\n - Keep it out of auto-assignment for"
f" {_ABANDON_COOLDOWN_DAYS} days"
)
if others:
kept = ", ".join(f"{p['game_name']} (AppID={p['app_id']})" for p in others)
_echo(f"\n Your other pick(s) stay locked in: {kept}")
else:
_echo("\n - Leaves you with no assigned game (run 'scan' to get one)")
_echo()
confirm = input(f"Type YES to abandon {game_name}: ").strip()
if confirm != "YES":
_echo("Aborted.")
return
abandon_manual_pick(state, app_id)
_echo(f"\nManual pick abandoned: {game_name}")
if is_game_installed(app_id):
_echo(f" Uninstalling {game_name}...")
if uninstall_game(app_id, game_name):
_echo(" Uninstalled.")
else:
_echo(" Warning: could not uninstall — remove it from Steam manually.")
if state.current_app_id is None:
_echo("\nNo game is assigned now. Run 'scan' to get a new assignment,")
_echo("or 'pick-manual <app_id>' to choose one yourself.\n")
else:
_echo(f"\nStill assigned: {state.current_game_name}\n")

View File

@ -0,0 +1,128 @@
"""Install, uninstall and library-visibility commands."""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_backlog_enforcer._actions import allowed_app_ids, allowed_games
from steam_backlog_enforcer._enforce_loop import get_all_owned_app_ids
from steam_backlog_enforcer.game_install import (
_echo,
get_installed_games,
install_game,
is_game_installed,
is_protected_app,
uninstall_other_games,
)
from steam_backlog_enforcer.library_hider import (
try_hide_other_games,
unhide_all_games,
)
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
def cmd_installed(_config: Config, state: State) -> None:
"""Show installed games."""
installed = get_installed_games()
_echo(f"\nInstalled games ({len(installed)}):\n")
for app_id, name in installed:
protected = " [PROTECTED]" if is_protected_app(app_id) else ""
assigned = " <<< ASSIGNED" if app_id == state.current_app_id else ""
_echo(f" {app_id:>8d} {name}{protected}{assigned}")
def cmd_uninstall(_config: Config, state: State) -> None:
"""Uninstall all games except the assigned one."""
if state.current_app_id is None:
_echo("No game assigned. Run 'scan' first.")
return
allowed = allowed_app_ids(state)
installed = get_installed_games()
to_remove = [
(aid, n)
for aid, n in installed
if aid not in allowed and not is_protected_app(aid)
]
if not to_remove:
_echo("No games to uninstall (only allowed games and runtimes installed).")
return
_echo(f"\nWill uninstall {len(to_remove)} games, keeping:")
for aid, name in allowed_games(state):
_echo(f" - {name} (AppID={aid})")
_echo(" - Steam runtimes and Proton versions\n")
_echo("Games to remove:")
for aid, name in to_remove:
_echo(f" - {name} (AppID={aid})")
_echo()
confirm = input("Type YES to confirm: ").strip()
if confirm != "YES":
_echo("Aborted.")
return
count = uninstall_other_games(allowed_app_ids(state))
_echo(f"\nUninstalled {count} games.")
def cmd_install(config: Config, state: State) -> None:
"""Manually trigger install of the assigned game."""
if state.current_app_id is None:
_echo("No game currently assigned. Run 'scan' first.")
return
if is_game_installed(state.current_app_id):
_echo(f"{state.current_game_name} is already installed.")
return
_echo(f"Installing {state.current_game_name} (AppID={state.current_app_id})...")
if install_game(
state.current_app_id,
state.current_game_name,
config.steam_id,
use_steam_protocol=True,
):
_echo("Done!")
else:
_echo("Failed to create install manifest.")
def cmd_hide(config: Config, state: State) -> None:
"""Hide all non-assigned games in the Steam library."""
if state.current_app_id is None:
_echo("No game assigned. Run 'scan' first.")
return
owned_ids = get_all_owned_app_ids(config)
if not owned_ids:
_echo("No owned game list available. Run 'scan' first.")
return
_echo(f"Hiding all games except {state.current_game_name}...")
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f"Library hiding: skipped ({skipped})")
return
_echo(f"Hidden {hidden} games.")
if hidden > 0:
_echo("Done! Only the assigned game should be visible in your library.")
def cmd_unhide(config: Config, _state: State) -> None:
"""Unhide all games in the Steam library."""
owned_ids = get_all_owned_app_ids(config)
if not owned_ids:
_echo("No owned game list available. Run 'scan' first.")
return
_echo("Unhiding all games...")
count = unhide_all_games(owned_ids)
_echo(f"Unhidden {count} games.")
if count > 0:
_echo("Done!")

View File

@ -0,0 +1,203 @@
"""Commands that do not belong to a larger group.
Store blocking, state reset, setup, whitelist exceptions, the web UI and the
total gaming block.
"""
from __future__ import annotations
import sys
from typing import TYPE_CHECKING
from steam_backlog_enforcer._enforce_loop import get_all_owned_app_ids
from steam_backlog_enforcer._total_block import start_total_block
from steam_backlog_enforcer._web_server import serve
from steam_backlog_enforcer._whitelist import (
add_pending_exception,
validate_reason,
)
from steam_backlog_enforcer.config import interactive_setup
from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.library_hider import restart_steam, unhide_all_games
from steam_backlog_enforcer.store_blocker import block_store, unblock_store
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
_MIN_ADD_EXCEPTION_ARGS = 3
_ADD_EXCEPTION_USAGE = (
'Usage: add-exception <app_id> --reason "<justification>"\n'
" app_id : numeric Steam application ID\n"
" --reason : genuine justification (>= 5 words)\n\n"
"Example:\n"
" add-exception 440 --reason "
'"TF2 is needed for a community event this weekend"\n\n'
"Exceptions become active immediately."
)
_BLOCK_GAMING_USAGE = (
"Usage: block-gaming <days>\n"
" days : whole number of days to block ALL gaming:\n"
" Steam uninstalled, all known game/launcher processes killed,\n"
" Steam + game-website domains blocked.\n\n"
"There is NO in-app command to undo this early once confirmed."
)
def cmd_unblock(_config: Config, _state: State) -> None:
"""Remove store blocking."""
if unblock_store():
_echo("Steam store unblocked.")
else:
_echo("Failed to unblock. Run with sudo.")
def cmd_buy_dlc(config: Config, state: State) -> None:
"""Temporarily unblock the store so the user can buy DLC."""
if state.current_app_id is None:
_echo("No game currently assigned.")
return
_echo(f"Current game: {state.current_game_name} (AppID={state.current_app_id})")
_echo("Unblocking Steam store for DLC purchase...")
if not unblock_store():
_echo("Failed to unblock store. Run with sudo.")
return
_echo("\nStore UNBLOCKED — buy your DLC now.")
_echo("Press Enter when you're done to re-block the store...")
input()
if config.block_store:
if block_store():
_echo("Store re-blocked. Restarting Steam to clear DNS cache...")
restart_steam()
_echo("Done.")
else:
_echo("Warning: failed to re-block store.")
def cmd_reset(config: Config, state: State) -> None:
"""Reset all state (unblock, unhide, clear assignment)."""
unblock_store()
# Unhide all games in the library.
try:
owned = get_all_owned_app_ids(config)
if owned:
count = unhide_all_games(owned)
if count:
_echo(f"Unhidden {count} games.")
except (OSError, RuntimeError, ValueError) as exc:
_echo(f"Warning: could not unhide games: {exc}")
state.current_app_id = None
state.current_game_name = ""
state.finished_app_ids = []
state.manual_pick_app_id = None
state.manual_pick_game_name = ""
state.manual_pick_started_at = ""
state.manual_picks = []
state.save()
_echo("State reset. Store unblocked.")
def cmd_setup(_config: Config, _state: State) -> None:
"""Run interactive setup."""
interactive_setup()
def cmd_serve(_config: Config, _state: State) -> None:
"""Start the interactive web UI server (read-only, localhost only)."""
serve()
def cmd_add_exception(args: list[str]) -> None:
"""Add a whitelist exception, active immediately.
Usage: add-exception <app_id> --reason "<text>"
The exception becomes active right away (no cooldown). The reason must be
a genuine justification of at least 5 words with sufficient entropy.
Args:
args: CLI argument list after the command name.
"""
if len(args) < _MIN_ADD_EXCEPTION_ARGS or "--reason" not in args:
_echo(_ADD_EXCEPTION_USAGE)
sys.exit(1)
try:
app_id = int(args[0])
except ValueError:
_echo(f"Error: app_id must be a number, got '{args[0]}'.")
sys.exit(1)
reason_idx = args.index("--reason")
reason_parts = args[reason_idx + 1 :]
if not reason_parts:
_echo("Error: --reason requires a value.")
sys.exit(1)
reason = " ".join(reason_parts)
# Show validation feedback before attempting to add.
err = validate_reason(reason)
if err is not None:
_echo(f"Invalid reason: {err}")
sys.exit(1)
try:
msg = add_pending_exception(app_id, reason)
except ValueError as exc:
_echo(f"Error: {exc}")
sys.exit(1)
_echo(msg)
def cmd_block_gaming(args: list[str]) -> None:
"""Start a total gaming block for a fixed number of days.
Usage: block-gaming <days>
Args:
args: Remaining CLI args (first element should be the day count).
"""
if not args:
_echo(_BLOCK_GAMING_USAGE)
sys.exit(1)
try:
days = int(args[0])
except ValueError:
_echo(f"Error: days must be a whole number, got '{args[0]}'.")
sys.exit(1)
if days < 1:
_echo("Error: days must be at least 1.")
sys.exit(1)
_echo(
f"\nWARNING: This will, for the next {days} day(s):"
f"\n - Uninstall Steam"
f"\n - Kill Steam and all known game-launcher processes on sight"
f"\n - Block all Steam network domains AND known browser/flash"
f"\n game websites"
f"\n\nThere is NO in-app command to undo this early. It can only be"
f"\nlifted by waiting out the {days} day(s), or by manual root-level"
f"\nsystem administration outside this tool."
)
_echo()
confirm = input(f"Type YES to confirm a {days}-day total gaming block: ").strip()
if confirm != "YES":
_echo("Aborted.")
return
_echo("\nStarting total gaming block...")
if start_total_block(days):
_echo(f"Total gaming block ACTIVE for {days} day(s).")
_echo("Run 'status' to check remaining time.")
else:
_echo("Error: failed to engage the block (see logs). Run with sudo?")
sys.exit(1)

Some files were not shown because too many files have changed in this diff Show More