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)