Fix MCP cancellation, mirror run state, and battle boundaries

Browse Source
This commit is contained in:
Codex
2026-10-03 01:21:51 +08:00
parent 97eca204c2
commit 7188b4ac0f
12 changed files with 926 additions and 117 deletions
+99
View File
@@ -0,0 +1,99 @@
"""Persist one mirror run without carrying completed-run state into a new run."""
import json
import os
import tempfile
import uuid
from datetime import datetime, timezone
from pathlib import Path
RESUMABLE = {'running', 'requires_analysis', 'stopped', 'user_takeover'}
def save_json(path, value):
"""Replace complete snapshots atomically so interruption cannot truncate them."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = None
try:
with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent,
prefix=path.name + '.', suffix='.tmp', delete=False) as output:
temporary = Path(output.name)
json.dump(value, output, ensure_ascii=False, indent=2)
output.write('\n')
os.replace(temporary, path)
finally:
if temporary is not None and temporary.exists():
temporary.unlink()
def load_json(path):
if not path.exists():
return None
value = json.loads(path.read_text(encoding='utf-8-sig'))
if not isinstance(value, dict):
raise ValueError('%s must contain an object' % path.name)
return value
def prepare_run(home, new_run=False, resume=False):
home = Path(home)
run_path = home / 'mirror_current_run.json'
context_path = home / 'jev_shop_context.json'
# Explicit new-run also recovers from corrupt or legacy state files.
run = None if new_run else load_json(run_path)
resumable = run is not None and run.get('status') in RESUMABLE
if resume and not resumable:
raise ValueError('No unfinished run to resume; use --new-run for a new dungeon')
if resumable:
started = datetime.fromisoformat(run['start_utc'])
if started.tzinfo is None:
raise ValueError('Run start_utc must include a timezone')
context = load_json(context_path) or {}
run_id = run.get('run_id') or uuid.uuid4().hex
if context.get('run_id') not in (None, run_id):
raise ValueError('Run/context IDs differ; inspect the state or use --new-run')
if context.get('run_id') is None:
# Keep legacy floor/upgrades for an unfinished run, but an unbound
# claim or battle flag cannot establish current-run completion.
for key in ('claim_requested', 'claim_run_id', 'claim_screen', 'claim_at_utc', 'battle_context'):
context.pop(key, None)
run['legacy_context_migrated'] = True
context.setdefault('refresh_used', 0)
context.setdefault('floor', 1)
context['run_id'] = run_id
run['run_id'] = run_id
run['status'] = 'running'
else:
run_id = uuid.uuid4().hex
run = {'run_id': run_id, 'start_utc': datetime.now(timezone.utc).isoformat(),
'status': 'running', 'dungeon_completed': False, 'final_reward_claimed': False}
context = {'run_id': run_id, 'refresh_used': 0, 'floor': 1}
save_json(run_path, run)
save_json(context_path, context)
return run, context
def claim_is_current(run, context):
screen = context.get('claim_screen')
return bool(context.get('claim_requested') and context.get('run_id') == run['run_id']
and context.get('claim_run_id') == run['run_id']
and isinstance(screen, dict) and screen.get('path'))
def record_claim(home, run, context, screen):
if not screen or not screen.get('path'):
raise ValueError('Final claim requires an observed completion screenshot')
context.update(claim_requested=True, claim_run_id=run['run_id'], claim_screen=screen,
claim_at_utc=datetime.now(timezone.utc).isoformat())
save_json(Path(home) / 'jev_shop_context.json', context)
def complete_run(home, run, context, screen):
if not claim_is_current(run, context) or not screen or not screen.get('path'):
raise ValueError('Completion requires current-run claim and return-screen evidence')
now = datetime.now(timezone.utc)
run.update(status='completed', dungeon_completed=True, final_reward_claimed=True,
end_utc=now.isoformat(),
elapsed_seconds=(now-datetime.fromisoformat(run['start_utc'])).total_seconds(),
claim_evidence=context['claim_screen'], completion_evidence=screen)
save_json(Path(home) / 'mirror_current_run.json', run)