feat: skip runs while another game (P3R) is running

Automatic counterpart to the manual pause switch: while any process in
config.GAME_BUSY_PROCESSES (currently P3R.exe) is running on nik-gpu,
ba_daily.py exits with BUSY_EXIT_CODE (76) instead of letting xdotool
take over the mouse/keyboard mid-game. Same scope as pause (cron and
manual runs), and re-checked between tasks so a game started mid-run
stops the sequence after the current task returns home.

New run_check meta-command (ACTIVE/PAUSED/BUSY, exit 0/75/76) lets
ba_cron_run.sh skip before its "Starting" Discord alert, which also
stops paused runs from posting an unmatched start alert. A 76 from the
real run logs "STOPPED early" with an info alert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Nik Afiq 2026-10-13 19:45:29 +09:00
parent 0bdd1919c4
commit c87151bdf8
4 changed files with 134 additions and 16 deletions

View File

@ -239,7 +239,7 @@ As of 2026-07-16, `ba_dailies.sh` presets run unattended on a schedule via cron
0 1,5,9,13,17,21 * * * /home/nik/repo/ba-auto-daily/ba_cron_run.sh q4h
```
Times are nik-gpu's local system time (`Asia/Tokyo`/JST). `ba_cron_run.sh` (repo root, run directly from the checkout -- see "Deployment model" above) wraps `ba_dailies.sh <preset>` (resolved as the sibling file next to its own `BASH_SOURCE`) in a shared, non-blocking `flock` (`~/ba_logs/ba_dailies.lock`) so overlapping fire times can never launch concurrent `xdotool`/`scrot` sessions against the same game window, and logs each run to its own `~/ba_logs/<preset>.log` (`daily.log`/`q4h.log`, never interleaved). It contains no game-automation logic -- pure locking/logging plumbing, same category as `ba_dailies.sh` itself. To check whether a scheduled run actually worked: `grep -E 'FAILED|SKIPPED' ~/ba_logs/*.log` -- every run logs one of `OK`/`FAILED (exit N)`/`SKIPPED (previous run still in progress)`/`SKIPPED (paused)` (see "Manual pause switch" below), deliberately distinct outcomes (a lock-skip and a genuinely crashed task both exit 1, so the wrapper checks lock acquisition as its own explicit step rather than folding it into the wrapped command's exit code).
Times are nik-gpu's local system time (`Asia/Tokyo`/JST). `ba_cron_run.sh` (repo root, run directly from the checkout -- see "Deployment model" above) wraps `ba_dailies.sh <preset>` (resolved as the sibling file next to its own `BASH_SOURCE`) in a shared, non-blocking `flock` (`~/ba_logs/ba_dailies.lock`) so overlapping fire times can never launch concurrent `xdotool`/`scrot` sessions against the same game window, and logs each run to its own `~/ba_logs/<preset>.log` (`daily.log`/`q4h.log`, never interleaved). It contains no game-automation logic -- pure locking/logging plumbing, same category as `ba_dailies.sh` itself. To check whether a scheduled run actually worked: `grep -E 'FAILED|SKIPPED|STOPPED' ~/ba_logs/*.log` -- every run logs one of `OK`/`FAILED (exit N)`/`SKIPPED (previous run still in progress)`/`SKIPPED (paused)`/`SKIPPED (game running)`/`STOPPED early (game started mid-run)` (see "Manual pause switch" and "Automatic skip while playing another game" below), deliberately distinct outcomes (a lock-skip and a genuinely crashed task both exit 1, so the wrapper checks lock acquisition as its own explicit step rather than folding it into the wrapped command's exit code).
This means: resources (AP, tickets, currency) may already be spent by the time a session starts, independent of anything done in that session -- check `~/ba_logs/` before assuming a given game state is from manual testing. The `daily`/`q4h` preset definitions themselves live in `ba_daily.py`'s `PRESETS` dict (see `plan.md`'s Phase 18 follow-ups for the full writeup), not here -- keep this section in sync if the schedule or preset names change.
@ -270,6 +270,17 @@ While paused, `ba_daily.py` exits with a distinct `PAUSE_EXIT_CODE` (75) rather
`PAUSED` lives inside the repo checkout itself (not alongside the cron lock file in `~/ba_logs/`), per explicit user request for something quick to reach on the same host without needing a separate path -- but it's gitignored (`/PAUSED` in `.gitignore`). It is host-specific mutable runtime state, the same category as the cron lock file, not something that should ever be committed or pushed between machines -- the rsync command in "Deployment model" has no `--delete`, so pushing repo updates from `nik-macbookair` can never delete or overwrite a `PAUSED` flag that only exists on `nik-gpu`.
### Automatic skip while playing another game
Added 2026-10-13, per explicit user request: the automatic counterpart to the manual pause switch. The user plays other games (currently only Persona 3 Reload, `P3R.exe`) on the same nik-gpu desktop, and a cron fire mid-session would have `xdotool` take over their mouse/keyboard.
- `config.GAME_BUSY_PROCESSES` (currently `("P3R.exe",)`) is an explicit process-name list, matched exactly against `/proc/<pid>/comm` by `ba_daily.py`'s `_running_busy_game()`. For a Proton game that's the bare `.exe` name. It's deliberately an explicit list, not "any running Steam game", per user choice: add a new game's `.exe` there when the user starts playing it.
- It has the same scope as the pause flag, checked in `main()` right after the pause check: it blocks cron fires and manual invocations alike, exiting with `BUSY_EXIT_CODE` (76).
- It's also re-checked between tasks in `_run_sequence`. If a game starts mid-run, the current task finishes and returns home, then the rest of the run is skipped (exit 76). In `q4h` that can include `exit_game`, so BA may stay open in the background until the next run.
- `./ba_dailies.sh run_check` is a meta-command with no game interaction. It prints `ACTIVE`/`PAUSED`/`BUSY (<name>)` and exits 0/75/76. `ba_cron_run.sh` calls it as a pre-flight before its "Starting" Discord alert, so paused and game-running runs log `SKIPPED $PRESET -- paused`/`SKIPPED $PRESET -- game running: BUSY (P3R.exe)` and never alert. A 76 from the real run itself means the game started mid-run: that's logged as `STOPPED $PRESET early -- game started mid-run` with an `info` alert closing out the "Starting" message. The log check is now `grep -E 'FAILED|SKIPPED|STOPPED' ~/ba_logs/*.log`.
Verified live 2026-10-13 with P3R actually running: `run_check` reported `BUSY (P3R.exe)`/exit 76, `./ba_dailies.sh mailbox` exited 76 without launching BA, and `ba_cron_run.sh` logged the SKIPPED line with no "starting" line or alert. The mid-run stop was verified only with stubbed tasks, not a real run, because that would mean launching BA while the user was in P3R.
## Runtime dependencies on nik-gpu
These are host-level dependencies. Confirm they exist before assuming a bug is in the project code.

View File

@ -44,6 +44,21 @@ os.makedirs(SCRATCHPAD_DIR, exist_ok=True)
# copy that exists only on nik-gpu either way).
PAUSE_FLAG_PATH = os.path.join(PROJECT_ROOT, "PAUSED")
# Automatic counterpart to PAUSE_FLAG_PATH, per explicit user request
# (2026-10-13): while any of these processes is running on this host, the
# user is playing another game on the same desktop, and ba_daily.py skips
# the run exactly like a pause (same scope -- cron fires and manual
# invocations alike) rather than letting xdotool steal their mouse/keyboard
# mid-game. Re-checked between tasks too, so a game started mid-run stops
# the sequence after the current task returns home. Matched exactly
# against /proc/<pid>/comm -- for a Proton game that's the bare .exe name
# (confirmed live: P3R reads as "P3R.exe"); the kernel truncates comm to
# 15 chars, which ba_daily.py's _running_busy_game() already accounts for,
# so a longer name can be listed here in full. Add a new game's .exe here
# when the user starts playing it -- this list is deliberately explicit
# rather than "any running Steam game", per the same request.
GAME_BUSY_PROCESSES = ("P3R.exe",)
# Refined from (1726, 60): that coordinate sat on the edge of the icon's
# hitbox and intermittently missed during live testing.
MAILBOX_ICON = (1732, 50)

View File

@ -11,11 +11,12 @@
# a scheduled fire time can never silently run late.
#
# Logs to ~/ba_logs/<preset>.log -- one file per preset, so "daily" and
# "q4h" never interleave. Every line is one of four explicitly-tagged
# "q4h" never interleave. Every line is one of six explicitly-tagged
# outcomes (OK / FAILED / SKIPPED -- previous run still in progress /
# SKIPPED -- paused) specifically so a real failure can be found with a
# SKIPPED -- paused / SKIPPED -- game running / STOPPED early -- game
# started mid-run) specifically so a real failure can be found with a
# single command, e.g.:
# grep -E 'FAILED|SKIPPED' ~/ba_logs/*.log
# grep -E 'FAILED|SKIPPED|STOPPED' ~/ba_logs/*.log
# A bare exit code alone can't do this: flock and a genuinely crashed task
# both exit 1, so lock acquisition is checked as its own explicit step
# (via an fd-based flock, not the "flock -n LOCKFILE COMMAND" form used
@ -23,14 +24,18 @@
# Likewise, ba_daily.py's manual pause switch (config.PAUSE_FLAG_PATH,
# toggled via `./ba_dailies.sh pause`/`resume`) exits with the distinct
# PAUSE_EXIT_CODE (75) below rather than the generic failure code, so a
# deliberate pause never gets logged as a crash.
# deliberate pause never gets logged as a crash. Its automatic counterpart,
# the busy-game check (config.GAME_BUSY_PROCESSES -- e.g. the user is
# playing P3R on this same desktop), exits with BUSY_EXIT_CODE (76) the
# same way.
#
# Optional Discord alerting (see plan.md Phase 26): if repo-root .env
# (gitignored -- copy .env.example to create it) provides a working
# ALERT_BRIDGE_URL/ALERT_BRIDGE_API_KEY pair, this posts a start alert and
# an OK/FAILED finish alert to alert-bridge for every real run. SKIPPED
# (lock contention or paused) never alerts -- both are benign/expected and
# would just be noise. A missing, incomplete, or malformed .env silently
# (lock contention, paused, or game running) never alerts -- all benign/
# expected and would just be noise; the paused/game-running cases are
# caught by a run_check pre-flight before the start alert goes out. A missing, incomplete, or malformed .env silently
# disables alerting only -- it can never affect the wrapped ba_dailies.sh
# run or this script's own OK/FAILED/SKIPPED logging.
#
@ -97,6 +102,22 @@ alert() {
exit 0
fi
# Pre-flight: ask ba_daily.py's run_check meta-command (no game
# interaction) whether this run would be skipped -- paused, or a game in
# config.GAME_BUSY_PROCESSES is running -- BEFORE the "Starting" alert,
# so a skipped run never posts to Discord at all. Any other exit code
# (e.g. the venv itself is broken) falls through to the real run below,
# which then fails and gets logged/alerted as FAILED the normal way.
check_output=$("$SCRIPT_DIR/ba_dailies.sh" run_check 2>&1)
check_status=$?
if [ "$check_status" -eq 75 ]; then
echo "=== $(date -Iseconds) SKIPPED $PRESET -- paused ==="
exit 0
elif [ "$check_status" -eq 76 ]; then
echo "=== $(date -Iseconds) SKIPPED $PRESET -- game running: $check_output ==="
exit 0
fi
echo "=== $(date -Iseconds) starting $PRESET ==="
start_epoch=$(date +%s)
alert info "Starting $PRESET"
@ -114,6 +135,12 @@ alert() {
alert info "$PRESET finished OK in $duration"
elif [ "$status" -eq 75 ]; then
echo "=== $(date -Iseconds) SKIPPED $PRESET -- paused ==="
elif [ "$status" -eq 76 ]; then
# The pre-flight above already passed, so a busy game must have
# started during the run -- ba_daily.py stopped between tasks. Alert
# so the "Starting" message already posted gets a matching close.
echo "=== $(date -Iseconds) STOPPED $PRESET early -- game started mid-run (exit 76) ==="
alert info "$PRESET stopped early after $duration -- game started mid-run"
else
echo "=== $(date -Iseconds) finished $PRESET FAILED (exit $status) ==="
alert error "$PRESET FAILED (exit $status) after $duration"

View File

@ -270,10 +270,22 @@ def _run_sequence(names):
# line instead of a slow doomed retry-then-traceback. Skipped for the
# last task and for exit_game specifically, since exit_game closing the
# window is its own intended success, not a failure to report.
#
# The busy-game check (see config.GAME_BUSY_PROCESSES) runs here too,
# not only once in main(): a daily run is long enough that the user can
# start another game partway through it. Stopping between tasks (never
# mid-task) means the task that was already running still finishes and
# gets _run_task's own return-to-home cleanup first.
last_index = len(names) - 1
for i, name in enumerate(names):
_run_task(name)
if i == last_index or name == "exit_game":
if i == last_index:
continue
busy = _running_busy_game()
if busy:
print(f"[{name}] {busy} started mid-run -- stopping before the next task", file=sys.stderr)
return BUSY_EXIT_CODE
if name == "exit_game":
continue
if not driver.window_exists():
raise RuntimeError(
@ -282,6 +294,7 @@ def _run_sequence(names):
"(check nik-gpu manually -- Steam may need signing in, or the game may have crashed)"
)
print("All done.")
return 0
# Distinct from the generic error exit code (1) so ba_cron_run.sh can log a
@ -290,6 +303,37 @@ def _run_sequence(names):
# of this exact value.
PAUSE_EXIT_CODE = 75
# Same idea for config.GAME_BUSY_PROCESSES, kept distinct from the pause
# code so ba_cron_run.sh can log which of the two it was.
BUSY_EXIT_CODE = 76
def _running_busy_game():
"""Return the first config.GAME_BUSY_PROCESSES entry currently running
on this host, or None.
Reads /proc/<pid>/comm directly rather than shelling out to pgrep. comm
is truncated to 15 chars by the kernel, so configured names are
compared truncated the same way. No /proc at all (macOS dev machine)
means nothing can be detected -- returns None, since the game only ever
runs on nik-gpu anyway.
"""
wanted = {name[:15]: name for name in config.GAME_BUSY_PROCESSES}
try:
pids = [entry for entry in os.listdir("/proc") if entry.isdigit()]
except FileNotFoundError:
return None
for pid in pids:
try:
with open(f"/proc/{pid}/comm") as f:
comm = f.read().strip()
except OSError:
# Process exited between listdir and open -- harmless race.
continue
if comm in wanted:
return wanted[comm]
return None
def _pause():
open(config.PAUSE_FLAG_PATH, "w").close()
@ -308,13 +352,31 @@ def _pause_status():
print("PAUSED" if os.path.exists(config.PAUSE_FLAG_PATH) else "ACTIVE")
def _run_check():
# Pre-flight for ba_cron_run.sh: the same two checks main() makes before
# dispatching, reported via exit code without touching the game, so the
# wrapper can skip a run before sending its "Starting" alert rather
# than after.
if os.path.exists(config.PAUSE_FLAG_PATH):
print("PAUSED")
return PAUSE_EXIT_CODE
busy = _running_busy_game()
if busy:
print(f"BUSY ({busy})")
return BUSY_EXIT_CODE
print("ACTIVE")
return 0
# Meta-commands: control the pause flag itself rather than the game, so
# they must stay reachable even while paused -- handled in main() before
# the pause check, not added to TASKS (no driver/game interaction at all).
# A meta-command may return an exit code; returning nothing means 0.
META_COMMANDS = {
"pause": _pause,
"resume": _resume,
"pause_status": _pause_status,
"run_check": _run_check,
}
@ -330,22 +392,24 @@ def main(argv):
return 0
if args and args[0] in META_COMMANDS:
META_COMMANDS[args[0]]()
return 0
return META_COMMANDS[args[0]]() or 0
if os.path.exists(config.PAUSE_FLAG_PATH):
print(f"Paused (flag present at {config.PAUSE_FLAG_PATH}) -- skipping this run. Run './ba_dailies.sh resume' to re-enable.", file=sys.stderr)
return PAUSE_EXIT_CODE
busy = _running_busy_game()
if busy:
print(f"{busy} is running (see config.GAME_BUSY_PROCESSES) -- skipping this run so it can't take over the mouse/keyboard mid-game.", file=sys.stderr)
return BUSY_EXIT_CODE
if not args:
_run_sequence(DEFAULT_ORDER)
return 0
return _run_sequence(DEFAULT_ORDER)
command = args[0]
if command in PRESETS:
_run_sequence(PRESETS[command])
return 0
return _run_sequence(PRESETS[command])
if command not in TASKS:
print(f"Unknown phase: {command}", file=sys.stderr)
@ -361,7 +425,8 @@ def main(argv):
if __name__ == "__main__":
# Skipped for --list-commands: that output is consumed verbatim by
# completions/ba_dailies.bash as a plain space-separated list, and a
# timestamp prefix would break its parsing.
if not (len(sys.argv) > 1 and sys.argv[1] == "--list-commands"):
# timestamp prefix would break its parsing. Likewise for run_check,
# whose one-line output ba_cron_run.sh embeds in its own log line.
if not (len(sys.argv) > 1 and sys.argv[1] in ("--list-commands", "run_check")):
_install_timestamped_output()
sys.exit(main(sys.argv))