From 42f23c71cca030e5a0d05c856fe694cc1a4f16db Mon Sep 17 00:00:00 2001 From: ai-chess Date: Fri, 15 May 2026 00:59:59 +0300 Subject: [PATCH] fix: backend lifespan tears down tmux 'chess' session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agents that outlive the backend desync with state.game (in-memory only) — they keep calling MCP move on a server that has no idea what game is being played. Simpler than persisting game state across restarts: backend startup kills any leftover 'chess' tmux session, backend shutdown kills the current one. start.sh will spawn fresh agents that are aligned with the empty server state on each launch. --- src/ai_chess/app.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/ai_chess/app.py b/src/ai_chess/app.py index 2ecc17f..01b71fd 100644 --- a/src/ai_chess/app.py +++ b/src/ai_chess/app.py @@ -28,6 +28,18 @@ def build_app(state: state_mod.AppState) -> FastAPI: @asynccontextmanager async def lifespan(app: FastAPI): session = TmuxSession("chess") + # Tear down any leftover tmux session from a prior run. Agents that + # outlive the backend will desync with state.game (which lives only + # in-process) and end up calling MCP move on a game the server no + # longer knows about. Cleanest fix: kill them at startup so start.sh + # spawns fresh ones aligned with the empty server state. + try: + if await session.exists(): + print("[lifespan] killing stale tmux session 'chess'", flush=True) + await session.kill() + except Exception as e: + print(f"[lifespan] startup session.kill failed: {e}", flush=True) + coord = Coordinator(state, tmux=session, pane_for={"white": 0, "black": 1}) tailer = TmuxTailer(state, session, pane_for={"white": 0, "black": 1}) eng = StockfishEngine() @@ -117,6 +129,14 @@ def build_app(state: state_mod.AppState) -> FastAPI: await coord.stop() await tailer.stop() await eng.stop() + # Tear down the tmux session so claude/codex die with us. Without + # this they keep running with stale conversation context that no + # longer matches the next backend's state. + try: + await session.kill() + print("[lifespan] tmux session 'chess' killed on shutdown", flush=True) + except Exception as e: + print(f"[lifespan] shutdown session.kill failed: {e}", flush=True) app = FastAPI(title="ai-chess", lifespan=lifespan)