From ba7b502322e0e391fa5b8fcbf21d49500241809c Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Thu, 12 Nov 2026 08:02:05 +0100 Subject: [PATCH] Monitors: survive boot, biggest is primary The watcher started at the LightDM greeter, X refused it, and it hit the systemd restart limit in 15 s, so DP-2 never came up. It now waits for X, the unit passes XAUTHORITY, and i3 restarts it at login. The biggest monitor is now primary and leftmost (DP-0 was hardcoded). Prunes the oldest evidence file (60-file cap). CI_GREEN_SKIP: main is red from a runner DNS outage (apt could not resolve security.ubuntu.com), not code; failed jobs re-run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WzxdWWTekMNwEdyLgWRgTs --- .../monitor-autoconfig-boot-2026-11-12.json | 12 +++++ .../monitor-autoconfig-boot-2026-11-12.json | 38 +++++++++++++++ ...audit-v2-and-repo-contract-2026-10-04.json | 41 ----------------- .../features/monitor_autoconfig.py | 32 +++++++++---- .../features/monitor_layout.py | 18 +++++--- .../features/setup_monitor_autoconfig.sh | 2 +- .../systemd/monitor-autoconfig.service | 2 + linux_configuration/i3/config | 6 +++ .../tests/test_monitor_autoconfig.py | 46 ++++++++++++++----- .../tests/test_monitor_layout.py | 30 ++++++++++-- 10 files changed, 155 insertions(+), 72 deletions(-) create mode 100644 docs/superpowers/contracts/monitor-autoconfig-boot-2026-11-12.json create mode 100644 docs/superpowers/evidence/monitor-autoconfig-boot-2026-11-12.json delete mode 100644 docs/superpowers/evidence/token-audit-v2-and-repo-contract-2026-10-04.json diff --git a/docs/superpowers/contracts/monitor-autoconfig-boot-2026-11-12.json b/docs/superpowers/contracts/monitor-autoconfig-boot-2026-11-12.json new file mode 100644 index 00000000..91fb15c0 --- /dev/null +++ b/docs/superpowers/contracts/monitor-autoconfig-boot-2026-11-12.json @@ -0,0 +1,12 @@ +{ + "title": "Monitor autoconfig: survive boot, biggest monitor primary", + "objective": "DP-2 (4K) connects automatically on every boot and hotplug with no manual xrandr: the watcher waits for X at the LightDM greeter instead of crashing, and the biggest monitor becomes primary and leftmost.", + "acceptance_criteria": [ + "plan(outputs) with no primary named puts the largest native mode first at 0x0 with --primary", + "_open_display retries on DisplayConnectionError instead of exiting", + "unit sets XAUTHORITY=%h/.Xauthority; i3 config restarts the unit on login/reload", + "live: xrandr --listmonitors shows DP-2 primary 3840x2160+0+0 and HDMI-0 at +3840+0" + ], + "out_of_scope": ["Per-monitor custom layouts", "Wayland"], + "verifier": "python3 -m pytest -q linux_configuration/tests/test_monitor_layout.py linux_configuration/tests/test_monitor_autoconfig.py; pre-commit run --files " +} diff --git a/docs/superpowers/evidence/monitor-autoconfig-boot-2026-11-12.json b/docs/superpowers/evidence/monitor-autoconfig-boot-2026-11-12.json new file mode 100644 index 00000000..c251c1f7 --- /dev/null +++ b/docs/superpowers/evidence/monitor-autoconfig-boot-2026-11-12.json @@ -0,0 +1,38 @@ +{ + "intent": "DP-2 connects automatically at every boot; the biggest monitor is primary and leftmost.", + "scope": [ + "linux_configuration/features/monitor_{layout,autoconfig}.py, unit, setup script", + "linux_configuration/i3/config", + "Non-goal: per-monitor custom layouts" + ], + "changes": [ + "monitor_autoconfig._open_display waits (2 s steps) while X refuses the connection; the unit no longer burns its restart limit at the greeter", + "Unit sets XAUTHORITY=%h/.Xauthority; i3 exec_always restarts the unit at login and reload", + "Default primary is now the connected output with the largest best mode (was hardcoded DP-0, absent on this machine)" + ], + "verification": [ + { + "command": "python3 -m pytest -q linux_configuration/tests/test_monitor_layout.py linux_configuration/tests/test_monitor_autoconfig.py", + "result": "pass", + "evidence": "4 new tests red before the change; 26 passed after" + }, + { + "command": "setup_monitor_autoconfig.sh && xrandr --listmonitors", + "result": "pass", + "evidence": "applied: DP-2 3840x2160@144 --pos 0x0 --primary, HDMI-0 2560x1440@143.98 --pos 3840x0; kuhy confirmed layout" + }, + { + "command": "XAUTHORITY=/dev/null timeout 7 monitor_autoconfig.py", + "result": "pass", + "evidence": "exit 124: still waiting for X, no crash" + } + ], + "risks": [ + "Watcher waits forever if X never accepts it (cheap: one connect attempt per 2 s)", + "exec_always restart re-applies the layout on i3 reload, overriding a manual xrandr change" + ], + "rollback": [ + "git revert this commit, rerun setup_monitor_autoconfig.sh, copy i3/config to ~/.config/i3/config", + "Check systemctl --user status monitor-autoconfig" + ] +} diff --git a/docs/superpowers/evidence/token-audit-v2-and-repo-contract-2026-10-04.json b/docs/superpowers/evidence/token-audit-v2-and-repo-contract-2026-10-04.json deleted file mode 100644 index d418ee89..00000000 --- a/docs/superpowers/evidence/token-audit-v2-and-repo-contract-2026-10-04.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "intent": "token_audit reports real spend: deduplicated per-message usage, subagent sidechains included, per-model USD, time-windowed snapshots + lever ledger scored by /token-optimization; testsAndMisc gets the shared repo contract (CLAUDE.md Commands, scripts/test_changed.sh, CI gate) and newest-stable pins.", - "scope": [ - "python_pkg/token_audit: records, discover, pricing (+prices.json), history, breakdown, recommend, review, turns (new); parse, model, __main__ (edited); tests for every module", - "repo contract: scripts/check_repo_contract.sh, scripts/test_changed.sh, .github/workflows/repo-contract.yml, AGENTS.md Commands, pre-commit hook", - "meta/requirements.txt: pylint 4.1.2, websockets 17.2, pyflakes 4.0.2 (main CI was red on freshness)", - "Rides along from other sessions: ci_mirror async (own evidence JSON 2026-09-11), app-icons evidence, endurain_import duplicate ADB_SERIAL_ENV block removed", - "Non-goal: changing the hooks in ~/.claude that consume these reports" - ], - "changes": [ - "Usage is counted once per API message id (transcripts repeat it per content block: 1.9x overcount before)", - "Subagent transcripts are discovered and attributed (were 35% of spend and invisible)", - "Each run analyses only records after the previous snapshot, writes history/.json and scores ledger levers against it; usd_per_commit metric", - "history.py resolves REPORT_DIR at call time so tests redirect it; parse split into parse + turns to stay under 250 lines and complexity 10; Breakdown groups tallies (old attribute names kept as properties)" - ], - "verification": [ - { - "command": "~/.claude/scripts/capped.sh python3 -m pytest python_pkg/token_audit python_pkg/endurain_import -q --cov-branch", - "result": "pass", - "evidence": "291 passed; every python_pkg/token_audit module at 100% line+branch coverage (1108 stmts, 260 branches, 0 missed)" - }, - { - "command": "~/.claude/scripts/capped.sh python3 -m python_pkg.token_audit --no-write", - "result": "pass", - "evidence": "Analysed 20-24 sessions in 0.15s; window starts at the previous snapshot; ~/.claude/token-report file list and mtimes unchanged by the test suite" - }, - { - "command": "scripts/check_dependency_freshness.sh --all", - "result": "pass", - "evidence": "after bumping pylint, websockets, pyflakes (flake8 7.4.1 allows pyflakes <4.1.0)" - } - ], - "risks": [ - "Absolute USD figures before 2026-10-04 double-counted ~1.9x; comparisons across that date are rate-only.", - "prices.json must be updated when Anthropic prices change; unknown models price at 0 and are listed." - ], - "rollback": [ - "git revert : token_audit v1 report format returns; no data migration needed", - "Snapshots under ~/.claude/token-report/history are additive and can stay" - ] -} diff --git a/linux_configuration/features/monitor_autoconfig.py b/linux_configuration/features/monitor_autoconfig.py index b2350ee5..42e62771 100755 --- a/linux_configuration/features/monitor_autoconfig.py +++ b/linux_configuration/features/monitor_autoconfig.py @@ -36,6 +36,10 @@ OUTPUT_CHANGE_MASK = 4 SETTLE_SECONDS = 1.0 # How many settle periods to wait for a connected monitor to list any mode. MODE_TRIES = 5 +# At boot the user manager starts this unit while LightDM's greeter still owns +# :0, so X refuses us until kuhy logs in. Wait for that instead of exiting: +# exiting burned the restart limit in 15 s on 2026-11-12 and left DP-2 dark. +CONNECT_WAIT = 2.0 class _Root(Protocol): @@ -91,7 +95,7 @@ def _query( def apply_once( - primary: str, + primary: str | None, run: Callable[[list[str]], str] = _run, settle: Callable[[], None] = _settle, tries: int = MODE_TRIES, @@ -107,7 +111,7 @@ def apply_once( def _safe_apply( - primary: str, run: Callable[[list[str]], str], settle: Callable[[], None] + primary: str | None, run: Callable[[list[str]], str], settle: Callable[[], None] ) -> None: """Apply, but log a failed xrandr instead of dying. @@ -119,14 +123,24 @@ def _safe_apply( sys.stderr.write(f"xrandr failed ({error.returncode}): {error.stderr}\n") -def _open_display() -> Display: - """Connect to ``$DISPLAY`` (Xlib imported lazily; tests never need it).""" - display: Display = importlib.import_module("Xlib.display").Display() - return display +def _open_display(sleep: Callable[[float], None] = time.sleep) -> Display: + """Connect to ``$DISPLAY``, waiting as long as X refuses (greeter, no login). + + Xlib is imported lazily so the tests never need it. + """ + xlib_display = importlib.import_module("Xlib.display") + refused = importlib.import_module("Xlib.error").DisplayConnectionError + while True: + try: + display: Display = xlib_display.Display() + except refused: + sleep(CONNECT_WAIT) + else: + return display def watch( - primary: str, + primary: str | None, display: Display | None = None, run: Callable[[list[str]], str] = _run, settle: Callable[[], None] = _settle, @@ -150,7 +164,9 @@ def watch( def main(argv: list[str] | None = None, run: Callable[[list[str]], str] = _run) -> int: """CLI entry point.""" parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--primary", default="DP-0", help="leftmost primary output") + parser.add_argument( + "--primary", default=None, help="leftmost primary (default: biggest)" + ) mode = parser.add_mutually_exclusive_group() mode.add_argument("--once", action="store_true", help="apply and exit") mode.add_argument("--dry-run", action="store_true", help="print, change nothing") diff --git a/linux_configuration/features/monitor_layout.py b/linux_configuration/features/monitor_layout.py index b8f4cb7f..7506d3ad 100755 --- a/linux_configuration/features/monitor_layout.py +++ b/linux_configuration/features/monitor_layout.py @@ -10,9 +10,10 @@ Policy, agreed 2026-11-11: highest refresh rate offered for that size. A bigger listed size is a downscale, not "better". Without a preferred mode: largest area, then fastest, interlaced modes skipped. -- layout = one row at y=0; the preferred primary (default DP-0) leftmost, - the rest in xrandr order to its right. If it is absent, the first - connected output is primary. +- layout = one row at y=0; the primary leftmost, the rest in xrandr order + to its right. Primary = the monitor whose best mode has the most pixels + (agreed 2026-11-12; ties keep xrandr order), unless one is named and + connected. - disconnected outputs that still hold a CRTC are switched off, so no gap. """ @@ -104,14 +105,17 @@ def pick_mode(output: Output) -> Mode | None: return max(candidates, key=lambda m: (m.width * m.height, float(m.rate))) -def _ordered(outputs: list[Output], primary: str) -> list[tuple[Output, Mode]]: - """Connected outputs with a usable mode, preferred primary first.""" +def _ordered(outputs: list[Output], primary: str | None) -> list[tuple[Output, Mode]]: + """Connected outputs with a usable mode, primary first.""" usable = [(o, m) for o in outputs if o.connected and (m := pick_mode(o))] + if usable and primary not in {o.name for o, _ in usable}: + biggest = max(usable, key=lambda pair: pair[1].width * pair[1].height) + primary = biggest[0].name usable.sort(key=lambda pair: pair[0].name != primary) return usable -def plan(outputs: list[Output], primary: str) -> list[str]: +def plan(outputs: list[Output], primary: str | None = None) -> list[str]: """Return the xrandr arguments to reach the policy, ``[]`` if already there.""" row = _ordered(outputs, primary) args: list[str] = [] @@ -134,7 +138,7 @@ def plan(outputs: list[Output], primary: str) -> list[str]: def main() -> int: """Print the plan for ``xrandr --query`` text read from stdin.""" - sys.stdout.write(" ".join(plan(parse_xrandr(sys.stdin.read()), "DP-0")) + "\n") + sys.stdout.write(" ".join(plan(parse_xrandr(sys.stdin.read()))) + "\n") return 0 diff --git a/linux_configuration/features/setup_monitor_autoconfig.sh b/linux_configuration/features/setup_monitor_autoconfig.sh index 07718d84..2de18fb2 100755 --- a/linux_configuration/features/setup_monitor_autoconfig.sh +++ b/linux_configuration/features/setup_monitor_autoconfig.sh @@ -4,7 +4,7 @@ # Installs the monitor-autoconfig systemd user service. It applies the layout # at login and again whenever a monitor is plugged or unplugged: # - each monitor runs its native resolution at the highest refresh rate; -# - DP-0 is primary and leftmost, the others sit to its right; +# - the biggest monitor is primary and leftmost, the others to its right; # - an unplugged monitor is switched off so no gap is left. # Policy lives in monitor_layout.py; the watcher in monitor_autoconfig.py. # diff --git a/linux_configuration/features/systemd/monitor-autoconfig.service b/linux_configuration/features/systemd/monitor-autoconfig.service index 32e5c5e0..97c2a7ad 100644 --- a/linux_configuration/features/systemd/monitor-autoconfig.service +++ b/linux_configuration/features/systemd/monitor-autoconfig.service @@ -9,6 +9,8 @@ StartLimitBurst=5 [Service] Type=simple Environment=DISPLAY=:0 +# The login's cookie; i3 may not have exported XAUTHORITY to systemd yet. +Environment=XAUTHORITY=%h/.Xauthority ExecStart=/usr/bin/python3 @FEATURES_DIR@/monitor_autoconfig.py Restart=on-failure RestartSec=3s diff --git a/linux_configuration/i3/config b/linux_configuration/i3/config index 865b7408..0029f5b0 100644 --- a/linux_configuration/i3/config +++ b/linux_configuration/i3/config @@ -48,6 +48,12 @@ exec --no-startup-id systemctl --user start leetcode-guard.service # window), so starting it here as well costs nothing. exec --no-startup-id systemctl --user start book-guard.service +# Monitor autoconfig (features/monitor_autoconfig.py): every monitor at its +# best mode, the biggest one primary and leftmost, re-applied on hotplug. At +# boot the unit starts at the LightDM greeter and waits for X; this restart +# re-arms it at login (and on i3 reload) even if systemd gave up on it. +exec_always --no-startup-id systemctl --user restart monitor-autoconfig.service + # Wallpaper rotator (python_pkg/wallpaper_rotator): a dark, text-free # background, new every 3 hours via a 15-minute systemd timer. This start # paints right at login instead of at the next tick. Installed by diff --git a/linux_configuration/tests/test_monitor_autoconfig.py b/linux_configuration/tests/test_monitor_autoconfig.py index a30a9555..731be8d7 100644 --- a/linux_configuration/tests/test_monitor_autoconfig.py +++ b/linux_configuration/tests/test_monitor_autoconfig.py @@ -2,6 +2,7 @@ from __future__ import annotations +from pathlib import Path import subprocess from types import SimpleNamespace from typing import TYPE_CHECKING @@ -130,7 +131,7 @@ def test_main_default_watches(monkeypatch: pytest.MonkeyPatch) -> None: seen: list[str] = [] monkeypatch.setattr(monitor_autoconfig, "watch", seen.append) assert main([]) == 0 - assert seen == ["DP-0"] + assert seen == [None] def test_apply_once_waits_for_late_edid_modes() -> None: @@ -171,19 +172,42 @@ def test_run_returns_stdout(monkeypatch: pytest.MonkeyPatch) -> None: assert calls[0][1]["check"] is True -def test_open_display_uses_xlib(monkeypatch: pytest.MonkeyPatch) -> None: - """The real display comes from ``Xlib.display.Display()``.""" - sentinel = object() - fake_module = SimpleNamespace(Display=lambda: sentinel) - monkeypatch.setattr( - monitor_autoconfig.importlib, "import_module", lambda name: fake_module - ) - assert monitor_autoconfig._open_display() is sentinel - - def test_settle_sleeps_settle_seconds(monkeypatch: pytest.MonkeyPatch) -> None: """The real settle waits ``SETTLE_SECONDS`` for EDID to arrive.""" slept: list[float] = [] monkeypatch.setattr(monitor_autoconfig.time, "sleep", slept.append) monitor_autoconfig._settle() assert slept == [monitor_autoconfig.SETTLE_SECONDS] + + +class _RefusedError(Exception): + """Stands in for ``Xlib.error.DisplayConnectionError``.""" + + +def test_open_display_waits_for_login(monkeypatch: pytest.MonkeyPatch) -> None: + """At the greeter X refuses us; keep retrying until the login's auth works.""" + sentinel = object() + answers: list[object] = [_RefusedError(), _RefusedError(), sentinel] + + def display() -> object: + answer = answers.pop(0) + if isinstance(answer, Exception): + raise answer + return answer + + modules = { + "Xlib.display": SimpleNamespace(Display=display), + "Xlib.error": SimpleNamespace(DisplayConnectionError=_RefusedError), + } + monkeypatch.setattr(monitor_autoconfig.importlib, "import_module", modules.get) + slept: list[float] = [] + assert monitor_autoconfig._open_display(sleep=slept.append) is sentinel + assert slept == [monitor_autoconfig.CONNECT_WAIT] * 2 + + +def test_unit_passes_xauthority() -> None: + """The unit must find the login's X cookie even before i3 exports it.""" + unit = ( + Path(monitor_autoconfig.__file__).parent / "systemd/monitor-autoconfig.service" + ) + assert "Environment=XAUTHORITY=%h/.Xauthority" in unit.read_text() diff --git a/linux_configuration/tests/test_monitor_layout.py b/linux_configuration/tests/test_monitor_layout.py index 9337bee3..b7d884ba 100644 --- a/linux_configuration/tests/test_monitor_layout.py +++ b/linux_configuration/tests/test_monitor_layout.py @@ -56,6 +56,19 @@ DP-1 connected {AXES} 1280x1024 85.00 """ +# Real `xrandr --query` from 2026-11-12: DP-2 (4K) connected but off. The +# bigger monitor must become primary and leftmost without naming it. +DP2_OFF = f"""\ +Screen 0: minimum 8 x 8, current 6400 x 1440, maximum 32767 x 32767 +HDMI-0 connected primary 2560x1440+3840+0 {AXES} 600mm x 330mm + 2560x1440 59.95 + 143.98* 120.00 + 3840x2160 59.94 50.00 +DP-1 disconnected {AXES} +DP-2 connected {AXES} + 3840x2160 60.00 + 144.00 119.88 100.00 + 2560x1440 144.00 120.00 +""" + HDMI_BEST = ["--output", "HDMI-0", "--mode", "2560x1440", "--rate", "143.98"] @@ -125,10 +138,19 @@ class TestPlan: "--output", "DP-0", "--off", ] # fmt: skip - def test_unknown_primary_uses_first_connected(self) -> None: - """A missing preferred primary falls back to xrandr order.""" - args = plan(parse_xrandr(DP0_OFF), "DP-9") - assert args[:9] == [*HDMI_BEST, "--pos", "0x0", "--primary"] + def test_unknown_primary_uses_biggest(self) -> None: + """A named primary that is not connected falls back to the biggest.""" + args = plan(parse_xrandr(DP2_OFF), "DP-9") + assert args[:10] == plan(parse_xrandr(DP2_OFF))[:10] + assert args[1] == "DP-2" + + def test_no_primary_named_picks_biggest_native_leftmost(self) -> None: + """``primary=None``: the largest native mode (DP-2 4K) leads the row.""" + assert plan(parse_xrandr(DP2_OFF), None) == [ + "--output", "DP-2", "--mode", "3840x2160", "--rate", "144.00", + "--pos", "0x0", "--primary", + *HDMI_BEST, "--pos", "3840x0", + ] # fmt: skip def test_nothing_connected_is_noop(self) -> None: """No connected output means no xrandr call at all."""