From b5b4b35c0721db64f946f682211c82cc3a2189f7 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Sun, 23 Aug 2026 20:52:08 +0200 Subject: [PATCH] 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) Claude-Session: https://claude.ai/code/session_01PPpmMpTSkp8UziRc5u8B7P --- steam_backlog_enforcer/_cmd_playtime.py | 12 +- steam_backlog_enforcer/_mcp.py | 423 +------- steam_backlog_enforcer/_mcp_actions.py | 188 ++++ steam_backlog_enforcer/_mcp_gaming_time.py | 109 ++ steam_backlog_enforcer/_mcp_query.py | 98 ++ steam_backlog_enforcer/_mcp_server.py | 83 ++ steam_backlog_enforcer/_pacman.py | 78 ++ steam_backlog_enforcer/_playtime.py | 496 +-------- steam_backlog_enforcer/_playtime_block.py | 222 +--- steam_backlog_enforcer/_playtime_budget.py | 98 ++ steam_backlog_enforcer/_playtime_cutoff.py | 125 +++ steam_backlog_enforcer/_playtime_kill.py | 176 ++++ steam_backlog_enforcer/_playtime_mountinfo.py | 59 ++ steam_backlog_enforcer/_playtime_notify.py | 51 + steam_backlog_enforcer/_playtime_procs.py | 111 ++ steam_backlog_enforcer/_playtime_run.py | 34 + steam_backlog_enforcer/_playtime_state.py | 196 ++++ steam_backlog_enforcer/_total_block.py | 653 +----------- .../_total_block_domains.py | 64 ++ steam_backlog_enforcer/_total_block_hosts.py | 86 ++ .../_total_block_iptables.py | 195 ++++ .../_total_block_launchers.py | 45 + steam_backlog_enforcer/_total_block_purge.py | 218 ++++ .../tests/_isolate_playtime.py | 85 ++ .../tests/_no_subprocess.py | 79 ++ .../tests/_total_block_paths.py | 78 ++ steam_backlog_enforcer/tests/conftest.py | 168 +-- .../tests/test_cmd_playtime.py | 6 +- steam_backlog_enforcer/tests/test_mcp.py | 298 +----- .../tests/test_mcp_actions.py | 155 +++ .../tests/test_mcp_gaming_time.py | 112 ++ steam_backlog_enforcer/tests/test_pacman.py | 84 ++ steam_backlog_enforcer/tests/test_playtime.py | 20 +- .../tests/test_playtime_block.py | 47 +- .../tests/test_playtime_block_part2.py | 304 +----- .../tests/test_playtime_cutoff.py | 198 ++++ .../tests/test_playtime_kill.py | 161 +++ .../tests/test_playtime_part2.py | 146 +-- .../tests/test_playtime_procs.py | 183 ++++ .../tests/test_playtime_proctree.py | 204 ++++ .../tests/test_playtime_tick.py | 184 +--- .../tests/test_total_block.py | 980 +----------------- .../tests/test_total_block_hosts.py | 128 +++ .../tests/test_total_block_iptables.py | 194 ++++ .../tests/test_total_block_lifecycle.py | 204 ++++ .../tests/test_total_block_purge.py | 178 ++++ .../tests/test_total_block_remnants.py | 173 ++++ 47 files changed, 4558 insertions(+), 3631 deletions(-) create mode 100644 steam_backlog_enforcer/_mcp_actions.py create mode 100644 steam_backlog_enforcer/_mcp_gaming_time.py create mode 100644 steam_backlog_enforcer/_mcp_query.py create mode 100644 steam_backlog_enforcer/_mcp_server.py create mode 100644 steam_backlog_enforcer/_pacman.py create mode 100644 steam_backlog_enforcer/_playtime_budget.py create mode 100644 steam_backlog_enforcer/_playtime_cutoff.py create mode 100644 steam_backlog_enforcer/_playtime_kill.py create mode 100644 steam_backlog_enforcer/_playtime_mountinfo.py create mode 100644 steam_backlog_enforcer/_playtime_notify.py create mode 100644 steam_backlog_enforcer/_playtime_procs.py create mode 100644 steam_backlog_enforcer/_playtime_run.py create mode 100644 steam_backlog_enforcer/_playtime_state.py create mode 100644 steam_backlog_enforcer/_total_block_domains.py create mode 100644 steam_backlog_enforcer/_total_block_hosts.py create mode 100644 steam_backlog_enforcer/_total_block_iptables.py create mode 100644 steam_backlog_enforcer/_total_block_launchers.py create mode 100644 steam_backlog_enforcer/_total_block_purge.py create mode 100644 steam_backlog_enforcer/tests/_isolate_playtime.py create mode 100644 steam_backlog_enforcer/tests/_no_subprocess.py create mode 100644 steam_backlog_enforcer/tests/_total_block_paths.py create mode 100644 steam_backlog_enforcer/tests/test_mcp_actions.py create mode 100644 steam_backlog_enforcer/tests/test_mcp_gaming_time.py create mode 100644 steam_backlog_enforcer/tests/test_pacman.py create mode 100644 steam_backlog_enforcer/tests/test_playtime_cutoff.py create mode 100644 steam_backlog_enforcer/tests/test_playtime_kill.py create mode 100644 steam_backlog_enforcer/tests/test_playtime_procs.py create mode 100644 steam_backlog_enforcer/tests/test_playtime_proctree.py create mode 100644 steam_backlog_enforcer/tests/test_total_block_hosts.py create mode 100644 steam_backlog_enforcer/tests/test_total_block_iptables.py create mode 100644 steam_backlog_enforcer/tests/test_total_block_lifecycle.py create mode 100644 steam_backlog_enforcer/tests/test_total_block_purge.py create mode 100644 steam_backlog_enforcer/tests/test_total_block_remnants.py diff --git a/steam_backlog_enforcer/_cmd_playtime.py b/steam_backlog_enforcer/_cmd_playtime.py index abe8f9a..893549e 100644 --- a/steam_backlog_enforcer/_cmd_playtime.py +++ b/steam_backlog_enforcer/_cmd_playtime.py @@ -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: diff --git a/steam_backlog_enforcer/_mcp.py b/steam_backlog_enforcer/_mcp.py index a7df7c6..38fb8a0 100644 --- a/steam_backlog_enforcer/_mcp.py +++ b/steam_backlog_enforcer/_mcp.py @@ -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: diff --git a/steam_backlog_enforcer/_mcp_actions.py b/steam_backlog_enforcer/_mcp_actions.py new file mode 100644 index 0000000..23bda1f --- /dev/null +++ b/steam_backlog_enforcer/_mcp_actions.py @@ -0,0 +1,188 @@ +"""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, + MANUAL_GRACE_DAYS, + abandon_manual_pick, + active_manual_picks, + apply_manual_pick, + can_abandon_manual_pick, + find_manual_pick, + manual_pick_grace_remaining, +) +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 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} diff --git a/steam_backlog_enforcer/_mcp_gaming_time.py b/steam_backlog_enforcer/_mcp_gaming_time.py new file mode 100644 index 0000000..515d3d9 --- /dev/null +++ b/steam_backlog_enforcer/_mcp_gaming_time.py @@ -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], + } diff --git a/steam_backlog_enforcer/_mcp_query.py b/steam_backlog_enforcer/_mcp_query.py new file mode 100644 index 0000000..b2df7f7 --- /dev/null +++ b/steam_backlog_enforcer/_mcp_query.py @@ -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) +# ────────────────────────────────────────────────────────────── diff --git a/steam_backlog_enforcer/_mcp_server.py b/steam_backlog_enforcer/_mcp_server.py new file mode 100644 index 0000000..299bb7d --- /dev/null +++ b/steam_backlog_enforcer/_mcp_server.py @@ -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) +# ────────────────────────────────────────────────────────────── diff --git a/steam_backlog_enforcer/_pacman.py b/steam_backlog_enforcer/_pacman.py new file mode 100644 index 0000000..9f9a438 --- /dev/null +++ b/steam_backlog_enforcer/_pacman.py @@ -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 diff --git a/steam_backlog_enforcer/_playtime.py b/steam_backlog_enforcer/_playtime.py index a07767b..3de5064 100644 --- a/steam_backlog_enforcer/_playtime.py +++ b/steam_backlog_enforcer/_playtime.py @@ -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 `