Spaces:
Running on Zero

CWM-Coder724 commited on
Commit
94ba961
·
0 Parent(s):

Deploy Clash of Minds to Hugging Face Spaces

Browse files
.dockerignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ .Python
6
+ env/
7
+ venv/
8
+ .venv/
9
+ .git/
10
+ .gitignore
11
+ .github/
12
+ .vscode/
13
+ .idea/
14
+ scratch/
15
+ test_*.py
16
+ *.log
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ *.pdf
6
+ .venv/
7
+ venv/
8
+ scratch/
9
+ test_*.py
10
+ *.log
Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─── Clash of Minds Production Dockerfile for Hugging Face & Cloud ───
2
+ FROM python:3.11-slim
3
+
4
+ # Prevent Python from writing .pyc files & buffer stdout/stderr
5
+ ENV PYTHONDONTWRITEBYTECODE=1
6
+ ENV PYTHONUNBUFFERED=1
7
+ ENV PORT=7860
8
+
9
+ # Install minimal OS dependencies
10
+ RUN apt-get update && apt-get install -y --no-install-recommends \
11
+ curl \
12
+ build-essential \
13
+ && rm -rf /var/lib/apt/lists/*
14
+
15
+ # Set up user named "user" with UID 1000 (Hugging Face requirement)
16
+ RUN useradd -m -u 1000 user
17
+ USER user
18
+ ENV HOME=/home/user \
19
+ PATH=/home/user/.local/bin:$PATH
20
+
21
+ WORKDIR $HOME/app
22
+
23
+ # Install lightweight CPU-only PyTorch first (saves ~2.5 GB)
24
+ RUN pip install --no-cache-dir --upgrade pip && \
25
+ pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu
26
+
27
+ # Copy and install Python dependencies
28
+ COPY --chown=user backend/requirements.txt $HOME/app/backend/requirements.txt
29
+ RUN pip install --no-cache-dir -r $HOME/app/backend/requirements.txt
30
+
31
+ # Copy backend and frontend code
32
+ COPY --chown=user backend $HOME/app/backend
33
+ COPY --chown=user frontend $HOME/app/frontend
34
+
35
+ # Set Python module search path to backend
36
+ ENV PYTHONPATH=$HOME/app/backend
37
+
38
+ WORKDIR $HOME/app/backend
39
+
40
+ EXPOSE 7860
41
+
42
+ # Launch Uvicorn on dynamic port (7860 for Hugging Face, or dynamic $PORT on Render)
43
+ CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port ${PORT:-7860}"]
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Debate
3
+ emoji: ⚡
4
+ colorFrom: indigo
5
+ colorTo: blue
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ # Clash of Minds — AI Debate Judge
12
+ AI-Powered Live Debate Evaluation System — CSES ML Exhibition, NIT Warangal.
backend/debate_memory.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Debate Memory Store — PDF Section 16
3
+ Structured, per-match, in-memory debate state with claim tracking.
4
+ Model weights stay loaded across matches; only match state is cleared on reset.
5
+ """
6
+ from __future__ import annotations
7
+ import asyncio
8
+ import logging
9
+ import time
10
+ from typing import Dict, Optional
11
+
12
+ from models import (
13
+ MatchState, PlayerState, PlayerSide, ClaimRecord, ClaimStatus,
14
+ TurnScore, MatchPhase
15
+ )
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ # Active matches in memory. Key = match_id.
20
+ # Separate from model weights (PDF Section 16: "key distinction")
21
+ _matches: Dict[str, MatchState] = {}
22
+ _lock = asyncio.Lock()
23
+
24
+ INACTIVITY_TIMEOUT = 3600 # 1 hour (PDF Section 15.4)
25
+
26
+
27
+ async def create_match(
28
+ match_id: str,
29
+ p1_name: str,
30
+ p2_name: str,
31
+ topic: str,
32
+ max_rounds: int = 4
33
+ ) -> MatchState:
34
+ """Create and register a new match. Clears any old match with same ID."""
35
+ async with _lock:
36
+ state = MatchState(
37
+ match_id=match_id,
38
+ topic=topic,
39
+ proposition=topic,
40
+ max_rounds=max_rounds,
41
+ current_round=1,
42
+ current_player_id="p1",
43
+ phase=MatchPhase.ACTIVE,
44
+ players={
45
+ "p1": PlayerState(
46
+ player_id="p1",
47
+ name=p1_name,
48
+ side=PlayerSide.FOR
49
+ ),
50
+ "p2": PlayerState(
51
+ player_id="p2",
52
+ name=p2_name,
53
+ side=PlayerSide.AGAINST
54
+ )
55
+ }
56
+ )
57
+ _matches[match_id] = state
58
+ logger.info(f"[Memory] Created match {match_id}: {p1_name} vs {p2_name}")
59
+ return state
60
+
61
+
62
+ async def get_match(match_id: str) -> Optional[MatchState]:
63
+ async with _lock:
64
+ return _matches.get(match_id)
65
+
66
+
67
+ async def save_match(state: MatchState) -> None:
68
+ """Persist updated match state back to the in-memory store."""
69
+ async with _lock:
70
+ state.last_activity = time.time()
71
+ _matches[state.match_id] = state
72
+
73
+
74
+ async def reset_match(match_id: str) -> None:
75
+ """
76
+ Delete match-specific state. Model weights remain loaded (PDF Section 16).
77
+ Called by operator after each debate ends.
78
+ """
79
+ async with _lock:
80
+ if match_id in _matches:
81
+ del _matches[match_id]
82
+ logger.info(f"[Memory] Reset match {match_id}")
83
+
84
+
85
+ async def add_claim(state: MatchState, claim: ClaimRecord) -> None:
86
+ """Add a claim to the debate memory and link it to the player."""
87
+ state.claim_state[claim.claim_id] = claim
88
+ if claim.player_id in state.players:
89
+ state.players[claim.player_id].claim_ids.append(claim.claim_id)
90
+ # All new claims start as unanswered for the opponent
91
+ if claim.claim_id not in state.unanswered_claim_ids:
92
+ state.unanswered_claim_ids.append(claim.claim_id)
93
+
94
+
95
+ async def mark_claim_addressed(
96
+ state: MatchState,
97
+ opponent_claim_id: str,
98
+ addressing_claim_id: str,
99
+ partial: bool = False
100
+ ) -> None:
101
+ """Update the response status of an opponent claim (PDF Section 8.2)."""
102
+ if opponent_claim_id in state.claim_state:
103
+ claim = state.claim_state[opponent_claim_id]
104
+ if not partial:
105
+ claim.status = ClaimStatus.RESOLVED
106
+ if opponent_claim_id in state.unanswered_claim_ids:
107
+ state.unanswered_claim_ids.remove(opponent_claim_id)
108
+ else:
109
+ claim.status = ClaimStatus.PARTIALLY_ADDRESSED
110
+ claim.addressed_by.append(addressing_claim_id)
111
+
112
+
113
+ def get_player_claims(state: MatchState, player_id: str) -> list[ClaimRecord]:
114
+ """Return all claims made by a player, ordered by round."""
115
+ ids = state.players.get(player_id, PlayerState(
116
+ player_id=player_id, name="", side=PlayerSide.FOR
117
+ )).claim_ids
118
+ return [state.claim_state[c] for c in ids if c in state.claim_state]
119
+
120
+
121
+ def get_opponent_claims(state: MatchState, player_id: str) -> list[ClaimRecord]:
122
+ """Return all claims from the opponent (including unanswered)."""
123
+ opp_id = "p2" if player_id == "p1" else "p1"
124
+ return get_player_claims(state, opp_id)
125
+
126
+
127
+ def get_unanswered_opponent_claims(
128
+ state: MatchState, player_id: str
129
+ ) -> list[ClaimRecord]:
130
+ """
131
+ Return opponent claims still unanswered — used by relevant-point retrieval
132
+ to weight unresolved claims higher (PDF Section 8.2).
133
+ """
134
+ opp_claims = get_opponent_claims(state, player_id)
135
+ return [
136
+ c for c in opp_claims
137
+ if c.status in (ClaimStatus.UNANSWERED, ClaimStatus.PARTIALLY_ADDRESSED)
138
+ ]
139
+
140
+
141
+ async def expire_inactive_matches() -> None:
142
+ """
143
+ Clean up matches that have been inactive for INACTIVITY_TIMEOUT seconds.
144
+ Prevents unbounded memory growth during 5-6 hour exhibition (PDF Section 15.5).
145
+ """
146
+ async with _lock:
147
+ now = time.time()
148
+ to_delete = [
149
+ mid for mid, m in _matches.items()
150
+ if now - m.last_activity > INACTIVITY_TIMEOUT
151
+ ]
152
+ for mid in to_delete:
153
+ del _matches[mid]
154
+ logger.info(f"[Memory] Expired inactive match {mid}")
155
+
156
+
157
+ def get_active_match_count() -> int:
158
+ return len(_matches)
159
+
160
+
161
+ def get_latest_active_match() -> Optional[MatchState]:
162
+ """Return the most recently created or active match."""
163
+ active = [m for m in _matches.values() if m.phase == MatchPhase.ACTIVE]
164
+ if not active:
165
+ return None
166
+ return max(active, key=lambda m: m.last_activity)
167
+
backend/main.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Clash of Minds — FastAPI Backend (PDF Section 18-19)
3
+ WebSocket-based live debate evaluation system.
4
+
5
+ Architecture:
6
+ - POST /api/match/start — create new match
7
+ - POST /api/match/submit — submit turn argument
8
+ - POST /api/match/reset — operator reset (PDF Section 15.4)
9
+ - GET /api/match/{id} — get current state
10
+ - WS /ws/{match_id} — real-time updates
11
+
12
+ PDF Section 15.3: Idempotent turn processing via turn_id validation.
13
+ PDF Section 14: RAG runs in background; score emitted immediately with pending status.
14
+ PDF Section 15.5: Memory bounds — match state cleared on reset; models stay loaded.
15
+ """
16
+ from __future__ import annotations
17
+ import asyncio
18
+ import logging
19
+ import uuid
20
+ import time
21
+ from contextlib import asynccontextmanager
22
+ from typing import Any, Dict, List, Optional, Set
23
+
24
+ from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
25
+ from fastapi.middleware.cors import CORSMiddleware
26
+ from fastapi.staticfiles import StaticFiles
27
+ from pydantic import BaseModel
28
+
29
+ from models import (
30
+ MatchState, ClaimRecord, ClaimType, VerificationVerdict,
31
+ RepetitionClass, TurnScore, MatchPhase, MatchSummary,
32
+ StartMatchRequest, SubmitTurnRequest, TurnResult, PlayerState
33
+ )
34
+ import debate_memory as memory
35
+ from pipeline_b_segmentation import segment_response, is_fact_checkable
36
+ from pipeline_e_rag import verify_claim
37
+
38
+ logging.basicConfig(
39
+ level=logging.INFO,
40
+ format="%(asctime)s [%(name)s] %(levelname)s: %(message)s"
41
+ )
42
+ logger = logging.getLogger("clash_of_minds")
43
+
44
+ # ─── WebSocket connection manager ────────────────────────────────────────────
45
+
46
+ class ConnectionManager:
47
+ """Manages WebSocket connections per match_id."""
48
+ def __init__(self):
49
+ self.connections: Dict[str, Set[WebSocket]] = {}
50
+
51
+ async def connect(self, match_id: str, ws: WebSocket):
52
+ await ws.accept()
53
+ self.connections.setdefault(match_id, set()).add(ws)
54
+ logger.info(f"[WS] Client connected to match {match_id}")
55
+
56
+ def disconnect(self, match_id: str, ws: WebSocket):
57
+ if match_id in self.connections:
58
+ self.connections[match_id].discard(ws)
59
+ logger.info(f"[WS] Client disconnected from match {match_id}")
60
+
61
+ async def broadcast(self, match_id: str, data: dict):
62
+ """Send JSON data to all connected clients for this match."""
63
+ dead = set()
64
+ for ws in self.connections.get(match_id, set()):
65
+ try:
66
+ await ws.send_json(data)
67
+ except Exception:
68
+ dead.add(ws)
69
+ for ws in dead:
70
+ self.connections[match_id].discard(ws)
71
+
72
+
73
+ manager = ConnectionManager()
74
+
75
+
76
+ # ─── Application lifespan ────────────────────────────────────────────────────
77
+
78
+ @asynccontextmanager
79
+ async def lifespan(app: FastAPI):
80
+ """
81
+ Load all NLP models ONCE at startup (PDF Section 14 + 22).
82
+ Never reloaded per match.
83
+ """
84
+ logger.info("=== Clash of Minds starting — loading NLP models ===")
85
+
86
+ # Load models with individual error handling (PDF Section 15.2)
87
+ try:
88
+ from pipeline_a_embedding import load_model as load_embedding
89
+ load_embedding()
90
+ except Exception as e:
91
+ logger.error(f"[Startup] Embedding model load failed: {e}")
92
+
93
+ try:
94
+ from pipeline_c_retrieval import load_cross_encoder
95
+ load_cross_encoder()
96
+ except Exception as e:
97
+ logger.error(f"[Startup] Cross-encoder load failed: {e}")
98
+
99
+ try:
100
+ from pipeline_d_nli import load_nli_model
101
+ load_nli_model()
102
+ except Exception as e:
103
+ logger.error(f"[Startup] NLI model load failed: {e}")
104
+
105
+ # Start background cleanup task
106
+ cleanup_task = asyncio.create_task(_periodic_cleanup())
107
+
108
+ logger.info("=== All models loaded — ready for debates ===")
109
+ yield
110
+
111
+ cleanup_task.cancel()
112
+ logger.info("=== Clash of Minds shutting down ===")
113
+
114
+
115
+ async def _periodic_cleanup():
116
+ """Expire inactive matches every 10 minutes (PDF Section 15.5)."""
117
+ while True:
118
+ await asyncio.sleep(600)
119
+ await memory.expire_inactive_matches()
120
+
121
+
122
+ # ─── FastAPI app ──────────────────────────────────────────────────────────────
123
+
124
+ app = FastAPI(
125
+ title="Clash of Minds",
126
+ description="AI-Powered Live Debate Evaluation — CSES ML Exhibition NIT Warangal",
127
+ version="1.0.0",
128
+ lifespan=lifespan
129
+ )
130
+
131
+ app.add_middleware(
132
+ CORSMiddleware,
133
+ allow_origins=["*"],
134
+ allow_methods=["*"],
135
+ allow_headers=["*"],
136
+ )
137
+
138
+
139
+ # ─── API Endpoints ────────────────────────────────────────────────────────────
140
+
141
+ @app.post("/api/match/start")
142
+ async def start_match(req: StartMatchRequest):
143
+ """Create a new debate match or restart existing room with new topic."""
144
+ match_id = req.match_id.strip() if req.match_id and req.match_id.strip() else str(uuid.uuid4())[:12]
145
+ state = await memory.create_match(
146
+ match_id=match_id,
147
+ p1_name=req.p1_name.strip(),
148
+ p2_name=req.p2_name.strip(),
149
+ topic=req.topic.strip(),
150
+ max_rounds=req.max_rounds
151
+ )
152
+ logger.info(f"[API] Match started: {match_id} | {req.p1_name} vs {req.p2_name} | Topic: {req.topic}")
153
+
154
+ match_payload = {
155
+ "type": "match_restarted",
156
+ "match_id": match_id,
157
+ "topic": req.topic,
158
+ "max_rounds": req.max_rounds,
159
+ "p1": {"name": req.p1_name, "side": "FOR"},
160
+ "p2": {"name": req.p2_name, "side": "AGAINST"},
161
+ "current_player": "p1",
162
+ "current_round": 1
163
+ }
164
+
165
+ # Notify any currently connected devices in this room (e.g. Laptop 2, projector)
166
+ await manager.broadcast(match_id, match_payload)
167
+
168
+ return {
169
+ "match_id": match_id,
170
+ "topic": req.topic,
171
+ "max_rounds": req.max_rounds,
172
+ "p1": {"name": req.p1_name, "side": "FOR"},
173
+ "p2": {"name": req.p2_name, "side": "AGAINST"},
174
+ "current_player": "p1",
175
+ "current_round": 1
176
+ }
177
+
178
+
179
+ @app.get("/api/match/latest")
180
+ async def get_latest_match():
181
+ """Get current active match for easy joining across devices."""
182
+ state = memory.get_latest_active_match()
183
+ if not state:
184
+ raise HTTPException(status_code=404, detail="No active match found")
185
+ return _serialize_state(state)
186
+
187
+
188
+ @app.get("/api/match/{match_id}")
189
+ async def get_match(match_id: str):
190
+ """Get current match state."""
191
+ state = await memory.get_match(match_id)
192
+ if not state:
193
+ raise HTTPException(status_code=404, detail="Match not found")
194
+ return _serialize_state(state)
195
+
196
+
197
+
198
+ @app.post("/api/match/submit")
199
+ async def submit_turn(req: SubmitTurnRequest):
200
+ """
201
+ Submit a participant's argument for a turn.
202
+
203
+ Validates: player_id, match_id, turn_id (idempotency), turn state (PDF 15.3).
204
+ Runs pipelines A-D synchronously (fast path).
205
+ Runs pipeline E (RAG) in background (PDF Section 14).
206
+ """
207
+ state = await memory.get_match(req.match_id)
208
+ if not state:
209
+ raise HTTPException(status_code=404, detail="Match not found")
210
+
211
+ if state.phase != MatchPhase.ACTIVE:
212
+ raise HTTPException(status_code=400, detail="Match is not active")
213
+
214
+ # ── Idempotency guard (PDF Section 15.3) ──
215
+ if req.turn_id in state.processed_turn_ids:
216
+ raise HTTPException(status_code=409, detail="Turn already processed")
217
+
218
+ # ── Player and turn validation ──
219
+ if req.player_id != state.current_player_id:
220
+ raise HTTPException(status_code=400, detail=f"It is not {req.player_id}'s turn")
221
+
222
+ if req.player_id not in state.players:
223
+ raise HTTPException(status_code=400, detail="Invalid player_id")
224
+
225
+ # ── Input validation (PDF Section 4, Step 6) ──
226
+ text = req.text.strip()
227
+ if not text:
228
+ raise HTTPException(status_code=400, detail="Argument text cannot be empty")
229
+ if len(text.split()) > 500: # bound argument length (PDF Section 14)
230
+ text = " ".join(text.split()[:500])
231
+
232
+ # Mark turn as being processed
233
+ state.processed_turn_ids.append(req.turn_id)
234
+
235
+ # ── Pipeline B: Claim Segmentation ──
236
+ raw_claims = segment_response(text, max_claims=8)
237
+ player = state.players[req.player_id]
238
+
239
+ # Notify all connected devices that an argument was submitted and analysis is running
240
+ await manager.broadcast(req.match_id, {
241
+ "type": "turn_evaluating",
242
+ "player_id": req.player_id,
243
+ "player_name": player.name
244
+ })
245
+
246
+ # ── Pipeline A: Semantic Embeddings ──
247
+ from pipeline_a_embedding import encode, encode_single
248
+ import numpy as np
249
+
250
+ topic_embedding = encode_single(state.topic)
251
+ claim_texts = [c[0] for c in raw_claims]
252
+ claim_embeddings_arr = encode(claim_texts) if claim_texts else np.array([])
253
+
254
+ # Build ClaimRecord objects
255
+ new_claims = []
256
+ for i, (claim_text, claim_type) in enumerate(raw_claims):
257
+ emb = claim_embeddings_arr[i].tolist() if len(claim_embeddings_arr) > i else None
258
+ claim = ClaimRecord(
259
+ text=claim_text,
260
+ player_id=req.player_id,
261
+ round_number=state.current_round,
262
+ claim_type=claim_type,
263
+ embedding=emb
264
+ )
265
+ new_claims.append(claim)
266
+ await memory.add_claim(state, claim)
267
+
268
+ # ── Pipeline A: Repetition Detection ──
269
+ own_claims = memory.get_player_claims(state, req.player_id)
270
+ own_prev_embeddings = [
271
+ np.array(c.embedding) for c in own_claims[:-len(new_claims)]
272
+ if c.embedding
273
+ ]
274
+
275
+ from pipeline_a_embedding import detect_repetition_type
276
+ repetition_classes = []
277
+ for i, claim in enumerate(new_claims):
278
+ if claim.embedding:
279
+ cls, sim = detect_repetition_type(
280
+ np.array(claim.embedding),
281
+ own_prev_embeddings
282
+ )
283
+ repetition_classes.append(cls)
284
+ else:
285
+ repetition_classes.append(RepetitionClass.NEW)
286
+
287
+ # ── Pipeline C: Relevant Point Retrieval ──
288
+ opponent_claims = memory.get_opponent_claims(state, req.player_id)
289
+ opponent_embeddings = [
290
+ np.array(c.embedding) for c in opponent_claims if c.embedding
291
+ ]
292
+ opponent_with_embeddings = [c for c in opponent_claims if c.embedding]
293
+
294
+ from pipeline_c_retrieval import (
295
+ retrieve_relevant_opponent_claims,
296
+ check_does_response_address_opponent,
297
+ build_retrieval_context
298
+ )
299
+
300
+ # Recent turn window for pronoun resolution (PDF Section 8.4)
301
+ recent_turns = [t.get("text", "") for t in state.turn_log[-4:]]
302
+
303
+ all_relations = []
304
+ addressed_count = 0
305
+
306
+ if opponent_with_embeddings:
307
+ for claim in new_claims:
308
+ if not claim.embedding:
309
+ continue
310
+ relevant = retrieve_relevant_opponent_claims(
311
+ current_text=claim.text,
312
+ current_claim_embedding=np.array(claim.embedding),
313
+ opponent_claims=opponent_with_embeddings,
314
+ opponent_embeddings=opponent_embeddings,
315
+ top_k=5,
316
+ final_k=3
317
+ )
318
+
319
+ does_address = check_does_response_address_opponent(relevant)
320
+ if does_address:
321
+ addressed_count += 1
322
+
323
+ # ── Pipeline D: NLI Relation Analysis ──
324
+ from pipeline_d_nli import analyze_relation
325
+ for opp_claim, score in relevant:
326
+ relation = analyze_relation(
327
+ current_claim_text=claim.text,
328
+ opponent_claim_text=opp_claim.text,
329
+ current_claim_id=claim.claim_id,
330
+ opponent_claim_id=opp_claim.claim_id,
331
+ similarity_score=score
332
+ )
333
+ all_relations.append(relation)
334
+
335
+ # Update claim status in memory
336
+ from models import ArgumentRelation
337
+ if relation.relation in (ArgumentRelation.CONTRADICT, ArgumentRelation.QUALIFY):
338
+ await memory.mark_claim_addressed(
339
+ state, opp_claim.claim_id, claim.claim_id,
340
+ partial=(relation.relation == ArgumentRelation.QUALIFY)
341
+ )
342
+ elif relation.relation == ArgumentRelation.ELABORATE:
343
+ await memory.mark_claim_addressed(
344
+ state, opp_claim.claim_id, claim.claim_id, partial=True
345
+ )
346
+
347
+ # ── Pipeline E: Internet RAG (runs in background) ──
348
+ # Fast path continues; RAG updates evidence async (PDF Section 14)
349
+ async def run_rag_for_claims():
350
+ checkable = [c for c in new_claims if is_fact_checkable(c.claim_type)]
351
+ tasks = []
352
+ for claim in checkable[:3]: # cap per turn (PDF Section 15.6)
353
+ tasks.append(_verify_and_update(state, claim, req.match_id))
354
+ if tasks:
355
+ await asyncio.gather(*tasks, return_exceptions=True)
356
+
357
+ is_last_turn = (state.current_round >= state.max_rounds and req.player_id == "p2")
358
+ if is_last_turn:
359
+ # Wait for fact-check on the very last turn (15s max) so score is accurate
360
+ try:
361
+ await asyncio.wait_for(run_rag_for_claims(), timeout=15.0)
362
+ except asyncio.TimeoutError:
363
+ logger.warning("[API] RAG timed out on final turn — proceeding with current scores")
364
+ else:
365
+ asyncio.create_task(run_rag_for_claims())
366
+
367
+ # ── Scoring Engine ──
368
+ from scoring import compute_turn_score, aggregate_final_scores, generate_final_analysis
369
+
370
+ claim_embeddings_list = [
371
+ np.array(c.embedding) for c in new_claims if c.embedding
372
+ ]
373
+
374
+ turn_score = compute_turn_score(
375
+ turn_id=req.turn_id,
376
+ player_id=req.player_id,
377
+ round_number=state.current_round,
378
+ response_text=text,
379
+ claims=new_claims,
380
+ claim_embeddings=claim_embeddings_list,
381
+ topic_embedding=topic_embedding,
382
+ relations=all_relations,
383
+ repetition_classes=repetition_classes,
384
+ addressed_opponent_claims_count=addressed_count,
385
+ player_side=player.side.value
386
+ )
387
+
388
+ # Update player state
389
+ state.players[req.player_id].turn_scores.append(turn_score)
390
+ state.players[req.player_id].total_score += turn_score.weighted_total * 100
391
+
392
+ # Log turn
393
+ state.turn_log.append({
394
+ "turn_id": req.turn_id,
395
+ "player_id": req.player_id,
396
+ "player_name": player.name,
397
+ "round": state.current_round,
398
+ "text": text,
399
+ "input_method": req.input_method.value,
400
+ "score": turn_score.weighted_total,
401
+ "timestamp": time.time()
402
+ })
403
+
404
+ # ── Advance turn state ──
405
+ debate_over = False
406
+ winner = None
407
+ final_summary = ""
408
+
409
+ next_player = "p2" if req.player_id == "p1" else "p1"
410
+
411
+ # Each round = both players speak; after p2 speaks, increment round
412
+ if req.player_id == "p2":
413
+ state.current_round += 1
414
+
415
+ if state.current_round > state.max_rounds:
416
+ # Debate finished — compute final winner
417
+ p1_turns = state.players["p1"].turn_scores
418
+ p2_turns = state.players["p2"].turn_scores
419
+ p1_total, p2_total = aggregate_final_scores(p1_turns, p2_turns)
420
+
421
+ state.players["p1"].total_score = p1_total
422
+ state.players["p2"].total_score = p2_total
423
+
424
+ winner = "p1" if p1_total > p2_total else "p2"
425
+ state.winner = winner
426
+ state.phase = MatchPhase.FINISHED
427
+ debate_over = True
428
+
429
+ final_summary = generate_final_analysis(
430
+ p1_turns, p2_turns,
431
+ state.players["p1"].name, state.players["p2"].name,
432
+ winner
433
+ )
434
+ logger.info(f"[API] Debate over! Winner: {winner} ({state.players[winner].name})")
435
+ else:
436
+ state.current_player_id = next_player
437
+
438
+ await memory.save_match(state)
439
+
440
+ # ── Build response ──
441
+ result = {
442
+ "type": "turn_result",
443
+ "match_id": req.match_id,
444
+ "turn_id": req.turn_id,
445
+ "player_id": req.player_id,
446
+ "player_name": player.name,
447
+ "text": text,
448
+ "round_number": state.current_round if not debate_over else state.max_rounds,
449
+ "score": {
450
+ "topic_relevance": round(turn_score.topic_relevance_raw * 100, 1),
451
+ "clarity": round(turn_score.clarity_raw * 100, 1),
452
+ "logical_reasoning": round(turn_score.logical_reasoning_raw * 100, 1),
453
+ "rebuttal": round(turn_score.rebuttal_raw * 100, 1),
454
+ "evidence_quality": round(turn_score.evidence_quality_raw * 100, 1),
455
+ "stance_consistency": round(turn_score.stance_consistency_raw * 100, 1),
456
+ "repetition_penalty": round(turn_score.repetition_penalty * 100, 1),
457
+ "weighted_total": round(turn_score.weighted_total * 100, 1),
458
+ "rag_pending": turn_score.rag_pending
459
+ },
460
+ "claims": [
461
+ {
462
+ "id": c.claim_id,
463
+ "text": c.text,
464
+ "type": c.claim_type.value,
465
+ "status": c.status.value,
466
+ "verification": c.verification.verdict.value
467
+ }
468
+ for c in new_claims
469
+ ],
470
+ "relations": [
471
+ {
472
+ "relation": r.relation.value,
473
+ "score": round(r.score, 3),
474
+ "hint": r.reasoning_hint
475
+ }
476
+ for r in all_relations
477
+ ],
478
+ "feedback": turn_score.feedback_text,
479
+ "debate_over": debate_over,
480
+ "winner": winner,
481
+ "winner_name": state.players[winner].name if winner else None,
482
+ "scores": {
483
+ "p1": {
484
+ "name": state.players["p1"].name,
485
+ "total": round(state.players["p1"].total_score, 1)
486
+ },
487
+ "p2": {
488
+ "name": state.players["p2"].name,
489
+ "total": round(state.players["p2"].total_score, 1)
490
+ }
491
+ },
492
+ "final_analysis": final_summary,
493
+ "next_player": next_player if not debate_over else None,
494
+ "next_round": state.current_round if not debate_over else None
495
+ }
496
+
497
+ # Broadcast over WebSocket to all connected clients (PDF live interface)
498
+ await manager.broadcast(req.match_id, result)
499
+
500
+ return result
501
+
502
+
503
+ async def _verify_and_update(state: MatchState, claim: ClaimRecord, match_id: str):
504
+ """
505
+ Background task: run RAG verification and update claim in memory.
506
+ Broadcasts updated evidence scores via WebSocket (PDF Section 14).
507
+ """
508
+ try:
509
+ result = await verify_claim(claim.text, claim.claim_type.value)
510
+ claim.verification = result
511
+
512
+ # Update in state
513
+ if claim.claim_id in state.claim_state:
514
+ state.claim_state[claim.claim_id].verification = result
515
+ await memory.save_match(state)
516
+
517
+ # Broadcast evidence update
518
+ await manager.broadcast(match_id, {
519
+ "type": "evidence_update",
520
+ "claim_id": claim.claim_id,
521
+ "claim_text": claim.text[:80],
522
+ "verdict": result.verdict.value,
523
+ "confidence": result.confidence,
524
+ "conflicting": result.conflicting_evidence,
525
+ "sources": [
526
+ {"url": s.url, "title": s.title, "quality": s.source_quality}
527
+ for s in result.sources[:2]
528
+ ]
529
+ })
530
+
531
+ except Exception as e:
532
+ logger.error(f"[RAG background] Error for claim {claim.claim_id}: {e}")
533
+
534
+
535
+ @app.post("/api/match/{match_id}/reset")
536
+ async def reset_match(match_id: str):
537
+ """
538
+ Operator reset: clear match state while keeping models loaded.
539
+ PDF Section 16: "key distinction between persistent process and temporary session."
540
+ """
541
+ await memory.reset_match(match_id)
542
+ logger.info(f"[API] Match {match_id} reset by operator")
543
+ await manager.broadcast(match_id, {"type": "match_reset", "match_id": match_id})
544
+ return {"status": "reset", "match_id": match_id}
545
+
546
+
547
+ def get_local_ip():
548
+ import socket
549
+ try:
550
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
551
+ s.connect(("8.8.8.8", 80))
552
+ ip = s.getsockname()[0]
553
+ s.close()
554
+ # 172.16.x - 172.31.x is the internal WSL virtual switch — unreachable from other laptops!
555
+ if ip.startswith("172."):
556
+ return "10.126.165.227"
557
+ return ip
558
+ except Exception:
559
+ return "10.126.165.227"
560
+
561
+
562
+ @app.get("/api/health")
563
+ async def health():
564
+ """Health check endpoint for exhibition monitoring (PDF Section 24)."""
565
+ return {
566
+ "status": "ok",
567
+ "active_matches": memory.get_active_match_count(),
568
+ "lan_ip": get_local_ip(),
569
+ "timestamp": time.time()
570
+ }
571
+
572
+
573
+ # ─── WebSocket endpoint ───────────────────────────────────────────────────────
574
+
575
+ @app.websocket("/ws/{match_id}")
576
+ async def websocket_endpoint(websocket: WebSocket, match_id: str):
577
+ await manager.connect(match_id, websocket)
578
+ try:
579
+ # Send current state on connection
580
+ state = await memory.get_match(match_id)
581
+ if state:
582
+ await websocket.send_json({
583
+ "type": "connected",
584
+ "match_id": match_id,
585
+ "state": _serialize_state(state)
586
+ })
587
+ while True:
588
+ # Keep connection alive; all events pushed from server side
589
+ data = await websocket.receive_text()
590
+ # Handle ping
591
+ if data == "ping":
592
+ await websocket.send_text("pong")
593
+ except WebSocketDisconnect:
594
+ manager.disconnect(match_id, websocket)
595
+
596
+
597
+ # ─── Helper ──────────────────────────────────────────────────────────────────
598
+
599
+ def _serialize_state(state: MatchState) -> dict:
600
+ p1 = state.players.get("p1")
601
+ p2 = state.players.get("p2")
602
+ return {
603
+ "match_id": state.match_id,
604
+ "topic": state.topic,
605
+ "phase": state.phase.value,
606
+ "current_round": state.current_round,
607
+ "max_rounds": state.max_rounds,
608
+ "current_player": state.current_player_id,
609
+ "p1": {
610
+ "name": p1.name if p1 else "Player 1",
611
+ "side": "FOR",
612
+ "total_score": round(p1.total_score, 1) if p1 else 0.0
613
+ },
614
+ "p2": {
615
+ "name": p2.name if p2 else "Player 2",
616
+ "side": "AGAINST",
617
+ "total_score": round(p2.total_score, 1) if p2 else 0.0
618
+ },
619
+ "players": {
620
+ pid: {
621
+ "name": p.name,
622
+ "side": p.side.value,
623
+ "total_score": round(p.total_score, 1)
624
+ }
625
+ for pid, p in state.players.items()
626
+ },
627
+ "turn_count": len(state.turn_log),
628
+ "turn_log": state.turn_log,
629
+ "winner": state.winner
630
+ }
631
+
632
+
633
+ # ─── Static files for frontend ────────────────────────────────────────────────
634
+ import os
635
+ import pathlib
636
+
637
+ frontend_path = pathlib.Path(__file__).parent.parent / "frontend"
638
+ if frontend_path.exists():
639
+ app.mount("/", StaticFiles(directory=str(frontend_path), html=True), name="frontend")
640
+
641
+
642
+ if __name__ == "__main__":
643
+ import uvicorn
644
+ uvicorn.run(
645
+ "main:app",
646
+ host="0.0.0.0",
647
+ port=8000,
648
+ reload=False, # Never reload in exhibition mode (PDF Section 22)
649
+ log_level="info"
650
+ )
backend/models.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pydantic models and enums for Clash of Minds debate state.
3
+ Faithful to the PDF workflow — every field corresponds to a documented state.
4
+ """
5
+ from __future__ import annotations
6
+ from enum import Enum
7
+ from typing import Dict, List, Optional, Any
8
+ from pydantic import BaseModel, Field
9
+ import uuid
10
+ import time
11
+
12
+
13
+ # ─── Enums ──────────────────────────────────────────────────────────────────
14
+
15
+ class ClaimType(str, Enum):
16
+ FACTUAL = "factual"
17
+ OPINION = "opinion"
18
+ CONDITIONAL = "conditional"
19
+ RHETORICAL = "rhetorical"
20
+ STATISTICAL = "statistical"
21
+ PREDICTION = "prediction"
22
+ VALUE_JUDGMENT = "value_judgment"
23
+ UNCLEAR = "unclear"
24
+
25
+
26
+ class ClaimStatus(str, Enum):
27
+ UNANSWERED = "unanswered"
28
+ PARTIALLY_ADDRESSED = "partially_addressed"
29
+ RESOLVED = "resolved"
30
+
31
+
32
+ class VerificationVerdict(str, Enum):
33
+ SUPPORTED = "SUPPORTED"
34
+ PARTIALLY_SUPPORTED = "PARTIALLY_SUPPORTED"
35
+ REFUTED = "REFUTED"
36
+ INSUFFICIENT_EVIDENCE = "INSUFFICIENT_EVIDENCE"
37
+ AMBIGUOUS = "AMBIGUOUS"
38
+ PENDING = "PENDING"
39
+ NOT_CHECKABLE = "NOT_CHECKABLE" # opinions, rhetorical, etc.
40
+
41
+
42
+ class ArgumentRelation(str, Enum):
43
+ SUPPORT = "support"
44
+ CONTRADICT = "contradict"
45
+ QUALIFY = "qualify"
46
+ ELABORATE = "elaborate"
47
+ NEUTRAL = "neutral"
48
+ UNRELATED = "unrelated"
49
+
50
+
51
+ class RepetitionClass(str, Enum):
52
+ REPEATED = "repeated"
53
+ REPHRASED = "rephrased"
54
+ ELABORATED = "elaborated"
55
+ REPEATED_WITH_NEW_EVIDENCE = "repeated_with_new_evidence"
56
+ NEW = "new"
57
+
58
+
59
+ class PlayerSide(str, Enum):
60
+ FOR = "FOR"
61
+ AGAINST = "AGAINST"
62
+
63
+
64
+ class InputMethod(str, Enum):
65
+ TEXT = "text"
66
+ VOICE = "voice"
67
+
68
+
69
+ class MatchPhase(str, Enum):
70
+ SETUP = "setup"
71
+ ACTIVE = "active"
72
+ FINISHED = "finished"
73
+
74
+
75
+ # ─── Claim-level models ───────────────────────────────────────────────────────
76
+
77
+ class EvidenceSource(BaseModel):
78
+ url: str
79
+ domain: str
80
+ title: str
81
+ publication_date: Optional[str] = None
82
+ retrieval_date: str = Field(default_factory=lambda: str(time.time()))
83
+ source_quality: float = 0.5 # 0-1 priority score
84
+
85
+
86
+ class VerificationResult(BaseModel):
87
+ verdict: VerificationVerdict = VerificationVerdict.PENDING
88
+ evidence_passages: List[str] = Field(default_factory=list)
89
+ sources: List[EvidenceSource] = Field(default_factory=list)
90
+ confidence: float = 0.0
91
+ conflicting_evidence: bool = False
92
+ notes: str = ""
93
+
94
+
95
+ class ClaimRecord(BaseModel):
96
+ claim_id: str = Field(default_factory=lambda: str(uuid.uuid4())[:8])
97
+ text: str
98
+ player_id: str # "p1" or "p2"
99
+ round_number: int
100
+ claim_type: ClaimType = ClaimType.UNCLEAR
101
+ status: ClaimStatus = ClaimStatus.UNANSWERED
102
+ embedding: Optional[List[float]] = None # stored separately in FAISS
103
+ verification: VerificationResult = Field(default_factory=VerificationResult)
104
+ addressed_by: List[str] = Field(default_factory=list) # claim_ids that addressed this
105
+
106
+
107
+ class RelationRecord(BaseModel):
108
+ """Records the NLI relation between a current claim and a retrieved opponent claim."""
109
+ current_claim_id: str
110
+ opponent_claim_id: str
111
+ relation: ArgumentRelation
112
+ score: float # cross-encoder confidence
113
+ reasoning_hint: str = ""
114
+
115
+
116
+ # ─── Turn-level models ────────────────────────────────────────────────────────
117
+
118
+ class TurnScore(BaseModel):
119
+ """Per-criterion scores for one turn. Weights from PDF Section 11."""
120
+ turn_id: str
121
+ player_id: str
122
+ round_number: int
123
+
124
+ # Raw signals (0-1)
125
+ topic_relevance_raw: float = 0.0 # 15%
126
+ clarity_raw: float = 0.0 # 15%
127
+ logical_reasoning_raw: float = 0.0 # 20%
128
+ rebuttal_raw: float = 0.0 # 20%
129
+ evidence_quality_raw: float = 0.0 # 20%
130
+ stance_consistency_raw: float = 0.0 # 10%
131
+
132
+ # Penalty
133
+ repetition_penalty: float = 0.0 # deducted from total
134
+
135
+ # Weighted final
136
+ weighted_total: float = 0.0
137
+
138
+ # Diagnosis
139
+ claims_analyzed: int = 0
140
+ relations_found: List[RelationRecord] = Field(default_factory=list)
141
+ repetition_classes: List[RepetitionClass] = Field(default_factory=list)
142
+ feedback_text: str = ""
143
+ rag_pending: bool = False # True if RAG still running when score emitted
144
+
145
+
146
+ class PlayerState(BaseModel):
147
+ player_id: str # "p1" or "p2"
148
+ name: str
149
+ side: PlayerSide
150
+ total_score: float = 0.0
151
+ turn_scores: List[TurnScore] = Field(default_factory=list)
152
+ claim_ids: List[str] = Field(default_factory=list) # claims this player made
153
+
154
+
155
+ # ─── Match-level models ───────────────────────────────────────────────────────
156
+
157
+ class MatchState(BaseModel):
158
+ """
159
+ Top-level debate memory. Cleared on reset; model weights remain loaded.
160
+ Corresponds directly to PDF Section 16 debate memory design.
161
+ """
162
+ match_id: str = Field(default_factory=lambda: str(uuid.uuid4())[:12])
163
+ topic: str = ""
164
+ proposition: str = "" # clearly worded proposition form of topic
165
+
166
+ phase: MatchPhase = MatchPhase.SETUP
167
+ current_round: int = 1
168
+ max_rounds: int = 4
169
+ current_player_id: str = "p1" # whose turn it is
170
+
171
+ players: Dict[str, PlayerState] = Field(default_factory=dict)
172
+ claim_state: Dict[str, ClaimRecord] = Field(default_factory=dict)
173
+ turn_scores: List[TurnScore] = Field(default_factory=list)
174
+ unanswered_claim_ids: List[str] = Field(default_factory=list)
175
+
176
+ # Per-turn idempotency guard (PDF Section 15.3)
177
+ processed_turn_ids: List[str] = Field(default_factory=list)
178
+
179
+ # RAG query cache (PDF Section 14, Section 15.6)
180
+ rag_cache: Dict[str, VerificationResult] = Field(default_factory=dict)
181
+
182
+ # Transcript/turn log
183
+ turn_log: List[Dict[str, Any]] = Field(default_factory=list)
184
+
185
+ winner: Optional[str] = None # player_id of winner
186
+ created_at: float = Field(default_factory=time.time)
187
+ last_activity: float = Field(default_factory=time.time)
188
+
189
+
190
+ # ─── API Request/Response models ─────────────────────────────────────────────
191
+
192
+ class StartMatchRequest(BaseModel):
193
+ p1_name: str
194
+ p2_name: str
195
+ topic: str
196
+ max_rounds: int = 4 # configurable per PDF Section 13
197
+ match_id: Optional[str] = None # optional to reuse existing room code across debates
198
+
199
+
200
+
201
+ class SubmitTurnRequest(BaseModel):
202
+ match_id: str
203
+ player_id: str
204
+ turn_id: str # client-generated UUID for idempotency
205
+ text: str
206
+ input_method: InputMethod = InputMethod.TEXT
207
+
208
+
209
+ class TurnResult(BaseModel):
210
+ match_id: str
211
+ turn_id: str
212
+ player_id: str
213
+ round_number: int
214
+ score: TurnScore
215
+ claims: List[ClaimRecord]
216
+ relations: List[RelationRecord]
217
+ debate_over: bool = False
218
+ winner: Optional[str] = None
219
+ next_player_id: Optional[str] = None
220
+
221
+
222
+ class MatchSummary(BaseModel):
223
+ match_id: str
224
+ topic: str
225
+ winner: Optional[str]
226
+ winner_name: Optional[str]
227
+ p1: PlayerState
228
+ p2: PlayerState
229
+ turn_log: List[Dict[str, Any]]
230
+ total_rounds: int
backend/pipeline_a_embedding.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pipeline A — Semantic Embedding Model (PDF Section 7)
3
+ Uses sentence-transformers for meaning-aware retrieval.
4
+ IMPORTANT (PDF): Cosine similarity is for retrieval/ranking ONLY.
5
+ It is NOT used to infer contradiction, agreement, or debate quality.
6
+ That is the job of Pipeline D (NLI cross-encoder).
7
+ """
8
+ from __future__ import annotations
9
+ import logging
10
+ import numpy as np
11
+ from typing import List, Tuple, Optional
12
+ from sentence_transformers import SentenceTransformer
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Model loaded ONCE at startup — never reloaded per match (PDF Section 14 + 22)
17
+ # all-mpnet-base-v2 chosen per PDF Section 18 recommendation
18
+ _MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
19
+ _model: Optional[SentenceTransformer] = None
20
+
21
+
22
+ def load_model() -> None:
23
+ """Load embedding model once at application startup."""
24
+ global _model
25
+ if _model is None:
26
+ logger.info(f"[Pipeline A] Loading embedding model: {_MODEL_NAME}")
27
+ _model = SentenceTransformer(_MODEL_NAME)
28
+ logger.info("[Pipeline A] Model loaded.")
29
+
30
+
31
+ def get_model() -> SentenceTransformer:
32
+ if _model is None:
33
+ load_model()
34
+ return _model
35
+
36
+
37
+ def encode(texts: List[str], batch_size: int = 32) -> np.ndarray:
38
+ """
39
+ Encode a list of texts into L2-normalized embedding vectors.
40
+ Returns shape (N, D).
41
+ """
42
+ if not texts:
43
+ return np.array([])
44
+ model = get_model()
45
+ embeddings = model.encode(
46
+ texts,
47
+ batch_size=batch_size,
48
+ normalize_embeddings=True, # unit vectors → cosine similarity = dot product
49
+ show_progress_bar=False
50
+ )
51
+ return embeddings
52
+
53
+
54
+ def encode_single(text: str) -> np.ndarray:
55
+ """Encode a single text. Returns shape (D,)."""
56
+ return encode([text])[0]
57
+
58
+
59
+ def cosine_similarity_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
60
+ """
61
+ Compute cosine similarities between rows of a (shape N×D) and b (shape M×D).
62
+ Returns shape (N, M).
63
+ Because embeddings are L2-normalized, this is just a dot product.
64
+ """
65
+ return np.dot(a, b.T)
66
+
67
+
68
+ def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
69
+ """Compute cosine similarity between two single vectors."""
70
+ return float(np.dot(a, b))
71
+
72
+
73
+ def compute_topic_relevance(claim_embedding: np.ndarray, topic_embedding: np.ndarray) -> float:
74
+ """
75
+ Topic relevance signal for scoring (PDF Section 11 — 15% weight).
76
+ Returns 0-1 similarity of claim to topic.
77
+ """
78
+ return max(0.0, cosine_similarity(claim_embedding, topic_embedding))
79
+
80
+
81
+ def detect_repetition_type(
82
+ new_embedding: np.ndarray,
83
+ own_history_embeddings: List[np.ndarray],
84
+ HIGH_THRESHOLD: float = 0.90,
85
+ MED_THRESHOLD: float = 0.75
86
+ ) -> Tuple[str, float]:
87
+ """
88
+ Classify new claim against participant's own claim history.
89
+ Returns (repetition_class, max_similarity_score).
90
+
91
+ PDF Section 7.4:
92
+ - repeated: same idea, no new evidence → penalizable
93
+ - rephrased: same idea with different vocab (not penalized if no evidence check)
94
+ - elaborated: extends a prior claim → NOT penalized
95
+ - new: genuinely new claim
96
+
97
+ NOTE: This classification is semantic only.
98
+ The scoring engine decides the actual penalty (PDF Section 12, Rule 4):
99
+ repetition WITH new evidence is NOT penalized.
100
+ """
101
+ from models import RepetitionClass
102
+
103
+ if not own_history_embeddings:
104
+ return RepetitionClass.NEW, 0.0
105
+
106
+ sims = [cosine_similarity(new_embedding, h) for h in own_history_embeddings]
107
+ max_sim = max(sims)
108
+
109
+ if max_sim >= HIGH_THRESHOLD:
110
+ return RepetitionClass.REPEATED, max_sim
111
+ elif max_sim >= MED_THRESHOLD:
112
+ return RepetitionClass.REPHRASED, max_sim
113
+ else:
114
+ return RepetitionClass.NEW, max_sim
115
+
116
+
117
+ def retrieve_top_k_candidates(
118
+ query_embedding: np.ndarray,
119
+ candidate_embeddings: List[np.ndarray],
120
+ candidate_ids: List[str],
121
+ k: int = 5,
122
+ unresolved_boost: Optional[List[bool]] = None
123
+ ) -> List[Tuple[str, float]]:
124
+ """
125
+ Retrieve top-k most semantically relevant candidates from a list.
126
+ Used by Pipeline C to get candidate opponent claims for NLI analysis.
127
+
128
+ unresolved_boost: parallel list; if True, boost that candidate's score
129
+ (PDF Section 8.2: unresolved claims weighted higher).
130
+
131
+ Returns list of (candidate_id, similarity_score) sorted descending.
132
+ """
133
+ if not candidate_embeddings or not candidate_ids:
134
+ return []
135
+
136
+ sims = [cosine_similarity(query_embedding, c) for c in candidate_embeddings]
137
+
138
+ # Boost unanswered/partially-answered claims (PDF Section 8.2)
139
+ UNRESOLVED_BOOST = 0.08
140
+ if unresolved_boost and len(unresolved_boost) == len(sims):
141
+ sims = [
142
+ s + (UNRESOLVED_BOOST if boost else 0.0)
143
+ for s, boost in zip(sims, unresolved_boost)
144
+ ]
145
+
146
+ ranked = sorted(
147
+ zip(candidate_ids, sims),
148
+ key=lambda x: x[1],
149
+ reverse=True
150
+ )
151
+ return ranked[:k]
backend/pipeline_b_segmentation.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pipeline B — Claim Segmentation and Claim Typing (PDF Section 6)
3
+ Splits a participant's response into atomic or near-atomic claims.
4
+ Classifies each claim's type before deeper evaluation.
5
+
6
+ Key insight from PDF (Section 6): "The same participant response can contain
7
+ several independent factual assertions, an opinion, a conditional statement,
8
+ and a rhetorical question. Each should be handled differently."
9
+
10
+ PDF Section 6.4: Do NOT strip qualifiers like if, only, may, could, not, unless.
11
+ PDF Section 6.3: Rhetorical questions are NOT automatically fact-checked.
12
+ PDF Section 6.2: Only checkable factual claims trigger web verification.
13
+ """
14
+ from __future__ import annotations
15
+ import re
16
+ import logging
17
+ from typing import List, Tuple
18
+ from models import ClaimType
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # ─── Linguistic patterns for claim typing ─────────────────────────────────────
23
+
24
+ # Conditional markers (PDF Section 6.4 — must preserve these)
25
+ CONDITIONAL_MARKERS = re.compile(
26
+ r'\b(if|unless|provided that|assuming|only if|even if|in case|'
27
+ r'given that|suppose|when|whenever|once|as long as)\b',
28
+ re.IGNORECASE
29
+ )
30
+
31
+ # Uncertainty qualifiers (PDF Section 6.4 — must NOT be stripped)
32
+ QUALIFIER_MARKERS = re.compile(
33
+ r'\b(may|might|could|can|possibly|perhaps|probably|likely|'
34
+ r'unlikely|sometimes|often|usually|potentially|arguably)\b',
35
+ re.IGNORECASE
36
+ )
37
+
38
+ # Statistical indicators (PDF Section 6.5)
39
+ STATISTICAL_MARKERS = re.compile(
40
+ r'\b(\d+\.?\d*\s*%|\d+\.?\d*\s*(million|billion|thousand|percent)|'
41
+ r'\d{4}\s+(study|report|data|survey)|according to|research shows|'
42
+ r'statistics show|data shows|studies show|survey found)\b',
43
+ re.IGNORECASE
44
+ )
45
+
46
+ # Rhetorical question patterns (PDF Section 6.3)
47
+ RHETORICAL_PATTERNS = re.compile(
48
+ r'(don\'t you think|isn\'t it obvious|how can (anyone|we)|'
49
+ r'who (would|could|should)|what (would|could|should)|'
50
+ r'isn\'t that|aren\'t (we|they)|wouldn\'t|couldn\'t|shouldn\'t)',
51
+ re.IGNORECASE
52
+ )
53
+
54
+ # Opinion / value judgment markers
55
+ OPINION_MARKERS = re.compile(
56
+ r'\b(I (think|believe|feel|argue|contend)|in my (opinion|view)|'
57
+ r'it seems|it appears|personally|for me|from my perspective|'
58
+ r'we should|society should|people must|everyone ought|'
59
+ r'fundamentally|morally|ethically|clearly|obviously|certainly)\b',
60
+ re.IGNORECASE
61
+ )
62
+
63
+ # Future prediction markers
64
+ PREDICTION_MARKERS = re.compile(
65
+ r'\b(will|shall|going to|in the future|soon|eventually|by \d{4}|'
66
+ r'forecast|predict|expected to|projected to|anticipated to)\b',
67
+ re.IGNORECASE
68
+ )
69
+
70
+
71
+ def split_into_sentences(text: str) -> List[str]:
72
+ """
73
+ Split response text into sentence-level segments.
74
+ Uses a simple rule-based splitter to avoid spaCy dependency at segment stage.
75
+ Preserves conditional structure — does not split on commas within conditions.
76
+ """
77
+ # Split on sentence-ending punctuation
78
+ raw = re.split(r'(?<=[.!?])\s+(?=[A-Z])', text.strip())
79
+ # Additional split on semicolons that act as claim boundaries
80
+ sentences = []
81
+ for s in raw:
82
+ parts = re.split(r';\s+(?=[A-Z])', s)
83
+ sentences.extend(parts)
84
+ return [s.strip() for s in sentences if len(s.strip()) > 10]
85
+
86
+
87
+ def classify_claim_type(sentence: str) -> ClaimType:
88
+ """
89
+ Classify a single sentence/claim into a claim type.
90
+ Priority: RHETORICAL > STATISTICAL > CONDITIONAL > PREDICTION > OPINION > FACTUAL > UNCLEAR
91
+
92
+ PDF Section 6.2: factual, opinion, prediction, conditional, value_judgment,
93
+ rhetorical/argumentative, statistic, or unclear.
94
+ """
95
+ text = sentence.strip()
96
+
97
+ # Rhetorical questions (PDF 6.3: do not fact-check literally)
98
+ if text.endswith('?') or RHETORICAL_PATTERNS.search(text):
99
+ return ClaimType.RHETORICAL
100
+
101
+ # Statistical (PDF 6.5: extract precise metric/value/context)
102
+ if STATISTICAL_MARKERS.search(text):
103
+ return ClaimType.STATISTICAL
104
+
105
+ # Conditional (PDF 6.4: preserve qualifiers; different truth conditions)
106
+ if CONDITIONAL_MARKERS.search(text):
107
+ return ClaimType.CONDITIONAL
108
+
109
+ # Prediction
110
+ if PREDICTION_MARKERS.search(text):
111
+ return ClaimType.PREDICTION
112
+
113
+ # Opinion / value judgment
114
+ if OPINION_MARKERS.search(text):
115
+ return ClaimType.OPINION
116
+
117
+ # Default: factual (checkable claim)
118
+ if len(text.split()) >= 4:
119
+ return ClaimType.FACTUAL
120
+
121
+ return ClaimType.UNCLEAR
122
+
123
+
124
+ def is_fact_checkable(claim_type: ClaimType) -> bool:
125
+ """
126
+ Determines if a claim should trigger the Internet RAG pipeline.
127
+ PDF Section 6.2: "Only checkable factual claims should normally trigger web verification."
128
+ """
129
+ return claim_type in (ClaimType.FACTUAL, ClaimType.STATISTICAL)
130
+
131
+
132
+ def segment_response(text: str, max_claims: int = 8) -> List[Tuple[str, ClaimType]]:
133
+ """
134
+ Main entry point: split response into (claim_text, claim_type) pairs.
135
+
136
+ Implements:
137
+ - PDF Section 6.1: multiple claims inside one response
138
+ - PDF Section 6.2: mixed fact and opinion
139
+ - PDF Section 6.3: hidden argument inside rhetorical question
140
+ - PDF Section 6.4: conditional and qualified statements
141
+ - PDF Section 6.5: numerical and statistical claims
142
+
143
+ max_claims bounds inference cost (PDF Section 14, point 6).
144
+ """
145
+ if not text or not text.strip():
146
+ return []
147
+
148
+ sentences = split_into_sentences(text)
149
+
150
+ # Bound claim count to control inference cost (PDF Section 14)
151
+ sentences = sentences[:max_claims]
152
+
153
+ results = []
154
+ for sentence in sentences:
155
+ claim_type = classify_claim_type(sentence)
156
+ results.append((sentence, claim_type))
157
+ logger.debug(f"[Pipeline B] Claim type '{claim_type.value}': {sentence[:60]}...")
158
+
159
+ logger.info(f"[Pipeline B] Segmented {len(results)} claims from response")
160
+ return results
161
+
162
+
163
+ def extract_statistical_metadata(text: str) -> dict:
164
+ """
165
+ For statistical claims, extract structured metadata (PDF Section 6.5):
166
+ value, metric, direction, population, time, condition.
167
+ """
168
+ meta = {
169
+ "numbers": re.findall(r'\d+\.?\d*', text),
170
+ "percentages": re.findall(r'\d+\.?\d*\s*%', text),
171
+ "years": re.findall(r'\b(19|20)\d{2}\b', text),
172
+ "has_source_attribution": bool(re.search(
173
+ r'\b(according to|source:|cited by|reported by|study by)\b',
174
+ text, re.IGNORECASE
175
+ )),
176
+ "qualifiers_preserved": [
177
+ m.group() for m in QUALIFIER_MARKERS.finditer(text)
178
+ ]
179
+ }
180
+ return meta
backend/pipeline_c_retrieval.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pipeline C — Relevant Point Retrieval (PDF Section 8)
3
+ Retrieves the opponent's most relevant previous claims for the current response.
4
+ Tracks unanswered/partially_addressed/resolved status across all turns.
5
+
6
+ PDF Section 8: "The system should not assume that the current participant
7
+ is responding to the immediately previous sentence."
8
+
9
+ Uses two-stage retrieval:
10
+ 1. Fast: Embedding similarity (Pipeline A) for candidate retrieval
11
+ 2. Precise: Cross-encoder reranking of top-k candidates
12
+ """
13
+ from __future__ import annotations
14
+ import logging
15
+ from typing import List, Tuple, Optional
16
+ import numpy as np
17
+ from models import ClaimRecord, ClaimStatus, ArgumentRelation, RelationRecord
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # Cross-encoder loaded once (PDF Section 14 + 22)
22
+ _CROSS_ENCODER_MODEL = "cross-encoder/ms-marco-MiniLM-L-6-v2"
23
+ _cross_encoder = None
24
+
25
+
26
+ def load_cross_encoder() -> None:
27
+ global _cross_encoder
28
+ if _cross_encoder is None:
29
+ try:
30
+ from sentence_transformers.cross_encoder import CrossEncoder
31
+ logger.info(f"[Pipeline C] Loading cross-encoder: {_CROSS_ENCODER_MODEL}")
32
+ _cross_encoder = CrossEncoder(_CROSS_ENCODER_MODEL)
33
+ logger.info("[Pipeline C] Cross-encoder loaded.")
34
+ except Exception as e:
35
+ logger.error(f"[Pipeline C] Failed to load cross-encoder: {e}")
36
+ _cross_encoder = None
37
+
38
+
39
+ def get_cross_encoder():
40
+ if _cross_encoder is None:
41
+ load_cross_encoder()
42
+ return _cross_encoder
43
+
44
+
45
+ def retrieve_relevant_opponent_claims(
46
+ current_text: str,
47
+ current_claim_embedding: np.ndarray,
48
+ opponent_claims: List[ClaimRecord],
49
+ opponent_embeddings: List[np.ndarray],
50
+ top_k: int = 5,
51
+ final_k: int = 3
52
+ ) -> List[Tuple[ClaimRecord, float]]:
53
+ """
54
+ Two-stage retrieval of opponent claims most relevant to the current claim.
55
+
56
+ Stage 1: Fast embedding retrieval with unresolved-claim boost (PDF 8.2)
57
+ Stage 2: Cross-encoder reranking for precise relevance scoring (PDF 8.1)
58
+
59
+ Returns list of (ClaimRecord, score) sorted descending.
60
+ """
61
+ if not opponent_claims or not opponent_embeddings:
62
+ return []
63
+
64
+ from pipeline_a_embedding import retrieve_top_k_candidates
65
+
66
+ # Build IDs and unresolved flags for retrieval
67
+ candidate_ids = [c.claim_id for c in opponent_claims]
68
+ unresolved_boost = [
69
+ c.status in (ClaimStatus.UNANSWERED, ClaimStatus.PARTIALLY_ADDRESSED)
70
+ for c in opponent_claims
71
+ ]
72
+
73
+ # Stage 1: Embedding-based top-k retrieval
74
+ top_k_results = retrieve_top_k_candidates(
75
+ query_embedding=current_claim_embedding,
76
+ candidate_embeddings=opponent_embeddings,
77
+ candidate_ids=candidate_ids,
78
+ k=top_k,
79
+ unresolved_boost=unresolved_boost
80
+ )
81
+
82
+ if not top_k_results:
83
+ return []
84
+
85
+ # Build ID→claim lookup
86
+ id_to_claim = {c.claim_id: c for c in opponent_claims}
87
+
88
+ # Stage 2: Cross-encoder reranking (PDF Section 8.1)
89
+ cross_enc = get_cross_encoder()
90
+ if cross_enc is not None:
91
+ try:
92
+ pairs = [
93
+ (current_text, id_to_claim[cid].text)
94
+ for cid, _ in top_k_results
95
+ if cid in id_to_claim
96
+ ]
97
+ if pairs:
98
+ ce_scores = cross_enc.predict(pairs)
99
+ reranked = sorted(
100
+ zip([cid for cid, _ in top_k_results], ce_scores),
101
+ key=lambda x: x[1],
102
+ reverse=True
103
+ )
104
+ return [
105
+ (id_to_claim[cid], float(score))
106
+ for cid, score in reranked[:final_k]
107
+ if cid in id_to_claim
108
+ ]
109
+ except Exception as e:
110
+ logger.warning(f"[Pipeline C] Cross-encoder reranking failed: {e}. Falling back to embedding order.")
111
+
112
+ # Fallback: use embedding order if cross-encoder fails
113
+ return [
114
+ (id_to_claim[cid], float(score))
115
+ for cid, score in top_k_results[:final_k]
116
+ if cid in id_to_claim
117
+ ]
118
+
119
+
120
+ def check_does_response_address_opponent(
121
+ relevant_candidates: List[Tuple[ClaimRecord, float]],
122
+ min_relevance_threshold: float = 0.30
123
+ ) -> bool:
124
+ """
125
+ PDF Section 8.1: Separate "same topic" from "directly addresses opponent point".
126
+ Returns True if at least one retrieved candidate has sufficient relevance.
127
+ """
128
+ if not relevant_candidates:
129
+ return False
130
+ return any(score >= min_relevance_threshold for _, score in relevant_candidates)
131
+
132
+
133
+ def build_retrieval_context(
134
+ current_text: str,
135
+ relevant_opponent_claims: List[Tuple[ClaimRecord, float]],
136
+ recent_turn_window: List[str],
137
+ max_context_chars: int = 1200
138
+ ) -> str:
139
+ """
140
+ Build contextual text combining retrieved opponent claims and recent turns.
141
+ Used to resolve pronoun references and contextual phrases (PDF Section 8.4).
142
+ Bounded to prevent excessive inference cost.
143
+ """
144
+ context_parts = []
145
+
146
+ # Recent turn window for pronoun resolution (PDF Section 8.4)
147
+ if recent_turn_window:
148
+ context_parts.append("Recent context:\n" + "\n".join(recent_turn_window[-2:]))
149
+
150
+ # Retrieved opponent claims
151
+ if relevant_opponent_claims:
152
+ context_parts.append("Relevant opponent claims:")
153
+ for claim, score in relevant_opponent_claims[:3]:
154
+ context_parts.append(f" [{claim.status.value}] {claim.text}")
155
+
156
+ context = "\n".join(context_parts)
157
+ return context[:max_context_chars]
backend/pipeline_d_nli.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pipeline D — NLI / Argument Relation Analysis (PDF Section 3, 7.2, 8.5)
3
+ Uses a cross-encoder NLI model to classify the logical relationship between
4
+ the current claim and retrieved opponent claims.
5
+
6
+ PDF Section 7.2: "Do not infer agreement or contradiction from embedding similarity.
7
+ Use a cross-encoder/NLI model and a stance signal after retrieval."
8
+
9
+ PDF Section 8.5: Relation labels: support, contradict, qualify, elaborate, neutral, unrelated.
10
+ PDF Section 12, Rule 1: "A contradiction is not automatically a strong rebuttal.
11
+ 'That is wrong' contains disagreement but little reasoning."
12
+
13
+ Model: cross-encoder/nli-deberta-v3-small (recommended in PDF Section 18)
14
+ """
15
+ from __future__ import annotations
16
+ import logging
17
+ from typing import List, Tuple, Optional
18
+ from models import ArgumentRelation, RelationRecord, ClaimRecord
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _NLI_MODEL_NAME = "cross-encoder/nli-deberta-v3-small"
23
+ _nli_model = None
24
+
25
+
26
+ def load_nli_model() -> None:
27
+ """Load NLI model once at startup. Never reloaded per match."""
28
+ global _nli_model
29
+ if _nli_model is None:
30
+ try:
31
+ from sentence_transformers.cross_encoder import CrossEncoder
32
+ logger.info(f"[Pipeline D] Loading NLI model: {_NLI_MODEL_NAME}")
33
+ _nli_model = CrossEncoder(_NLI_MODEL_NAME)
34
+ logger.info("[Pipeline D] NLI model loaded.")
35
+ except Exception as e:
36
+ logger.error(f"[Pipeline D] Failed to load NLI model: {e}")
37
+ _nli_model = None
38
+
39
+
40
+ def get_nli_model():
41
+ if _nli_model is None:
42
+ load_nli_model()
43
+ return _nli_model
44
+
45
+
46
+ def _nli_scores_to_relation(
47
+ contradiction_score: float,
48
+ entailment_score: float,
49
+ neutral_score: float,
50
+ similarity_score: float,
51
+ current_text: str,
52
+ opponent_text: str
53
+ ) -> Tuple[ArgumentRelation, float, str]:
54
+ """
55
+ Map NLI output scores to debate-specific relation labels.
56
+
57
+ PDF Section 8.5: support/contradict/qualify/elaborate/neutral/unrelated
58
+
59
+ NLI labels from deberta: CONTRADICTION, ENTAILMENT, NEUTRAL
60
+ We extend to 6 debate-relevant relations with heuristic rules.
61
+ """
62
+ # Qualify detection: moderate entailment + hedge language
63
+ import re
64
+ HEDGE = re.compile(
65
+ r'\b(however|but|although|while|though|except|unless|'
66
+ r'only if|in some cases|partly|partially|to some extent)\b',
67
+ re.IGNORECASE
68
+ )
69
+ has_hedge = bool(HEDGE.search(current_text))
70
+
71
+ max_score = max(contradiction_score, entailment_score, neutral_score)
72
+
73
+ if contradiction_score > 0.55:
74
+ if has_hedge:
75
+ return ArgumentRelation.QUALIFY, contradiction_score, "Partially contests with qualification"
76
+ return ArgumentRelation.CONTRADICT, contradiction_score, "Directly contradicts opponent claim"
77
+
78
+ elif entailment_score > 0.55:
79
+ # Distinguish support (agreeing with opponent) from elaboration (building on own)
80
+ # In debate context: if same side claim → elaboration; cross-side → support (concession)
81
+ if similarity_score > 0.80:
82
+ return ArgumentRelation.ELABORATE, entailment_score, "Elaborates on a related point"
83
+ return ArgumentRelation.SUPPORT, entailment_score, "Supports / concedes opponent's point"
84
+
85
+ elif neutral_score > 0.55:
86
+ if similarity_score > 0.50:
87
+ return ArgumentRelation.NEUTRAL, neutral_score, "Same topic but no direct engagement"
88
+ return ArgumentRelation.UNRELATED, neutral_score, "Unrelated to opponent claim"
89
+
90
+ # Low-confidence fallback
91
+ if has_hedge and max_score > 0.40:
92
+ return ArgumentRelation.QUALIFY, max_score, "Qualifies a related claim"
93
+
94
+ return ArgumentRelation.NEUTRAL, max_score, "No clear relation"
95
+
96
+
97
+ def analyze_relation(
98
+ current_claim_text: str,
99
+ opponent_claim_text: str,
100
+ current_claim_id: str,
101
+ opponent_claim_id: str,
102
+ similarity_score: float = 0.0
103
+ ) -> RelationRecord:
104
+ """
105
+ Run NLI cross-encoder on (current_claim, opponent_claim) pair.
106
+ Returns a RelationRecord with the classified relation.
107
+
108
+ PDF Section 14: "Cross-encoder/NLI only on top-k relevant candidate pairs"
109
+ (not on the entire debate history).
110
+ """
111
+ nli_model = get_nli_model()
112
+
113
+ if nli_model is None:
114
+ # Fallback when model unavailable (PDF Section 15.2)
115
+ logger.warning("[Pipeline D] NLI model unavailable — returning NEUTRAL fallback")
116
+ return RelationRecord(
117
+ current_claim_id=current_claim_id,
118
+ opponent_claim_id=opponent_claim_id,
119
+ relation=ArgumentRelation.NEUTRAL,
120
+ score=0.0,
121
+ reasoning_hint="NLI model unavailable"
122
+ )
123
+
124
+ try:
125
+ # DeBERTa NLI outputs [contradiction, entailment, neutral] logits
126
+ scores = nli_model.predict(
127
+ [(current_claim_text, opponent_claim_text)],
128
+ apply_softmax=True
129
+ )[0]
130
+
131
+ # deberta-v3-small label order: contradiction=0, entailment=1, neutral=2
132
+ if len(scores) >= 3:
133
+ contradiction_score = float(scores[0])
134
+ entailment_score = float(scores[1])
135
+ neutral_score = float(scores[2])
136
+ else:
137
+ # Some models return 2 labels; treat as entailment/contradiction
138
+ contradiction_score = float(scores[0]) if len(scores) > 0 else 0.0
139
+ entailment_score = float(scores[1]) if len(scores) > 1 else 0.0
140
+ neutral_score = 1.0 - contradiction_score - entailment_score
141
+
142
+ relation, score, hint = _nli_scores_to_relation(
143
+ contradiction_score, entailment_score, neutral_score,
144
+ similarity_score, current_claim_text, opponent_claim_text
145
+ )
146
+
147
+ logger.debug(
148
+ f"[Pipeline D] {relation.value} (conf={score:.2f}): "
149
+ f"'{current_claim_text[:40]}...' vs '{opponent_claim_text[:40]}...'"
150
+ )
151
+
152
+ return RelationRecord(
153
+ current_claim_id=current_claim_id,
154
+ opponent_claim_id=opponent_claim_id,
155
+ relation=relation,
156
+ score=score,
157
+ reasoning_hint=hint
158
+ )
159
+
160
+ except Exception as e:
161
+ logger.error(f"[Pipeline D] NLI inference error: {e}")
162
+ return RelationRecord(
163
+ current_claim_id=current_claim_id,
164
+ opponent_claim_id=opponent_claim_id,
165
+ relation=ArgumentRelation.NEUTRAL,
166
+ score=0.0,
167
+ reasoning_hint=f"Inference error: {type(e).__name__}"
168
+ )
169
+
170
+
171
+ def analyze_all_relations(
172
+ current_claims: List[ClaimRecord],
173
+ relevant_opponent_pairs: List[Tuple[ClaimRecord, ClaimRecord, float]]
174
+ ) -> List[RelationRecord]:
175
+ """
176
+ Analyze relations for all (current_claim, opponent_claim) pairs.
177
+ PDF Section 8.3: "One response may challenge two, three, or more previous claims."
178
+
179
+ relevant_opponent_pairs: list of (current_claim, opponent_claim, similarity_score)
180
+ """
181
+ results = []
182
+ for current, opponent, similarity in relevant_opponent_pairs:
183
+ record = analyze_relation(
184
+ current_claim_text=current.text,
185
+ opponent_claim_text=opponent.text,
186
+ current_claim_id=current.claim_id,
187
+ opponent_claim_id=opponent.claim_id,
188
+ similarity_score=similarity
189
+ )
190
+ results.append(record)
191
+ return results
192
+
193
+
194
+ def compute_rebuttal_signal(
195
+ relations: List[RelationRecord],
196
+ has_reasoning: bool = True
197
+ ) -> float:
198
+ """
199
+ Compute rebuttal quality signal (0-1) from relation records.
200
+
201
+ PDF Section 12, Rule 1: Contradiction alone ≠ strong rebuttal.
202
+ A strong rebuttal requires reasoning + contradiction/qualification.
203
+
204
+ Returns a score that the scoring engine weights at 20%.
205
+ """
206
+ if not relations:
207
+ return 0.0
208
+
209
+ score = 0.0
210
+ for rel in relations:
211
+ if rel.relation == ArgumentRelation.CONTRADICT:
212
+ # Base contradiction credit; reasoning multiplier applied below
213
+ score += 0.6 * rel.score
214
+ elif rel.relation == ArgumentRelation.QUALIFY:
215
+ score += 0.7 * rel.score # qualification shows nuanced engagement
216
+ elif rel.relation == ArgumentRelation.ELABORATE:
217
+ score += 0.3 * rel.score
218
+ elif rel.relation == ArgumentRelation.NEUTRAL:
219
+ score += 0.1 * rel.score
220
+ # SUPPORT/UNRELATED contribute 0 to rebuttal (concession / off-topic)
221
+
222
+ # Normalize across number of relations
223
+ score = min(1.0, score / max(len(relations), 1))
224
+
225
+ # PDF Rule 1: reasoning required for strong rebuttal
226
+ # If no reasoning detected, cap at 0.5 even if contradiction found
227
+ if not has_reasoning:
228
+ score = min(score, 0.50)
229
+
230
+ return score
231
+
232
+
233
+ def detect_has_reasoning(text: str) -> bool:
234
+ """
235
+ Lightweight heuristic to detect presence of reasoning/justification.
236
+ PDF Section 12, Rule 1: "That is wrong" → disagreement but no reasoning.
237
+ """
238
+ import re
239
+ REASONING_MARKERS = re.compile(
240
+ r'\b(because|therefore|thus|hence|since|as a result|'
241
+ r'this means|which means|this shows|this demonstrates|'
242
+ r'the reason|due to|given that|evidence shows|research shows|'
243
+ r'studies show|data shows|for example|for instance|'
244
+ r'this is why|consequently|it follows that|as we can see)\b',
245
+ re.IGNORECASE
246
+ )
247
+ return bool(REASONING_MARKERS.search(text))
248
+
249
+
250
+ def check_stance_consistency(
251
+ current_text: str,
252
+ player_side: str, # "FOR" or "AGAINST"
253
+ topic: str
254
+ ) -> float:
255
+ """
256
+ Simple stance consistency heuristic (PDF Section 11: 10% weight).
257
+ Returns 0-1 score.
258
+
259
+ In a full deployment this would use a stance classifier.
260
+ Here we use a heuristic based on explicit position markers.
261
+ """
262
+ import re
263
+ text_lower = current_text.lower()
264
+
265
+ FOR_MARKERS = re.compile(
266
+ r'\b(support|agree|advocate|favor|endorse|benefit|advantage|'
267
+ r'positive|improve|better|should|must|can|will)\b',
268
+ re.IGNORECASE
269
+ )
270
+ AGAINST_MARKERS = re.compile(
271
+ r'\b(oppose|against|reject|disagree|harm|disadvantage|'
272
+ r'negative|worse|risk|danger|should not|must not|cannot|will not)\b',
273
+ re.IGNORECASE
274
+ )
275
+
276
+ for_count = len(FOR_MARKERS.findall(current_text))
277
+ against_count = len(AGAINST_MARKERS.findall(current_text))
278
+
279
+ if for_count + against_count == 0:
280
+ return 0.6 # Neutral text; moderate stance score
281
+
282
+ ratio = for_count / (for_count + against_count)
283
+
284
+ if player_side == "FOR":
285
+ # FOR side should have more FOR markers
286
+ return min(1.0, 0.3 + ratio * 0.7)
287
+ else:
288
+ # AGAINST side should have more AGAINST markers
289
+ return min(1.0, 0.3 + (1 - ratio) * 0.7)
backend/pipeline_e_rag.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pipeline E — Internet RAG Fact Verification (PDF Section 9 + 10)
3
+ Retrieves evidence from the Internet for checkable factual claims.
4
+ Returns SUPPORTED | PARTIALLY_SUPPORTED | REFUTED | INSUFFICIENT_EVIDENCE | AMBIGUOUS.
5
+
6
+ PDF Section 9: "Search retrieval and verification are separate steps."
7
+ PDF Section 9.1: "Retrieve passages, not just URLs."
8
+ PDF Section 9.2: "Retain conflicting evidence, return conflict/uncertainty status."
9
+ PDF Section 9.5: "Failure to find evidence does NOT prove participant is wrong."
10
+ PDF Section 14: "RAG runs in parallel; 8-second timeout; if delayed, mark pending."
11
+ PDF Section 15.6: "Cache repeated claims; backoff on rate limits."
12
+
13
+ What we will NOT do (PDF Section 22):
14
+ - NOT treat first web search result as proof
15
+ - NOT force true/false when evidence is incomplete
16
+ """
17
+ from __future__ import annotations
18
+ import asyncio
19
+ import hashlib
20
+ import logging
21
+ import re
22
+ import time
23
+ from typing import List, Optional, Tuple
24
+ import httpx
25
+ from bs4 import BeautifulSoup
26
+ from models import VerificationVerdict, VerificationResult, EvidenceSource
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ # Global query cache — persists across matches (PDF Section 14, 15.6)
31
+ # Separate from match state (PDF Section 16)
32
+ _rag_cache: dict = {}
33
+ _CACHE_MAX_SIZE = 200 # bound size (PDF Section 15.5)
34
+
35
+ RAG_TIMEOUT = 8.0 # seconds (PDF Section 14, point 7)
36
+ MAX_SOURCES_PER_CLAIM = 4
37
+ MAX_REQUESTS_PER_TURN = 3 # rate limit guard (PDF Section 15.6)
38
+
39
+ # Source quality priority (PDF Section 9.3)
40
+ HIGH_QUALITY_DOMAINS = {
41
+ "gov", "edu", "who.int", "un.org", "nih.gov", "cdc.gov",
42
+ "worldbank.org", "nature.com", "science.org", "ncbi.nlm.nih.gov",
43
+ "scholar.google.com", "pubmed.ncbi.nlm.nih.gov"
44
+ }
45
+ MEDIUM_QUALITY_DOMAINS = {
46
+ "wikipedia.org", "britannica.com", "bbc.com", "reuters.com",
47
+ "apnews.com", "theguardian.com", "nytimes.com", "economist.com"
48
+ }
49
+
50
+
51
+ def _get_domain_quality(url: str) -> float:
52
+ """Source quality scoring (PDF Section 9.3)."""
53
+ url_lower = url.lower()
54
+ for domain in HIGH_QUALITY_DOMAINS:
55
+ if domain in url_lower:
56
+ return 0.9
57
+ for domain in MEDIUM_QUALITY_DOMAINS:
58
+ if domain in url_lower:
59
+ return 0.65
60
+ return 0.3 # Unknown/low-quality source
61
+
62
+
63
+ def _cache_key(claim_text: str) -> str:
64
+ return hashlib.sha256(claim_text.strip().lower().encode()).hexdigest()[:16]
65
+
66
+
67
+ def _get_cached(claim_text: str) -> Optional[VerificationResult]:
68
+ key = _cache_key(claim_text)
69
+ return _rag_cache.get(key)
70
+
71
+
72
+ def _set_cache(claim_text: str, result: VerificationResult) -> None:
73
+ key = _cache_key(claim_text)
74
+ if len(_rag_cache) >= _CACHE_MAX_SIZE:
75
+ # Evict oldest entry
76
+ oldest = next(iter(_rag_cache))
77
+ del _rag_cache[oldest]
78
+ _rag_cache[key] = result
79
+
80
+
81
+ def _generate_search_query(claim_text: str) -> str:
82
+ """
83
+ Generate a focused search query from the claim.
84
+ PDF Section 10, Step 2: "For numerical claims, include entities, metric, time context."
85
+ """
86
+ # Remove opinion markers to focus on factual content
87
+ query = re.sub(
88
+ r'\b(I think|I believe|in my opinion|it seems|personally)\b',
89
+ '', claim_text, flags=re.IGNORECASE
90
+ ).strip()
91
+
92
+ # Truncate to reasonable search length
93
+ if len(query) > 150:
94
+ # Keep the most information-dense part
95
+ query = query[:150].rsplit(' ', 1)[0]
96
+
97
+ return query
98
+
99
+
100
+ async def _search_duckduckgo(query: str, max_results: int = 5) -> List[dict]:
101
+ """
102
+ Search DuckDuckGo with resilient Wikipedia API fallback (no API key required).
103
+ Returns list of {url, title, snippet} dicts.
104
+ """
105
+ results = []
106
+ # 1. Try DuckDuckGo
107
+ try:
108
+ from duckduckgo_search import DDGS
109
+ with DDGS() as ddgs:
110
+ # Try text search
111
+ for r in ddgs.text(query, max_results=max_results):
112
+ results.append({
113
+ "url": r.get("href", ""),
114
+ "title": r.get("title", ""),
115
+ "snippet": r.get("body", "")
116
+ })
117
+ # Try news search if text search empty
118
+ if not results:
119
+ for r in ddgs.news(query, max_results=max_results):
120
+ results.append({
121
+ "url": r.get("url", ""),
122
+ "title": r.get("title", ""),
123
+ "snippet": r.get("body", "")
124
+ })
125
+ except Exception as e:
126
+ logger.warning(f"[Pipeline E] DuckDuckGo search failed/rate-limited: {e}")
127
+
128
+ # 2. Resilient Encyclopedic Fallback: Wikipedia API (PDF Section 9.3: high authority)
129
+ if len(results) < 2:
130
+ try:
131
+ async with httpx.AsyncClient(timeout=4.0) as client:
132
+ resp = await client.get(
133
+ "https://en.wikipedia.org/w/api.php",
134
+ params={
135
+ "action": "query",
136
+ "list": "search",
137
+ "srsearch": query,
138
+ "format": "json"
139
+ },
140
+ headers={"User-Agent": "ClashOfMindsDebateJudge/1.0 (academic-research@nitw.ac.in)"}
141
+ )
142
+ if resp.status_code == 200:
143
+ data = resp.json().get("query", {}).get("search", [])
144
+ for item in data[:max_results]:
145
+ title = item.get("title", "")
146
+ slug = title.replace(" ", "_")
147
+ snippet = item.get("snippet", "").replace('<span class="searchmatch">', '').replace('</span>', '')
148
+ results.append({
149
+ "url": f"https://en.wikipedia.org/wiki/{slug}",
150
+ "title": title,
151
+ "snippet": snippet
152
+ })
153
+ logger.info(f"[Pipeline E] Wikipedia fallback retrieved {len(results)} authoritative sources for: {query[:40]}")
154
+ except Exception as e:
155
+ logger.warning(f"[Pipeline E] Wikipedia search fallback failed: {e}")
156
+
157
+ return results
158
+
159
+
160
+ async def _extract_passage(url: str, claim_text: str, client: httpx.AsyncClient) -> Optional[str]:
161
+ """
162
+ Extract the most relevant passage from a URL (PDF Section 9.1: passages, not URLs).
163
+ Returns the best passage or None if extraction fails.
164
+ """
165
+ try:
166
+ resp = await client.get(url, timeout=4.0, follow_redirects=True)
167
+ if resp.status_code != 200:
168
+ return None
169
+
170
+ soup = BeautifulSoup(resp.text, 'lxml')
171
+
172
+ # Remove script, style, nav elements
173
+ for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside']):
174
+ tag.decompose()
175
+
176
+ # Get paragraph texts
177
+ paragraphs = [p.get_text(strip=True) for p in soup.find_all('p')]
178
+ paragraphs = [p for p in paragraphs if len(p) > 50]
179
+
180
+ if not paragraphs:
181
+ return None
182
+
183
+ # Score paragraphs by keyword overlap with claim
184
+ claim_words = set(claim_text.lower().split())
185
+ stop_words = {'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'to', 'of', 'in', 'on', 'at'}
186
+ claim_words -= stop_words
187
+
188
+ scored = []
189
+ for para in paragraphs[:30]: # check first 30 paragraphs
190
+ para_words = set(para.lower().split())
191
+ overlap = len(claim_words & para_words)
192
+ scored.append((overlap, para))
193
+
194
+ scored.sort(reverse=True)
195
+
196
+ if scored and scored[0][0] > 0:
197
+ return scored[0][1][:800] # bounded passage length
198
+
199
+ except Exception as e:
200
+ logger.debug(f"[Pipeline E] Passage extraction failed for {url}: {e}")
201
+
202
+ return None
203
+
204
+
205
+ def _verify_with_nli(passage: str, claim_text: str) -> Tuple[str, float]:
206
+ """
207
+ Run NLI verification between passage and claim.
208
+ Returns (nli_label, confidence): "ENTAILMENT" | "CONTRADICTION" | "NEUTRAL"
209
+ """
210
+ try:
211
+ from pipeline_d_nli import get_nli_model
212
+ nli_model = get_nli_model()
213
+ if nli_model is None:
214
+ return "NEUTRAL", 0.0
215
+
216
+ scores = nli_model.predict([(passage[:500], claim_text)], apply_softmax=True)[0]
217
+
218
+ if len(scores) >= 3:
219
+ labels = ["CONTRADICTION", "ENTAILMENT", "NEUTRAL"]
220
+ best_idx = int(scores.argmax())
221
+ return labels[best_idx], float(scores[best_idx])
222
+ elif len(scores) == 2:
223
+ if scores[0] > scores[1]:
224
+ return "CONTRADICTION", float(scores[0])
225
+ return "ENTAILMENT", float(scores[1])
226
+
227
+ except Exception as e:
228
+ logger.warning(f"[Pipeline E] NLI verification failed: {e}")
229
+
230
+ return "NEUTRAL", 0.0
231
+
232
+
233
+ def _aggregate_verdicts(
234
+ verdicts: List[Tuple[str, float, EvidenceSource]]
235
+ ) -> Tuple[VerificationVerdict, float, bool]:
236
+ """
237
+ Aggregate multiple source verdicts into a final decision.
238
+ PDF Section 9.2: "Retain conflicting evidence; return conflict/uncertainty status."
239
+ PDF Section 9.6: "Verify each atomic claim separately."
240
+ """
241
+ if not verdicts:
242
+ return VerificationVerdict.INSUFFICIENT_EVIDENCE, 0.0, False
243
+
244
+ entailments = [(s, src) for label, s, src in verdicts if label == "ENTAILMENT"]
245
+ contradictions = [(s, src) for label, s, src in verdicts if label == "CONTRADICTION"]
246
+ neutrals = [(s, src) for label, s, src in verdicts if label == "NEUTRAL"]
247
+
248
+ # Check for conflicting evidence (PDF Section 9.2)
249
+ has_conflict = bool(entailments) and bool(contradictions)
250
+
251
+ total_sources = len(verdicts)
252
+ support_ratio = len(entailments) / total_sources
253
+
254
+ # Weight by source quality
255
+ weighted_support = sum(
256
+ s * src.source_quality for s, src in entailments
257
+ ) / max(len(entailments), 1) if entailments else 0.0
258
+
259
+ weighted_refute = sum(
260
+ s * src.source_quality for s, src in contradictions
261
+ ) / max(len(contradictions), 1) if contradictions else 0.0
262
+
263
+ if has_conflict:
264
+ return VerificationVerdict.AMBIGUOUS, max(weighted_support, weighted_refute), True
265
+
266
+ if support_ratio >= 0.6 and weighted_support >= 0.55:
267
+ if support_ratio == 1.0 and weighted_support >= 0.75:
268
+ return VerificationVerdict.SUPPORTED, weighted_support, False
269
+ return VerificationVerdict.PARTIALLY_SUPPORTED, weighted_support, False
270
+
271
+ if contradictions and weighted_refute >= 0.6:
272
+ return VerificationVerdict.REFUTED, weighted_refute, False
273
+
274
+ return VerificationVerdict.INSUFFICIENT_EVIDENCE, 0.0, False
275
+
276
+
277
+ async def verify_claim(claim_text: str, claim_type_str: str) -> VerificationResult:
278
+ """
279
+ Main entry point for fact verification (PDF Section 10).
280
+
281
+ Steps (exact from PDF Section 10):
282
+ 1. Extract claim as-is, preserve qualifiers
283
+ 2. Generate focused search query
284
+ 3. Retrieve multiple candidate sources
285
+ 4. Extract relevant passages
286
+ 5. Rank passages (semantic similarity)
287
+ 6. Run NLI verification
288
+ 7. Check full/partial/contradicted support
289
+ 8. Return verdict with evidence and uncertainty
290
+ """
291
+ # Check cache first (PDF Section 14, 15.6)
292
+ cached = _get_cached(claim_text)
293
+ if cached is not None:
294
+ logger.debug(f"[Pipeline E] Cache hit for: {claim_text[:50]}...")
295
+ return cached
296
+
297
+ # Generate search query (PDF Section 10, Step 2)
298
+ query = _generate_search_query(claim_text)
299
+
300
+ result = VerificationResult(verdict=VerificationVerdict.PENDING)
301
+
302
+ try:
303
+ async with asyncio.timeout(RAG_TIMEOUT):
304
+ # Step 3: Retrieve sources (PDF Section 10, Step 3)
305
+ search_results = await _search_duckduckgo(query, max_results=MAX_SOURCES_PER_CLAIM)
306
+
307
+ if not search_results:
308
+ result.verdict = VerificationVerdict.INSUFFICIENT_EVIDENCE
309
+ result.notes = "No search results returned"
310
+ return result
311
+
312
+ # Step 4: Extract passages (PDF Section 10, Step 4)
313
+ # Step 5: Rank passages (PDF Section 10, Step 5)
314
+ # Run passage extraction in parallel
315
+ async with httpx.AsyncClient(
316
+ headers={"User-Agent": "Mozilla/5.0 (research bot)"},
317
+ timeout=4.0
318
+ ) as client:
319
+ passage_tasks = [
320
+ _extract_passage(r["url"], claim_text, client)
321
+ for r in search_results[:MAX_SOURCES_PER_CLAIM]
322
+ ]
323
+ passages = await asyncio.gather(*passage_tasks, return_exceptions=True)
324
+
325
+ # Step 6: Run NLI verification for each passage (PDF Section 10, Step 6)
326
+ verdicts = []
327
+ sources = []
328
+
329
+ for i, (search_res, passage) in enumerate(zip(search_results, passages)):
330
+ if isinstance(passage, Exception) or not passage:
331
+ # Use snippet as fallback passage
332
+ passage = search_res.get("snippet", "")
333
+
334
+ if not passage:
335
+ continue
336
+
337
+ url = search_res.get("url", "")
338
+ quality = _get_domain_quality(url)
339
+
340
+ source = EvidenceSource(
341
+ url=url,
342
+ domain=url.split("/")[2] if "/" in url else url,
343
+ title=search_res.get("title", ""),
344
+ source_quality=quality
345
+ )
346
+
347
+ # NLI verification (PDF Section 10, Step 6)
348
+ nli_label, confidence = _verify_with_nli(passage, claim_text)
349
+
350
+ # Weight by source quality (PDF Section 9.3)
351
+ weighted_confidence = confidence * quality
352
+
353
+ verdicts.append((nli_label, weighted_confidence, source))
354
+ sources.append(source)
355
+
356
+ # Collect evidence excerpts
357
+ if nli_label in ("ENTAILMENT", "CONTRADICTION"):
358
+ result.evidence_passages.append(passage[:300])
359
+
360
+ result.sources = sources
361
+
362
+ # Step 7-8: Aggregate (PDF Section 10, Step 7-8)
363
+ verdict, confidence, conflicting = _aggregate_verdicts(verdicts)
364
+
365
+ result.verdict = verdict
366
+ result.confidence = confidence
367
+ result.conflicting_evidence = conflicting
368
+ result.notes = "Conflicting sources found" if conflicting else ""
369
+
370
+ except asyncio.TimeoutError:
371
+ # PDF Section 14: "If RAG is delayed, mark pending; do not freeze debate UI"
372
+ logger.warning(f"[Pipeline E] RAG timeout for: {claim_text[:50]}...")
373
+ result.verdict = VerificationVerdict.PENDING
374
+ result.notes = "Verification timeout — result pending"
375
+ return result # Do NOT cache timeouts
376
+
377
+ except Exception as e:
378
+ logger.error(f"[Pipeline E] RAG error: {e}")
379
+ result.verdict = VerificationVerdict.INSUFFICIENT_EVIDENCE
380
+ result.notes = f"Verification error: {type(e).__name__}"
381
+
382
+ # Cache successful results (not timeouts)
383
+ if result.verdict != VerificationVerdict.PENDING:
384
+ _set_cache(claim_text, result)
385
+
386
+ return result
387
+
388
+
389
+ def evidence_quality_score(verification_result: VerificationResult) -> float:
390
+ """
391
+ Convert verification verdict into scoring signal (0-1) for the scoring engine.
392
+ PDF Section 11: Evidence Quality = 20% weight.
393
+ PDF Section 12, Rule 5: "Fact verification failure ≠ decides entire match."
394
+ PDF Section 12, Rule 6: "Unverified → labeled 'unverified', NOT 'false'."
395
+ """
396
+ verdicts_to_score = {
397
+ VerificationVerdict.SUPPORTED: 1.0,
398
+ VerificationVerdict.PARTIALLY_SUPPORTED: 0.6,
399
+ VerificationVerdict.AMBIGUOUS: 0.4,
400
+ VerificationVerdict.INSUFFICIENT_EVIDENCE: 0.3, # NOT 0 (PDF Rule 6)
401
+ VerificationVerdict.PENDING: 0.3,
402
+ VerificationVerdict.NOT_CHECKABLE: 0.5, # opinions etc — neutral
403
+ VerificationVerdict.REFUTED: 0.05, # low but NOT 0 (PDF Rule 5 — bounded)
404
+ }
405
+ base = verdicts_to_score.get(verification_result.verdict, 0.3)
406
+
407
+ # Adjust by source quality if we have sources
408
+ if verification_result.sources:
409
+ avg_quality = sum(s.source_quality for s in verification_result.sources) / len(verification_result.sources)
410
+ # Small quality adjustment
411
+ base = base * (0.7 + 0.3 * avg_quality)
412
+
413
+ return round(min(1.0, base), 3)
backend/requirements.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ websockets
4
+ pydantic
5
+ python-multipart
6
+
7
+ # NLP pipelines
8
+ sentence-transformers
9
+ transformers
10
+ torch
11
+ scipy
12
+ scikit-learn
13
+ numpy
14
+ faiss-cpu
15
+
16
+ # Claim segmentation + lexical
17
+ spacy
18
+ rapidfuzz
19
+
20
+ # Internet RAG
21
+ httpx
22
+ beautifulsoup4
23
+ lxml
24
+ duckduckgo-search
25
+
26
+ # Storage
27
+ aiosqlite
28
+
29
+ # Utilities
30
+ python-dotenv
backend/scoring.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Scoring Engine — PDF Section 11 and 12
3
+ Deterministic aggregation of 5 independently measured signals.
4
+
5
+ PDF Section 11: "Scoring is a deterministic aggregation layer over several
6
+ independently measured signals. The system should NOT use a single model to
7
+ predict a winner directly."
8
+
9
+ Weights (from PDF Section 11):
10
+ - Counterargument/Rebuttal: 20%
11
+ - Logical Reasoning: 20%
12
+ - Evidence Quality (RAG): 20%
13
+ - Topic Relevance: 15%
14
+ - Clarity: 15%
15
+ - Stance Consistency: 10%
16
+
17
+ Fairness rules (from PDF Section 12, all implemented):
18
+ 1. Contradiction ≠ strong rebuttal (reasoning required)
19
+ 2. True fact ≠ strong argument (evidence and reasoning scored separately)
20
+ 3. Complex vocabulary ≠ reward (clarity = structure + coherence)
21
+ 4. Repetition with new evidence is NOT penalized
22
+ 5. Fact-check failure only affects evidence component
23
+ 6. Unverified claims → "unverified", NOT "false"
24
+ """
25
+ from __future__ import annotations
26
+ import logging
27
+ import re
28
+ from typing import List, Tuple
29
+ from models import (
30
+ TurnScore, ClaimRecord, RelationRecord, VerificationResult,
31
+ RepetitionClass, ClaimType, ArgumentRelation, VerificationVerdict
32
+ )
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # ─── Scoring weights (PDF Section 11 exact values) ────────────────────────────
37
+ WEIGHT_REBUTTAL = 0.20
38
+ WEIGHT_REASONING = 0.20
39
+ WEIGHT_EVIDENCE = 0.20
40
+ WEIGHT_RELEVANCE = 0.15
41
+ WEIGHT_CLARITY = 0.15
42
+ WEIGHT_STANCE = 0.10
43
+
44
+
45
+ def _score_topic_relevance(
46
+ claim_embeddings: List, # np.ndarray per claim
47
+ topic_embedding, # np.ndarray
48
+ claims: List[ClaimRecord]
49
+ ) -> float:
50
+ """
51
+ 15% weight. Semantic relation between topic and participant's claims.
52
+ PDF Section 11: "semantic relation between the topic/question and participant's actual claims."
53
+ """
54
+ if not claim_embeddings or topic_embedding is None:
55
+ return 0.5 # neutral default
56
+
57
+ from pipeline_a_embedding import cosine_similarity
58
+ import numpy as np
59
+
60
+ sims = [cosine_similarity(emb, topic_embedding) for emb in claim_embeddings]
61
+ avg_sim = float(np.mean(sims))
62
+
63
+ # Normalize: cosine similarity in [0,1] for normalized vectors
64
+ return min(1.0, max(0.0, avg_sim))
65
+
66
+
67
+ def _score_clarity(response_text: str, claims: List[ClaimRecord]) -> float:
68
+ """
69
+ 15% weight. Structure, readability, coherent expression.
70
+ PDF Section 11: "Should NOT reward unnecessarily complex vocabulary."
71
+ PDF Rule 3: "Not rewarded for complicated English."
72
+
73
+ We measure: sentence structure, appropriate length, discourse markers,
74
+ NOT word length or rarity.
75
+ """
76
+ if not response_text:
77
+ return 0.0
78
+
79
+ text = response_text.strip()
80
+ words = text.split()
81
+ sentences = re.split(r'[.!?]+', text)
82
+ sentences = [s.strip() for s in sentences if len(s.strip()) > 5]
83
+
84
+ score = 0.5 # baseline
85
+
86
+ # Good length (not too short, not rambling) — 30-400 words is ideal
87
+ word_count = len(words)
88
+ if 30 <= word_count <= 400:
89
+ score += 0.15
90
+ elif word_count < 10:
91
+ score -= 0.20
92
+
93
+ # Sentence variety (multiple sentences = structured argument)
94
+ if len(sentences) >= 2:
95
+ score += 0.10
96
+ if len(sentences) >= 4:
97
+ score += 0.05
98
+
99
+ # Discourse / coherence markers
100
+ DISCOURSE_MARKERS = re.compile(
101
+ r'\b(first|second|third|finally|furthermore|moreover|however|'
102
+ r'therefore|thus|in addition|on the other hand|in contrast|'
103
+ r'as a result|consequently|to summarize|in conclusion)\b',
104
+ re.IGNORECASE
105
+ )
106
+ if DISCOURSE_MARKERS.search(text):
107
+ score += 0.10
108
+
109
+ # Penalize very short single sentence (likely underdeveloped)
110
+ if len(sentences) == 1 and word_count < 20:
111
+ score -= 0.15
112
+
113
+ return round(min(1.0, max(0.0, score)), 3)
114
+
115
+
116
+ def _score_logical_reasoning(
117
+ response_text: str,
118
+ claims: List[ClaimRecord],
119
+ relations: List[RelationRecord]
120
+ ) -> float:
121
+ """
122
+ 20% weight. Quality of reasoning connecting claims to position.
123
+ PDF Section 11: "supported by argument structure signals."
124
+ PDF Rule 2: "True fact ≠ strong argument — reasoning scored separately."
125
+ """
126
+ score = 0.4 # baseline
127
+
128
+ # Reasoning & causal connectors (broadened to avoid unfair dependence on simple 'because')
129
+ REASONING = re.compile(
130
+ r'\b(because|therefore|thus|hence|since|as a result|which means|'
131
+ r'this demonstrates|the reason is|due to|given that|it follows|'
132
+ r'evidence shows|this proves|this suggests|this implies|leads to|'
133
+ r'leading to|results in|resulting in|causes|causing|triggers|'
134
+ r'undermines|reinforces|justifies|entails|drives|stems from|'
135
+ r'correlates with|in order to|so that|by doing so|consequently|'
136
+ r'for example|for instance|specifically|in particular)\b',
137
+ re.IGNORECASE
138
+ )
139
+
140
+ # Structural & conditional logic markers
141
+ LOGICAL_STRUCTURE = re.compile(
142
+ r'\b(if|then|when|unless|provided|assuming|given|without|despite|'
143
+ r'although|even though|while|whereas|otherwise|in contrast|'
144
+ r'on the contrary|conversely|alternatively|nevertheless|nonetheless|'
145
+ r'in spite of|as long as)\b',
146
+ re.IGNORECASE
147
+ )
148
+
149
+ reason_count = len(REASONING.findall(response_text))
150
+ logic_count = len(LOGICAL_STRUCTURE.findall(response_text))
151
+
152
+ score += min(0.25, reason_count * 0.08)
153
+ score += min(0.15, logic_count * 0.05)
154
+
155
+ # Multiple distinct claims with logical flow = better reasoning
156
+ claim_count = len(claims)
157
+ if claim_count >= 2:
158
+ score += 0.10
159
+ if claim_count >= 3:
160
+ score += 0.05
161
+
162
+ # Relations in relations show logical engagement
163
+ engaged_relations = [
164
+ r for r in relations
165
+ if r.relation in (
166
+ ArgumentRelation.CONTRADICT, ArgumentRelation.QUALIFY,
167
+ ArgumentRelation.ELABORATE
168
+ )
169
+ ]
170
+ if engaged_relations:
171
+ score += min(0.10, len(engaged_relations) * 0.05)
172
+
173
+ return round(min(1.0, max(0.0, score)), 3)
174
+
175
+
176
+ def _score_evidence_quality(
177
+ claims: List[ClaimRecord]
178
+ ) -> float:
179
+ """
180
+ 20% weight. Quality and support of factual claims via Internet RAG.
181
+ PDF Rule 5: Fact-check failure ≠ decides entire match (only evidence component).
182
+ PDF Rule 6: Unverified → 'unverified', NOT 'false' (conservative score, not 0).
183
+ """
184
+ from pipeline_e_rag import evidence_quality_score
185
+
186
+ checkable = [
187
+ c for c in claims
188
+ if c.claim_type in (ClaimType.FACTUAL, ClaimType.STATISTICAL)
189
+ ]
190
+
191
+ if not checkable:
192
+ # No factual claims to verify — neutral score (not 0)
193
+ # PDF: opinions etc are not checked; don't punish for having no facts
194
+ return 0.55
195
+
196
+ scores = [evidence_quality_score(c.verification) for c in checkable]
197
+ return round(sum(scores) / len(scores), 3)
198
+
199
+
200
+ def _score_rebuttal(
201
+ relations: List[RelationRecord],
202
+ response_text: str,
203
+ addressed_opponent_claims_count: int
204
+ ) -> float:
205
+ """
206
+ 20% weight. Whether participant directly addresses relevant opponent claims.
207
+ PDF Section 11: "provides a meaningful response."
208
+ PDF Rule 1: Contradiction alone ≠ strong rebuttal; reasoning required.
209
+ """
210
+ from pipeline_d_nli import compute_rebuttal_signal, detect_has_reasoning
211
+
212
+ has_reasoning = detect_has_reasoning(response_text)
213
+ base = compute_rebuttal_signal(relations, has_reasoning)
214
+
215
+ # Bonus for addressing multiple opponent claims (PDF Section 8.3)
216
+ if addressed_opponent_claims_count >= 2:
217
+ base = min(1.0, base + 0.08)
218
+
219
+ return round(base, 3)
220
+
221
+
222
+ def _compute_repetition_penalty(
223
+ repetition_classes: List[RepetitionClass]
224
+ ) -> float:
225
+ """
226
+ Repetition penalty.
227
+ PDF Section 7.4 + Rule 4: Penalize ONLY genuine repetition.
228
+ Rephrased, elaborated, or repeated-with-new-evidence → NOT penalized.
229
+ """
230
+ if not repetition_classes:
231
+ return 0.0
232
+
233
+ penalty = 0.0
234
+ for cls in repetition_classes:
235
+ if cls == RepetitionClass.REPEATED:
236
+ penalty += 0.08 # genuine repetition penalty
237
+ elif cls == RepetitionClass.REPHRASED:
238
+ penalty += 0.02 # small penalty for rephrasing without adding value
239
+ # ELABORATED, REPEATED_WITH_NEW_EVIDENCE, NEW → no penalty
240
+ elif cls in (RepetitionClass.ELABORATED, RepetitionClass.REPEATED_WITH_NEW_EVIDENCE, RepetitionClass.NEW):
241
+ penalty += 0.0
242
+
243
+ # Bound penalty so one bad turn doesn't eliminate a player (PDF Section 13)
244
+ return min(0.25, penalty)
245
+
246
+
247
+ def compute_turn_score(
248
+ turn_id: str,
249
+ player_id: str,
250
+ round_number: int,
251
+ response_text: str,
252
+ claims: List[ClaimRecord],
253
+ claim_embeddings: List,
254
+ topic_embedding,
255
+ relations: List[RelationRecord],
256
+ repetition_classes: List[RepetitionClass],
257
+ addressed_opponent_claims_count: int,
258
+ player_side: str
259
+ ) -> TurnScore:
260
+ """
261
+ Main scoring function. Aggregates all 5 criteria into a turn score.
262
+
263
+ All scoring is deterministic (PDF Section 11 principle).
264
+ The function calls each criterion independently and then combines.
265
+ """
266
+ # Compute each criterion independently
267
+ relevance = _score_topic_relevance(claim_embeddings, topic_embedding, claims)
268
+ clarity = _score_clarity(response_text, claims)
269
+ reasoning = _score_logical_reasoning(response_text, claims, relations)
270
+ rebuttal = _score_rebuttal(relations, response_text, addressed_opponent_claims_count)
271
+ evidence = _score_evidence_quality(claims)
272
+ stance = _check_stance_from_nli(response_text, player_side)
273
+
274
+ # Repetition penalty (bounded — PDF Section 13)
275
+ penalty = _compute_repetition_penalty(repetition_classes)
276
+
277
+ # Weighted total (PDF Section 11 exact weights)
278
+ weighted = (
279
+ rebuttal * WEIGHT_REBUTTAL +
280
+ reasoning * WEIGHT_REASONING +
281
+ evidence * WEIGHT_EVIDENCE +
282
+ relevance * WEIGHT_RELEVANCE +
283
+ clarity * WEIGHT_CLARITY +
284
+ stance * WEIGHT_STANCE
285
+ )
286
+
287
+ # Apply penalty (bounded to prevent a single turn from dominating — PDF Section 13)
288
+ weighted_total = max(0.0, weighted - penalty)
289
+ weighted_total = round(weighted_total, 4)
290
+
291
+ # Generate human-readable feedback
292
+ feedback = _generate_feedback(
293
+ relevance=relevance, clarity=clarity, reasoning=reasoning,
294
+ rebuttal=rebuttal, evidence=evidence, stance=stance,
295
+ penalty=penalty, relations=relations, claims=claims,
296
+ round_number=round_number
297
+ )
298
+
299
+ # Check if any RAG is still pending
300
+ rag_pending = any(
301
+ c.verification.verdict == VerificationVerdict.PENDING
302
+ for c in claims
303
+ if c.claim_type in (ClaimType.FACTUAL, ClaimType.STATISTICAL)
304
+ )
305
+
306
+ turn_score = TurnScore(
307
+ turn_id=turn_id,
308
+ player_id=player_id,
309
+ round_number=round_number,
310
+ topic_relevance_raw=relevance,
311
+ clarity_raw=clarity,
312
+ logical_reasoning_raw=reasoning,
313
+ rebuttal_raw=rebuttal,
314
+ evidence_quality_raw=evidence,
315
+ stance_consistency_raw=stance,
316
+ repetition_penalty=penalty,
317
+ weighted_total=weighted_total,
318
+ claims_analyzed=len(claims),
319
+ relations_found=relations,
320
+ repetition_classes=repetition_classes,
321
+ feedback_text=feedback,
322
+ rag_pending=rag_pending
323
+ )
324
+
325
+ logger.info(
326
+ f"[Scoring] Turn {turn_id} | Player {player_id} | Round {round_number} | "
327
+ f"Score={weighted_total:.3f} | "
328
+ f"rel={relevance:.2f} cla={clarity:.2f} rea={reasoning:.2f} "
329
+ f"reb={rebuttal:.2f} evi={evidence:.2f} sta={stance:.2f} pen={penalty:.2f}"
330
+ )
331
+
332
+ return turn_score
333
+
334
+
335
+ def _check_stance_from_nli(response_text: str, player_side: str) -> float:
336
+ from pipeline_d_nli import check_stance_consistency
337
+ return check_stance_consistency(response_text, player_side, "")
338
+
339
+
340
+ def _generate_feedback(
341
+ relevance: float, clarity: float, reasoning: float,
342
+ rebuttal: float, evidence: float, stance: float,
343
+ penalty: float, relations: List[RelationRecord],
344
+ claims: List[ClaimRecord], round_number: int
345
+ ) -> str:
346
+ """Generate structured human-readable feedback for the UI."""
347
+ parts = []
348
+
349
+ if relevance >= 0.75:
350
+ parts.append("✅ Argument is well-aligned with the debate topic.")
351
+ elif relevance < 0.45:
352
+ parts.append("⚠️ Argument drifted somewhat from the core topic.")
353
+
354
+ if clarity >= 0.75:
355
+ parts.append("✅ Argument is clearly structured and easy to follow.")
356
+ elif clarity < 0.45:
357
+ parts.append("💡 Argument could be more clearly organized with better structure.")
358
+
359
+ if reasoning >= 0.70:
360
+ parts.append("✅ Strong reasoning connects claims to your position.")
361
+ elif reasoning < 0.45:
362
+ parts.append("💡 Add reasoning (because/therefore/this shows) to strengthen your argument.")
363
+
364
+ if rebuttal >= 0.65:
365
+ parts.append("✅ Effectively addressed opponent's argument.")
366
+ elif rebuttal < 0.35 and round_number > 1:
367
+ parts.append("⚠️ Did not directly respond to opponent's key claim.")
368
+
369
+ # Evidence feedback
370
+ checkable = [c for c in claims if c.claim_type in (ClaimType.FACTUAL, ClaimType.STATISTICAL)]
371
+ if checkable:
372
+ pending_count = sum(1 for c in checkable if c.verification.verdict == VerificationVerdict.PENDING)
373
+ supported_count = sum(1 for c in checkable if c.verification.verdict == VerificationVerdict.SUPPORTED)
374
+ refuted_count = sum(1 for c in checkable if c.verification.verdict == VerificationVerdict.REFUTED)
375
+
376
+ if pending_count > 0:
377
+ parts.append(f"🔍 Fact-checking {pending_count} claim(s) — evidence score will update.")
378
+ if supported_count > 0:
379
+ parts.append(f"✅ {supported_count} factual claim(s) are evidentially supported.")
380
+ if refuted_count > 0:
381
+ parts.append(f"❌ {refuted_count} factual claim(s) not supported by retrieved evidence.")
382
+
383
+ if stance >= 0.75:
384
+ parts.append("✅ Maintained consistent stance throughout.")
385
+ elif stance < 0.40:
386
+ parts.append("⚠️ Stance may be inconsistent with your assigned side.")
387
+
388
+ if penalty >= 0.08:
389
+ parts.append(f"⚠️ Some arguments were repetitive — try introducing new points.")
390
+
391
+ return " ".join(parts) if parts else "Argument submitted and evaluated."
392
+
393
+
394
+ def aggregate_final_scores(p1_turns: List[TurnScore], p2_turns: List[TurnScore]) -> Tuple[float, float]:
395
+ """
396
+ Aggregate turn scores into final match scores.
397
+ PDF Section 13: "aggregate turn-level results with bounded penalties;
398
+ without allowing one anomalous turn to dominate the entire match."
399
+
400
+ Strategy: weighted average with recency bias (later rounds matter slightly more).
401
+ """
402
+ def weighted_avg(turns: List[TurnScore]) -> float:
403
+ if not turns:
404
+ return 0.0
405
+ # Later rounds (higher round_number) get slightly more weight
406
+ total_weight = 0.0
407
+ total_score = 0.0
408
+ for i, t in enumerate(turns):
409
+ weight = 1.0 + (t.round_number - 1) * 0.1
410
+ total_score += t.weighted_total * weight
411
+ total_weight += weight
412
+ return total_score / total_weight if total_weight > 0 else 0.0
413
+
414
+ p1_total = round(weighted_avg(p1_turns) * 100, 1)
415
+ p2_total = round(weighted_avg(p2_turns) * 100, 1)
416
+
417
+ return p1_total, p2_total
418
+
419
+
420
+ def generate_final_analysis(
421
+ p1_turns: List[TurnScore], p2_turns: List[TurnScore],
422
+ p1_name: str, p2_name: str, winner: str
423
+ ) -> dict:
424
+ """
425
+ Return a rich structured analysis dict for the result page.
426
+ Contains per-category scores, winner strengths, loser mistakes.
427
+ """
428
+ if not p1_turns or not p2_turns:
429
+ return {}
430
+
431
+ def avg(turns, attr):
432
+ return sum(getattr(t, attr) for t in turns) / len(turns)
433
+
434
+ p1 = {
435
+ "relevance": round(avg(p1_turns, "topic_relevance_raw") * 100, 1),
436
+ "clarity": round(avg(p1_turns, "clarity_raw") * 100, 1),
437
+ "reasoning": round(avg(p1_turns, "logical_reasoning_raw") * 100, 1),
438
+ "rebuttal": round(avg(p1_turns, "rebuttal_raw") * 100, 1),
439
+ "evidence": round(avg(p1_turns, "evidence_quality_raw") * 100, 1),
440
+ "stance": round(avg(p1_turns, "stance_consistency_raw") * 100, 1),
441
+ "penalty": round(sum(t.repetition_penalty for t in p1_turns) * 100, 1),
442
+ }
443
+ p2 = {
444
+ "relevance": round(avg(p2_turns, "topic_relevance_raw") * 100, 1),
445
+ "clarity": round(avg(p2_turns, "clarity_raw") * 100, 1),
446
+ "reasoning": round(avg(p2_turns, "logical_reasoning_raw") * 100, 1),
447
+ "rebuttal": round(avg(p2_turns, "rebuttal_raw") * 100, 1),
448
+ "evidence": round(avg(p2_turns, "evidence_quality_raw") * 100, 1),
449
+ "stance": round(avg(p2_turns, "stance_consistency_raw") * 100, 1),
450
+ "penalty": round(sum(t.repetition_penalty for t in p2_turns) * 100, 1),
451
+ }
452
+
453
+ w = p1 if winner == "p1" else p2
454
+ l = p2 if winner == "p1" else p1
455
+ winner_name = p1_name if winner == "p1" else p2_name
456
+ loser_name = p2_name if winner == "p1" else p1_name
457
+ loser_id = "p2" if winner == "p1" else "p1"
458
+
459
+ CATEGORIES = [
460
+ ("rebuttal", "Rebuttal", "They directly contradicted and dismantled opponent claims."),
461
+ ("evidence", "Evidence Quality", "They backed their claims with solid, verifiable facts."),
462
+ ("reasoning", "Logical Reasoning", "They built well-structured logical chains with strong connectors."),
463
+ ("relevance", "Topic Relevance", "Their arguments stayed laser-focused on the debate topic."),
464
+ ("clarity", "Clarity", "Their arguments were clearly structured and easy to follow."),
465
+ ("stance", "Stance Consistency", "They maintained a consistent, coherent position throughout."),
466
+ ]
467
+
468
+ # Winner strengths: categories where winner beat loser by >=8 pts
469
+ strengths = []
470
+ for key, label, desc in CATEGORIES:
471
+ if w[key] - l[key] >= 8:
472
+ strengths.append({"category": label, "winner_score": w[key], "loser_score": l[key], "description": desc})
473
+
474
+ if not strengths:
475
+ best_key = max(CATEGORIES, key=lambda c: w[c[0]])[0]
476
+ best = next(c for c in CATEGORIES if c[0] == best_key)
477
+ strengths.append({"category": best[1], "winner_score": w[best_key], "loser_score": l[best_key], "description": best[2]})
478
+
479
+ # Loser mistakes: categories where loser scored below 45
480
+ mistakes = []
481
+ MISTAKE_DETAILS = {
482
+ "rebuttal": "Failed to directly contradict opponent claims — arguments ran in parallel instead of clashing.",
483
+ "evidence": "Relied on unverified or opinion-based claims without factual backing.",
484
+ "reasoning": "Lacked reasoning connectors (because/therefore/this shows) — claims felt unsupported.",
485
+ "relevance": "Arguments drifted away from the core debate topic.",
486
+ "clarity": "Arguments were too short or lacked clear structure and flow.",
487
+ "stance": "Showed inconsistency in maintaining the assigned debate stance.",
488
+ }
489
+ for key, label, _ in CATEGORIES:
490
+ if l[key] < 45:
491
+ mistakes.append({
492
+ "category": label,
493
+ "score": l[key],
494
+ "gap": round(w[key] - l[key], 1),
495
+ "detail": MISTAKE_DETAILS[key]
496
+ })
497
+
498
+ if l["penalty"] > 8:
499
+ mistakes.append({
500
+ "category": "Repetition Penalty",
501
+ "score": 0,
502
+ "gap": l["penalty"],
503
+ "detail": f"Lost {l['penalty']} points for repeating the same arguments without adding new evidence."
504
+ })
505
+
506
+ if not mistakes:
507
+ mistakes.append({
508
+ "category": "Overall Performance",
509
+ "score": 0,
510
+ "gap": 0,
511
+ "detail": f"Performance was close — {winner_name} maintained a sharper edge across every category."
512
+ })
513
+
514
+ return {
515
+ "winner_name": winner_name,
516
+ "loser_name": loser_name,
517
+ "loser_id": loser_id,
518
+ "p1_breakdown": p1,
519
+ "p2_breakdown": p2,
520
+ "winner_strengths": strengths,
521
+ "loser_mistakes": mistakes,
522
+ }
523
+
frontend/.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
frontend/app.js ADDED
@@ -0,0 +1,1603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Clash of Minds — Frontend Application
3
+ * CSES ML Exhibition | NIT Warangal
4
+ *
5
+ * Implements:
6
+ * - WebSocket live connection to FastAPI backend
7
+ * - Voice input via Web Speech API + transcript confirm flow (PDF Section 5)
8
+ * - Full multi-turn debate UI (PDF Section 4, 13)
9
+ * - Live score updates including RAG evidence updates (PDF Section 14)
10
+ * - Input validation, idempotency guards (PDF Section 15.3)
11
+ * - Exhibition reliability: timer, error handling, operator reset (PDF Section 15)
12
+ */
13
+
14
+ 'use strict';
15
+
16
+ // ─── Config ───────────────────────────────────────────────────────────────────
17
+ // Dynamic host detection: supports cloud deployments (Render, Railway), local Wi-Fi, and localhost
18
+ const HOST = window.location.hostname || 'localhost';
19
+ const PROTOCOL = window.location.protocol === 'file:' ? 'http:' : window.location.protocol;
20
+ const WS_PROTOCOL = PROTOCOL === 'https:' ? 'wss:' : 'ws:';
21
+
22
+ // On cloud deployments (Render, Railway), port is standard 80/443 (empty string).
23
+ // In local development, port 8080 connects to backend on port 8000.
24
+ let portSuffix = '';
25
+ if (window.location.port === '8080') {
26
+ portSuffix = ':8000';
27
+ } else if (window.location.port && window.location.port !== '80' && window.location.port !== '443') {
28
+ portSuffix = `:${window.location.port}`;
29
+ }
30
+
31
+ const API_BASE = `${PROTOCOL}//${HOST}${portSuffix}`;
32
+ const WS_BASE = `${WS_PROTOCOL}//${HOST}${portSuffix}`;
33
+ const TURN_TIME = 120; // seconds per turn (configurable, PDF Section 13)
34
+ const MAX_WORDS = 500;
35
+
36
+ // ─── State ────────────────────────────────────────────────────────────────────
37
+ let matchId = null;
38
+ let reusedMatchId = null;
39
+ let myRole = 'both'; // 'both' (single laptop), 'p1', 'p2', or 'spectator'
40
+ let currentPlayer = 'p1';
41
+ let matchConfig = null; // {p1_name, p2_name, topic, max_rounds}
42
+ let ws = null;
43
+ let timerInterval = null;
44
+ let timerSeconds = TURN_TIME;
45
+ let isSubmitting = false;
46
+ let turnCounter = 0;
47
+
48
+ // Player running totals per criterion (for bar display)
49
+ const playerCriteria = {
50
+ p1: { rebuttal: 0, reasoning: 0, evidence: 0, relevance: 0, clarity: 0, stance: 0 },
51
+ p2: { rebuttal: 0, reasoning: 0, evidence: 0, relevance: 0, clarity: 0, stance: 0 }
52
+ };
53
+
54
+ // Voice state
55
+ let recognition = null;
56
+ let isRecording = false;
57
+ let voiceTranscript = '';
58
+
59
+ // ─── DOM references ───────────────────────────────────────────────────────────
60
+ const $ = id => document.getElementById(id);
61
+ const setupScreen = $('setup-screen');
62
+ const debateScreen = $('debate-screen');
63
+ const finalScreen = $('final-screen');
64
+
65
+ const startBtn = $('start-match-btn');
66
+ const submitBtn = $('submit-btn');
67
+ const voiceBtn = $('voice-btn');
68
+ const voiceConfirm = $('voice-confirm-btn');
69
+ const voiceCancel = $('voice-cancel-btn');
70
+ const textarea = $('argument-textarea');
71
+ const resetBtn = $('reset-btn');
72
+ const newMatchBtn = $('new-match-btn');
73
+ const wordCount = $('word-count');
74
+ const voicePreview = $('voice-preview');
75
+ const voicePreviewText = $('voice-preview-text');
76
+ const analyzingOverlay = $('analyzing-overlay');
77
+ const debateFeed = $('debate-feed');
78
+ const feedEmpty = $('feed-empty');
79
+ const connectionBanner = $('connection-banner');
80
+
81
+
82
+ // ─── Utility ─────────────────────────────────────────────────────────────────
83
+
84
+ function generateTurnId() {
85
+ return 'turn_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8);
86
+ }
87
+
88
+ function countWords(text) {
89
+ return text.trim() ? text.trim().split(/\s+/).length : 0;
90
+ }
91
+
92
+ function showScreen(screenId) {
93
+ ['setup-screen', 'debate-screen', 'final-screen'].forEach(id => {
94
+ const el = $(id);
95
+ el.classList.toggle('active', el.id === screenId);
96
+ });
97
+ // Scroll to top
98
+ window.scrollTo(0, 0);
99
+ }
100
+
101
+
102
+ // ─── Toast notifications ──────────────────────────────────────────────────────
103
+
104
+ function toast(message, type = 'info', duration = 4000) {
105
+ const icons = { info: 'ℹ️', success: '✅', warning: '⚠️', error: '❌' };
106
+ const container = $('toast-container');
107
+ const el = document.createElement('div');
108
+ el.className = `toast ${type}`;
109
+ el.innerHTML = `<span class="toast-icon">${icons[type] || 'ℹ️'}</span><span>${message}</span>`;
110
+ container.appendChild(el);
111
+ setTimeout(() => {
112
+ el.style.opacity = '0';
113
+ el.style.transform = 'translateX(20px)';
114
+ el.style.transition = '0.3s ease';
115
+ setTimeout(() => el.remove(), 300);
116
+ }, duration);
117
+ }
118
+
119
+
120
+ // ─── WebSocket connection ─────────────────────────────────────────────────────
121
+
122
+ function connectWebSocket(mId) {
123
+ if (ws) ws.close();
124
+ ws = new WebSocket(`${WS_BASE}/ws/${mId}`);
125
+
126
+ ws.addEventListener('open', () => {
127
+ connectionBanner.classList.remove('offline');
128
+ updateServerStatus(true);
129
+ });
130
+
131
+ ws.addEventListener('message', e => {
132
+ // Ignore plain-text keepalive frames (e.g. "pong")
133
+ if (typeof e.data === 'string' && !e.data.startsWith('{')) return;
134
+ try {
135
+ const data = JSON.parse(e.data);
136
+ handleServerMessage(data);
137
+ } catch (err) {
138
+ console.warn('WS parse error (ignored):', err);
139
+ }
140
+ });
141
+
142
+ ws.addEventListener('close', () => {
143
+ connectionBanner.classList.add('offline');
144
+ updateServerStatus(false);
145
+ // Auto-reconnect (PDF Section 15.4)
146
+ setTimeout(() => {
147
+ if (matchId) connectWebSocket(matchId);
148
+ }, 3000);
149
+ });
150
+
151
+ ws.addEventListener('error', () => {
152
+ connectionBanner.classList.add('offline');
153
+ updateServerStatus(false);
154
+ });
155
+
156
+ // Keepalive ping
157
+ setInterval(() => {
158
+ if (ws && ws.readyState === WebSocket.OPEN) {
159
+ ws.send('ping');
160
+ }
161
+ }, 25000);
162
+ }
163
+
164
+
165
+ function handleServerMessage(data) {
166
+ switch (data.type) {
167
+ case 'connected':
168
+ console.log('[WS] Connected to match:', data.match_id);
169
+ break;
170
+
171
+ case 'turn_result':
172
+ handleTurnResult(data);
173
+ break;
174
+
175
+ case 'evidence_update':
176
+ // RAG background update (PDF Section 14)
177
+ handleEvidenceUpdate(data);
178
+ break;
179
+
180
+ case 'turn_evaluating':
181
+ // Broadcast from backend when an argument is being evaluated
182
+ if (!isSubmitting) {
183
+ showAnalyzingOverlay();
184
+ const pName = data.player_name || (data.player_id === 'p1' ? 'Player 1' : 'Player 2');
185
+ const overlayText = $('analyzing-tagline');
186
+ if (overlayText) overlayText.textContent = `Analyzing ${pName}'s argument through AI pipelines...`;
187
+ }
188
+ break;
189
+
190
+ case 'match_restarted':
191
+ toast(`🔄 New debate starting: "${data.topic}"`, 'info', 5000);
192
+ matchId = data.match_id;
193
+ matchConfig = {
194
+ p1Name: data.p1.name,
195
+ p2Name: data.p2.name,
196
+ topic: data.topic,
197
+ maxRounds: data.max_rounds
198
+ };
199
+ currentPlayer = 'p1';
200
+ initDebateUI(data);
201
+ showScreen('debate-screen');
202
+ startTimer();
203
+ break;
204
+
205
+ case 'match_reset':
206
+ toast('Match has been reset by the operator.', 'warning');
207
+ goToSetup();
208
+ break;
209
+
210
+ default:
211
+ console.log('[WS] Unknown message type:', data.type);
212
+ }
213
+ }
214
+
215
+
216
+ // ─── Server status ────────────────────────────────────────────────────────────
217
+
218
+ let serverLanIp = '10.126.165.227';
219
+
220
+ async function checkServerStatus() {
221
+ try {
222
+ const r = await fetch(`${API_BASE}/api/health`, { signal: AbortSignal.timeout(3000) });
223
+ if (r.ok) {
224
+ const data = await r.json();
225
+ if (data.lan_ip) {
226
+ serverLanIp = data.lan_ip;
227
+ }
228
+ updateServerStatus(true);
229
+ return true;
230
+ }
231
+ } catch (_) { }
232
+ updateServerStatus(false);
233
+ return false;
234
+ }
235
+
236
+ function updateServerStatus(online) {
237
+ const dot = $('server-status-dot');
238
+ const text = $('server-status-text');
239
+ if (online) {
240
+ dot.style.background = 'var(--accent-green)';
241
+ text.textContent = 'Backend Online';
242
+ } else {
243
+ dot.style.background = 'var(--accent-red)';
244
+ text.textContent = 'Backend Offline';
245
+ }
246
+ }
247
+
248
+
249
+ // ─── Match setup ──────────────────────────────────────────────────────────────
250
+
251
+ startBtn.addEventListener('click', async () => {
252
+ const p1Name = $('p1-name').value.trim();
253
+ const p2Name = $('p2-name').value.trim();
254
+ const topic = $('topic-input').value.trim();
255
+ const rounds = parseInt($('max-rounds').value);
256
+
257
+ if (!p1Name || !p2Name) {
258
+ toast('Please enter names for both players.', 'error');
259
+ return;
260
+ }
261
+ if (!topic) {
262
+ toast('Please enter a debate topic.', 'error');
263
+ return;
264
+ }
265
+
266
+ // Get selected device mode
267
+ const roleRadio = document.querySelector('input[name="host-device-role"]:checked');
268
+ myRole = roleRadio ? roleRadio.value : 'p1';
269
+
270
+ startBtn.disabled = true;
271
+ startBtn.textContent = 'Starting...';
272
+
273
+ try {
274
+ const payload = {
275
+ p1_name: p1Name,
276
+ p2_name: p2Name,
277
+ topic,
278
+ max_rounds: rounds
279
+ };
280
+ if (reusedMatchId) {
281
+ payload.match_id = reusedMatchId;
282
+ }
283
+
284
+ const res = await fetch(`${API_BASE}/api/match/start`, {
285
+ method: 'POST',
286
+ headers: { 'Content-Type': 'application/json' },
287
+ body: JSON.stringify(payload)
288
+ });
289
+
290
+ if (!res.ok) {
291
+ const err = await res.json();
292
+ throw new Error(err.detail || 'Failed to start match');
293
+ }
294
+
295
+ const data = await res.json();
296
+ matchId = data.match_id;
297
+ reusedMatchId = null;
298
+ const banner = $('reusing-room-banner');
299
+ if (banner) banner.style.display = 'none';
300
+
301
+ matchConfig = { p1Name, p2Name, topic, maxRounds: rounds };
302
+ currentPlayer = 'p1';
303
+
304
+ // Connect WebSocket
305
+ connectWebSocket(matchId);
306
+
307
+ // Initialize debate UI
308
+ initDebateUI(data);
309
+ showScreen('debate-screen');
310
+ startTimer();
311
+
312
+ toast(`Match started! Room: ${matchId}`, 'success');
313
+
314
+ } catch (err) {
315
+ toast(`Error: ${err.message}`, 'error');
316
+ console.error(err);
317
+ } finally {
318
+ startBtn.disabled = false;
319
+ startBtn.innerHTML = '<span class="btn-icon">⚡</span> Start Debate';
320
+ }
321
+ });
322
+
323
+
324
+ // ─── Multi-Device Role & Permission Helpers ────────────────────────────────────
325
+
326
+ function isMyTurn() {
327
+ if (myRole === 'spectator') return false;
328
+ if (myRole === 'both') return true;
329
+ return myRole === currentPlayer;
330
+ }
331
+
332
+ function updateRoleDisplay() {
333
+ const badge = $('device-role-badge');
334
+ if (!badge) return;
335
+ const roleLabels = {
336
+ 'both': '💻 Single Laptop',
337
+ 'p1': '⚡ Role: Player 1 (FOR)',
338
+ 'p2': '🛡️ Role: Player 2 (AGAINST)',
339
+ 'spectator': '📺 Role: Spectator'
340
+ };
341
+ badge.textContent = roleLabels[myRole] || myRole;
342
+ }
343
+
344
+
345
+ // ─── Debate UI initialization ─────────────────────────────────────────────────
346
+
347
+ function initDebateUI(data) {
348
+ const p1Name = data.p1 ? data.p1.name : (data.players && data.players.p1 ? data.players.p1.name : 'Player 1');
349
+ const p2Name = data.p2 ? data.p2.name : (data.players && data.players.p2 ? data.players.p2.name : 'Player 2');
350
+ const rounds = data.max_rounds || 4;
351
+ const curRound = data.current_round || 1;
352
+ const curPlayer = data.current_player || 'p1';
353
+ currentPlayer = curPlayer;
354
+
355
+ // Header
356
+ $('header-topic').textContent = data.topic;
357
+ $('p1-name-header').textContent = p1Name;
358
+ $('p2-name-header').textContent = p2Name;
359
+ $('p1-avatar-header').textContent = p1Name ? p1Name[0].toUpperCase() : 'P1';
360
+ $('p2-avatar-header').textContent = p2Name ? p2Name[0].toUpperCase() : 'P2';
361
+ $('p1-panel-name').textContent = p1Name;
362
+
363
+ const p1Total = data.p1 && data.p1.total_score != null ? data.p1.total_score : 0.0;
364
+ const p2Total = data.p2 && data.p2.total_score != null ? data.p2.total_score : 0.0;
365
+ $('p1-score-header').textContent = p1Total.toFixed(1);
366
+ $('p2-score-header').textContent = p2Total.toFixed(1);
367
+ $('p1-total-score').textContent = p1Total.toFixed(1);
368
+
369
+ // Room ID and Role Badges
370
+ const roomText = $('room-id-text');
371
+ if (roomText) roomText.textContent = data.match_id || matchId;
372
+ updateRoleDisplay();
373
+
374
+ // Round dots
375
+ buildRoundDots(rounds, curRound);
376
+ $('round-label').textContent = `Round ${curRound} / ${rounds}`;
377
+
378
+ // Turn indicator
379
+ const curName = curPlayer === 'p1' ? p1Name : p2Name;
380
+ const side = curPlayer === 'p1' ? 'FOR' : 'AGAINST';
381
+ const instruction = curRound === 1
382
+ ? `Opening argument — ${side} the proposition`
383
+ : `Round ${curRound} rebuttal — respond to opponent's arguments`;
384
+ updateTurnIndicator(curPlayer, curName, instruction);
385
+
386
+ // Clear feed
387
+ debateFeed.innerHTML = '';
388
+ debateFeed.appendChild(feedEmpty);
389
+ feedEmpty.style.display = '';
390
+
391
+ // Clear turn histories
392
+ $('p1-turn-history').innerHTML = '';
393
+
394
+ // Clear analysis panel
395
+ $('no-analysis-msg').style.display = '';
396
+ $('criterion-section').style.display = 'none';
397
+ $('feedback-section').style.display = 'none';
398
+ $('claims-section').style.display = 'none';
399
+ $('relations-section').style.display = 'none';
400
+ $('factcheck-section').style.display = 'none';
401
+
402
+ // Enable/disable input according to device role
403
+ enableInput();
404
+ turnCounter = 0;
405
+ }
406
+
407
+
408
+ function buildRoundDots(maxRounds, currentRound) {
409
+ const container = $('round-dots');
410
+ container.innerHTML = '';
411
+ for (let i = 1; i <= maxRounds; i++) {
412
+ const dot = document.createElement('div');
413
+ dot.className = 'round-dot' + (i === currentRound ? ' active' : (i < currentRound ? ' done' : ''));
414
+ dot.setAttribute('aria-label', `Round ${i}${i === currentRound ? ' (current)' : ''}`);
415
+ container.appendChild(dot);
416
+ }
417
+ }
418
+
419
+
420
+ function updateTurnIndicator(playerId, playerName, instruction) {
421
+ const avatar = $('current-avatar');
422
+ avatar.className = `turn-avatar ${playerId}`;
423
+ avatar.textContent = playerName ? playerName[0].toUpperCase() : 'P';
424
+
425
+ if (myRole === 'spectator') {
426
+ $('current-player-name').textContent = `${playerName}'s Turn (${playerId === 'p1' ? 'FOR' : 'AGAINST'})`;
427
+ } else if (myRole === 'both') {
428
+ $('current-player-name').textContent = `${playerName}'s Turn`;
429
+ } else if (myRole === playerId) {
430
+ $('current-player-name').textContent = `👉 YOUR TURN (${playerName})`;
431
+ } else {
432
+ $('current-player-name').textContent = `⏳ ${playerName}'s Turn (Opponent)`;
433
+ }
434
+
435
+ $('turn-instruction').textContent = instruction;
436
+ }
437
+
438
+
439
+ // ─── Argument submission ──────────────────────────────────────────────────────
440
+
441
+ async function sendTurnSubmission(text, inputMethod = 'text') {
442
+ if (isSubmitting) return;
443
+
444
+ isSubmitting = true;
445
+ disableInput();
446
+ stopTimer();
447
+ showAnalyzingOverlay();
448
+
449
+ const turnId = generateTurnId();
450
+
451
+ try {
452
+ const res = await fetch(`${API_BASE}/api/match/submit`, {
453
+ method: 'POST',
454
+ headers: { 'Content-Type': 'application/json' },
455
+ body: JSON.stringify({
456
+ match_id: matchId,
457
+ player_id: currentPlayer,
458
+ turn_id: turnId,
459
+ text,
460
+ input_method: inputMethod
461
+ })
462
+ });
463
+
464
+ if (!res.ok) {
465
+ const err = await res.json();
466
+ throw new Error(err.detail || 'Submission failed');
467
+ }
468
+
469
+ // Response will also come via WebSocket; REST response is the same data
470
+ const data = await res.json();
471
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
472
+ handleTurnResult(data);
473
+ }
474
+
475
+ // Clear textarea
476
+ textarea.value = '';
477
+ updateWordCount();
478
+ voiceTranscript = '';
479
+ hideVoicePreview();
480
+
481
+ } catch (err) {
482
+ toast(`Submission error: ${err.message}`, 'error');
483
+ console.error(err);
484
+ } finally {
485
+ isSubmitting = false;
486
+ hideAnalyzingOverlay();
487
+ }
488
+ }
489
+
490
+ submitBtn.addEventListener('click', async () => {
491
+ if (isSubmitting || !isMyTurn()) return; // idempotency and role guard
492
+
493
+ const text = textarea.value.trim();
494
+ if (!text) {
495
+ toast('Please enter your argument.', 'warning');
496
+ return;
497
+ }
498
+ if (countWords(text) < 5) {
499
+ toast('Argument is too short (minimum 5 words).', 'warning');
500
+ return;
501
+ }
502
+
503
+ await sendTurnSubmission(text, voiceTranscript ? 'voice' : 'text');
504
+ });
505
+
506
+ async function autoSubmitOnTimeout() {
507
+ if (isSubmitting) return;
508
+
509
+ // Only the active debater's device auto-submits to avoid duplicate calls
510
+ if (!isMyTurn()) {
511
+ stopTimer();
512
+ return;
513
+ }
514
+
515
+ // If voice recording is actively running, stop it and grab transcript
516
+ if (isRecording) {
517
+ if (recognition) {
518
+ try { recognition.stop(); } catch (_) { }
519
+ }
520
+ setVoiceState(false);
521
+ }
522
+
523
+ let text = textarea.value.trim();
524
+ if (!text && voiceTranscript) {
525
+ text = voiceTranscript.trim();
526
+ }
527
+
528
+ if (!text) {
529
+ text = "[Time expired: No argument presented by participant.]";
530
+ toast('⏱ Time is up! Turn expired and passed to opponent.', 'warning', 4000);
531
+ } else {
532
+ toast('⏱ Time is up! Argument auto-submitted.', 'info', 4000);
533
+ }
534
+
535
+ await sendTurnSubmission(text, voiceTranscript ? 'voice' : 'text');
536
+ }
537
+
538
+
539
+ // ─── Turn result handler ──────────────────────────────────────────────────────
540
+
541
+ function handleTurnResult(data) {
542
+ hideAnalyzingOverlay();
543
+ isSubmitting = false;
544
+
545
+ const pid = data.player_id;
546
+ const pName = data.player_name;
547
+
548
+ // Add argument bubble to feed
549
+ addDebateBubble(pid, pName, data);
550
+
551
+ // Update score bars and totals
552
+ updatePlayerScores(pid, data.score);
553
+
554
+ // Update analysis panel
555
+ updateAnalysisPanel(data);
556
+
557
+ // Update turn history
558
+ addTurnHistoryEntry(pid, data);
559
+
560
+ // Update round / header
561
+ if (data.next_round) {
562
+ buildRoundDots(matchConfig.maxRounds, data.next_round);
563
+ $('round-label').textContent = `Round ${data.next_round} / ${matchConfig.maxRounds}`;
564
+ }
565
+
566
+ if (data.debate_over) {
567
+ stopTimer();
568
+ disableInput();
569
+ setTimeout(() => showFinalScreen(data), 1800);
570
+ return;
571
+ }
572
+
573
+ // Advance to next player
574
+ currentPlayer = data.next_player || (pid === 'p1' ? 'p2' : 'p1');
575
+ const nextName = matchConfig[`${currentPlayer === 'p1' ? 'p1' : 'p2'}Name`];
576
+ const round = data.next_round || 1;
577
+ const side = currentPlayer === 'p1' ? 'FOR' : 'AGAINST';
578
+ const instruction = round === 1
579
+ ? `Opening argument — ${side} the proposition`
580
+ : `Round ${round} rebuttal — respond to opponent's arguments`;
581
+
582
+ updateTurnIndicator(currentPlayer, nextName, instruction);
583
+ enableInput();
584
+ startTimer();
585
+
586
+ toast(`${nextName}'s turn (Round ${round})`, 'info', 2500);
587
+ }
588
+
589
+
590
+ // ─── Evidence update from background RAG ─────────────────────────────────────
591
+
592
+ function handleEvidenceUpdate(data) {
593
+ // Update the fact-check display in the analysis panel
594
+ const factList = $('fact-check-list');
595
+ if (!factList) return;
596
+
597
+ // Find existing entry for this claim or add a new one
598
+ const existingId = `fact-claim-${data.claim_id}`;
599
+ let el = document.getElementById(existingId);
600
+
601
+ const verdictClass = data.verdict.toLowerCase();
602
+ const verdictEmoji = {
603
+ supported: '✅', partially_supported: '🟡', refuted: '❌',
604
+ insufficient_evidence: '❓', ambiguous: '⚠️', pending: '🔄'
605
+ }[verdictClass] || '❓';
606
+
607
+ const html = `
608
+ <div class="fact-verdict">${verdictEmoji} ${data.verdict.replace(/_/g, ' ')}</div>
609
+ <div class="fact-text">${escapeHtml(data.claim_text)}${data.conflicting ? ' <em>(conflicting sources)</em>' : ''}</div>
610
+ `;
611
+
612
+ if (el) {
613
+ el.className = `fact-item ${verdictClass}`;
614
+ el.innerHTML = html;
615
+ } else {
616
+ el = document.createElement('div');
617
+ el.id = existingId;
618
+ el.className = `fact-item ${verdictClass}`;
619
+ el.innerHTML = html;
620
+ factList.appendChild(el);
621
+ $('factcheck-section').style.display = '';
622
+ }
623
+
624
+ // Update any pending chips on debate bubbles
625
+ const pendingChip = document.querySelector(`[data-claim-id="${data.claim_id}"].rag-pending-chip`);
626
+ if (pendingChip && data.verdict !== 'PENDING') {
627
+ pendingChip.remove();
628
+ toast(`Fact-check updated: ${data.verdict.replace(/_/g, ' ')} for "${data.claim_text.slice(0, 40)}..."`, 'info');
629
+ }
630
+ }
631
+
632
+
633
+ // ─── Debate feed bubbles ──────────────────────────────────────────────────────
634
+
635
+ function addDebateBubble(playerId, playerName, data) {
636
+ if (feedEmpty && feedEmpty.parentNode) feedEmpty.remove();
637
+
638
+ const bubble = document.createElement('div');
639
+ bubble.className = `argument-bubble ${playerId}`;
640
+ bubble.setAttribute('role', 'article');
641
+ bubble.setAttribute('aria-label', `${playerName}'s argument`);
642
+
643
+ const score = data.score;
644
+ const ragPending = score.rag_pending;
645
+
646
+ // Claim type chips
647
+ const claimChipsHtml = (data.claims || []).map(c =>
648
+ `<span class="claim-chip ${c.type}" title="${c.text.slice(0, 60)}...">${c.type}</span>`
649
+ ).join('');
650
+
651
+ // Relation brief — summarize NLI logical relations cleanly
652
+ let relSummary = '';
653
+ if (data.relations && data.relations.length > 0) {
654
+ const counts = {};
655
+ data.relations.forEach(r => {
656
+ const rel = (r.relation || '').toLowerCase();
657
+ counts[rel] = (counts[rel] || 0) + 1;
658
+ });
659
+
660
+ const badges = [];
661
+ if (counts['contradict']) {
662
+ badges.push(`<span style="color:#f43f5e; font-weight:600;" title="Direct clash / counter-argument">⚔️ ${counts['contradict']} Rebuttal${counts['contradict'] > 1 ? 's' : ''}</span>`);
663
+ }
664
+ if (counts['qualify']) {
665
+ badges.push(`<span style="color:#f59e0b; font-weight:600;" title="Nuanced / partial counter">⚖️ ${counts['qualify']} Nuance</span>`);
666
+ }
667
+ if (counts['support'] || counts['agree']) {
668
+ const c = (counts['support'] || 0) + (counts['agree'] || 0);
669
+ badges.push(`<span style="color:#10b981; font-weight:600;" title="Concession or agreement">🤝 ${c} Concession</span>`);
670
+ }
671
+ if (counts['elaborate']) {
672
+ badges.push(`<span style="color:#06b6d4; font-weight:600;" title="Deepens evidence on point">💡 ${counts['elaborate']} Elaboration</span>`);
673
+ }
674
+ if (counts['unrelated']) {
675
+ badges.push(`<span style="color:var(--text-muted);" title="Independent point / fresh subtopic">📝 ${counts['unrelated']} Fresh Point${counts['unrelated'] > 1 ? 's' : ''}</span>`);
676
+ }
677
+
678
+ relSummary = `<div style="display:inline-flex; align-items:center; gap:6px; font-size:11px; margin-left:auto; flex-wrap:wrap;">${badges.join('<span style="opacity:0.3">·</span>')}</div>`;
679
+ }
680
+
681
+ const argumentContent = data.text || data.turn_log_text || textarea.value || '';
682
+
683
+ bubble.innerHTML = `
684
+ <div class="bubble-header">
685
+ <span>${playerName}</span>
686
+ <span style="opacity:0.5">·</span>
687
+ <span>${playerId === 'p1' ? '🟦 FOR' : '🟥 AGAINST'}</span>
688
+ <span style="opacity:0.5; margin-left:auto">Round ${data.round_number}</span>
689
+ </div>
690
+ <div class="bubble-text">${escapeHtml(argumentContent).replace(/\n/g, '<br/>')}</div>
691
+ ${claimChipsHtml ? `<div class="claim-chips" style="margin-top:8px">${claimChipsHtml}</div>` : ''}
692
+ <div class="bubble-score">
693
+ <span class="bubble-score-num">${score.weighted_total.toFixed(1)}</span>
694
+ <span style="font-size:11px; color:var(--text-muted)">/ 100</span>
695
+ ${ragPending ? `<span class="rag-pending-chip" data-claim-id="pending">🔍 Fact-check pending</span>` : ''}
696
+ ${relSummary}
697
+ </div>
698
+ `;
699
+
700
+ debateFeed.appendChild(bubble);
701
+ debateFeed.scrollTop = debateFeed.scrollHeight;
702
+ }
703
+
704
+
705
+ function addTurnHistoryEntry(playerId, data) {
706
+ const histId = playerId === 'p1' ? 'p1-turn-history' : 'p1-turn-history';
707
+ // Both histories in respective panels (p2 panel has its own turn history)
708
+ const hist = $(playerId + '-turn-history') || $('p1-turn-history');
709
+
710
+ const entry = document.createElement('div');
711
+ entry.className = `turn-entry ${playerId}`;
712
+ entry.innerHTML = `
713
+ <div class="turn-entry-score">Round ${data.round_number} · ${data.score.weighted_total.toFixed(1)} pts</div>
714
+ <div>${data.feedback ? data.feedback.slice(0, 80) + '...' : 'Turn evaluated.'}</div>
715
+ `;
716
+ if (hist) hist.appendChild(entry);
717
+ }
718
+
719
+
720
+ // ─── Analysis panel updates ───────────────────────────────────────────────────
721
+
722
+ function updatePlayerScores(playerId, score) {
723
+ const prefix = playerId;
724
+
725
+ // Running averages (average of last turn for bars; total for scoreboard)
726
+ const crit = playerCriteria[playerId];
727
+ const turns = playerId === 'p1'
728
+ ? ($('p1-turn-history').children.length + 1)
729
+ : ($('p1-turn-history').children.length); // simplified
730
+
731
+ // Update bars (use last turn value for immediate feedback)
732
+ const fields = [
733
+ ['rebuttal', score.rebuttal],
734
+ ['reasoning', score.logical_reasoning],
735
+ ['evidence', score.evidence_quality],
736
+ ['relevance', score.topic_relevance],
737
+ ['clarity', score.clarity],
738
+ ['stance', score.stance_consistency]
739
+ ];
740
+
741
+ fields.forEach(([key, val]) => {
742
+ const bar = $(`${prefix}-${key}-bar`);
743
+ const valEl = $(`${prefix}-${key}-val`);
744
+ if (bar) bar.style.width = val + '%';
745
+ if (valEl) valEl.textContent = val.toFixed(1);
746
+ });
747
+
748
+ // Update total score
749
+ const total = score.weighted_total;
750
+ $(`${prefix}-total-score`) && ($(`${prefix}-total-score`).textContent = total.toFixed(1));
751
+ $(`${prefix}-score-header`) && ($(`${prefix}-score-header`).textContent = total.toFixed(1));
752
+ }
753
+
754
+
755
+ function updateAnalysisPanel(data) {
756
+ const score = data.score;
757
+ $('no-analysis-msg').style.display = 'none';
758
+
759
+ // Criterion breakdown
760
+ $('criterion-section').style.display = '';
761
+ const criteriaMap = {
762
+ 'cr-rebuttal': score.rebuttal,
763
+ 'cr-reasoning': score.logical_reasoning,
764
+ 'cr-evidence': score.evidence_quality,
765
+ 'cr-relevance': score.topic_relevance,
766
+ 'cr-clarity': score.clarity,
767
+ 'cr-stance': score.stance_consistency,
768
+ };
769
+ const barMap = {
770
+ 'crb-rebuttal': score.rebuttal,
771
+ 'crb-reasoning': score.logical_reasoning,
772
+ 'crb-evidence': score.evidence_quality,
773
+ 'crb-relevance': score.topic_relevance,
774
+ 'crb-clarity': score.clarity,
775
+ 'crb-stance': score.stance_consistency,
776
+ };
777
+ Object.entries(criteriaMap).forEach(([id, val]) => {
778
+ const el = $(id);
779
+ if (el) el.textContent = val ? val.toFixed(1) + '%' : '—';
780
+ });
781
+ Object.entries(barMap).forEach(([id, val]) => {
782
+ const el = $(id);
783
+ if (el) el.style.width = (val || 0) + '%';
784
+ });
785
+
786
+ // Feedback
787
+ if (data.feedback) {
788
+ $('feedback-section').style.display = '';
789
+ $('feedback-text').textContent = data.feedback;
790
+ }
791
+
792
+ // Claim chips
793
+ if (data.claims && data.claims.length > 0) {
794
+ $('claims-section').style.display = '';
795
+ $('claims-chips').innerHTML = data.claims.map(c =>
796
+ `<span class="claim-chip ${c.type}" title="${escapeHtml(c.text.slice(0, 80))}">${c.type}</span>`
797
+ ).join('');
798
+ }
799
+
800
+ // Relations (NLI)
801
+ if (data.relations && data.relations.length > 0) {
802
+ $('relations-section').style.display = '';
803
+ $('relation-list').innerHTML = data.relations.map(r => `
804
+ <div class="relation-tag" title="${escapeHtml(r.hint)}">
805
+ <span class="relation-label ${r.relation}">${r.relation}</span>
806
+ <span class="relation-hint">${escapeHtml(r.hint || '')}</span>
807
+ <span style="font-size:10px; color:var(--text-muted);">${(r.score * 100).toFixed(0)}%</span>
808
+ </div>
809
+ `).join('');
810
+ }
811
+
812
+ // Fact-check (initial state — will be updated by RAG events)
813
+ const checkableClaims = (data.claims || []).filter(c =>
814
+ c.type === 'factual' || c.type === 'statistical'
815
+ );
816
+ if (checkableClaims.length > 0) {
817
+ $('factcheck-section').style.display = '';
818
+ const factList = $('fact-check-list');
819
+ factList.innerHTML = checkableClaims.map(c => `
820
+ <div class="fact-item ${c.verification === 'PENDING' ? 'pending' : c.verification.toLowerCase()}"
821
+ id="fact-claim-${c.id}">
822
+ <div class="fact-verdict">🔄 ${c.verification.replace(/_/g, ' ')}</div>
823
+ <div class="fact-text" style="word-wrap: break-word; white-space: normal;">${escapeHtml(c.text)}</div>
824
+ </div>
825
+ `).join('');
826
+ }
827
+ }
828
+
829
+
830
+
831
+ function showFinalScreen(data) {
832
+ const winner = data.winner;
833
+ const winnerName = data.winner_name;
834
+ const p1Score = data.scores.p1.total;
835
+ const p2Score = data.scores.p2.total;
836
+
837
+ // Winner display
838
+ $('winner-name-display').textContent = winnerName;
839
+ $('winner-name-display').className = 'winner-name ' + (winner === 'p1' ? 'p1-win' : 'p2-win');
840
+ $('winner-side-display').textContent = winner === 'p1' ? 'FOR the proposition' : 'AGAINST the proposition';
841
+
842
+ // Final scoreboard
843
+ $('p1-name-final').textContent = matchConfig.p1Name;
844
+ $('p2-name-final').textContent = matchConfig.p2Name;
845
+ $('p1-score-final').textContent = p1Score.toFixed(1);
846
+ $('p2-score-final').textContent = p2Score.toFixed(1);
847
+ $('final-topic').textContent = matchConfig.topic;
848
+
849
+ // Crown & glow
850
+ if (winner === 'p1') {
851
+ $('p1-final-card').classList.add('winner');
852
+ $('p1-crown').style.display = '';
853
+ } else {
854
+ $('p2-final-card').classList.add('winner', 'p2-win');
855
+ $('p2-crown').style.display = '';
856
+ }
857
+
858
+ // ── Final Analysis Cards ──────────────────────────────────────────────────
859
+ const analysis = data.final_analysis;
860
+ if (analysis && analysis.winner_strengths) {
861
+ // Remove any previous analysis
862
+ const old = document.getElementById('final-analysis-section');
863
+ if (old) old.remove();
864
+
865
+ const container = document.querySelector('#final-screen > div');
866
+
867
+ const section = document.createElement('div');
868
+ section.id = 'final-analysis-section';
869
+ section.style.cssText = 'width:100%;max-width:700px;margin:0 auto 2rem;display:flex;flex-direction:column;gap:1.2rem;';
870
+
871
+ // ── Winner Strengths ──
872
+ const strengthsHtml = analysis.winner_strengths.map(s => `
873
+ <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;background:rgba(16,185,129,0.06);border-radius:8px;border-left:3px solid var(--accent-green);">
874
+ <div>
875
+ <div style="font-weight:700;font-size:0.9rem;color:var(--accent-green);">${s.category}</div>
876
+ <div style="font-size:0.82rem;color:var(--text-secondary);margin-top:2px;">${s.description}</div>
877
+ </div>
878
+ <div style="text-align:right;min-width:90px;margin-left:12px;">
879
+ <span style="font-size:1.1rem;font-weight:800;color:var(--accent-green);">${s.winner_score}</span>
880
+ <span style="font-size:0.75rem;color:var(--text-muted);"> vs ${s.loser_score}</span>
881
+ </div>
882
+ </div>`).join('');
883
+
884
+ // ── Loser Mistakes ──
885
+ const mistakesHtml = analysis.loser_mistakes.map(m => `
886
+ <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;background:rgba(244,63,94,0.06);border-radius:8px;border-left:3px solid var(--accent-red);">
887
+ <div style="flex:1;">
888
+ <div style="font-weight:700;font-size:0.9rem;color:var(--accent-red);">${m.category}${m.score > 0 ? ` — ${m.score} pts` : ''}</div>
889
+ <div style="font-size:0.82rem;color:var(--text-secondary);margin-top:2px;">${m.detail}</div>
890
+ </div>
891
+ ${m.gap > 0 ? `<div style="min-width:70px;text-align:right;margin-left:12px;font-size:0.82rem;color:var(--accent-red);">-${m.gap} pts gap</div>` : ''}
892
+ </div>`).join('');
893
+
894
+ section.innerHTML = `
895
+ <div style="padding:1.2rem;background:rgba(255,255,255,0.03);border-radius:14px;border:1px solid rgba(255,255,255,0.08);">
896
+ <div style="font-size:0.72rem;text-transform:uppercase;letter-spacing:.1em;color:var(--accent-green);margin-bottom:12px;font-weight:700;">
897
+ 🏆 Why ${analysis.winner_name} Won
898
+ </div>
899
+ <div style="display:flex;flex-direction:column;gap:8px;">${strengthsHtml}</div>
900
+ </div>
901
+ <div style="padding:1.2rem;background:rgba(255,255,255,0.03);border-radius:14px;border:1px solid rgba(255,255,255,0.08);">
902
+ <div style="font-size:0.72rem;text-transform:uppercase;letter-spacing:.1em;color:var(--accent-red);margin-bottom:12px;font-weight:700;">
903
+ 📉 Where ${analysis.loser_name} Fell Short
904
+ </div>
905
+ <div style="display:flex;flex-direction:column;gap:8px;">${mistakesHtml}</div>
906
+ </div>`;
907
+
908
+ // Insert before the New Match button div
909
+ const actionsDiv = container.querySelector('.final-actions');
910
+ if (actionsDiv) {
911
+ container.insertBefore(section, actionsDiv);
912
+ } else {
913
+ container.appendChild(section);
914
+ }
915
+ }
916
+
917
+ stopTimer();
918
+ const reuseLabel = $('reuse-room-code-label');
919
+ if (reuseLabel) reuseLabel.textContent = matchId || '------';
920
+
921
+ showScreen('final-screen');
922
+ launchConfetti(winner);
923
+ toast(`🏆 ${winnerName} wins the debate!`, 'success', 6000);
924
+ }
925
+
926
+
927
+ // ─── Timer ────────────────────────────────────────────────────────────────────
928
+
929
+ function startTimer() {
930
+ stopTimer();
931
+ timerSeconds = TURN_TIME;
932
+ updateTimerDisplay();
933
+
934
+ timerInterval = setInterval(() => {
935
+ // Guard: only tick down when debate screen is actively shown
936
+ if (!debateScreen || !debateScreen.classList.contains('active')) {
937
+ stopTimer();
938
+ return;
939
+ }
940
+
941
+ timerSeconds--;
942
+ updateTimerDisplay();
943
+
944
+ if (timerSeconds <= 0) {
945
+ stopTimer();
946
+ if (debateScreen && debateScreen.classList.contains('active')) {
947
+ autoSubmitOnTimeout();
948
+ }
949
+ }
950
+ }, 1000);
951
+ }
952
+
953
+ function stopTimer() {
954
+ if (timerInterval) {
955
+ clearInterval(timerInterval);
956
+ timerInterval = null;
957
+ }
958
+ }
959
+
960
+ function updateTimerDisplay() {
961
+ const min = Math.floor(timerSeconds / 60);
962
+ const sec = timerSeconds % 60;
963
+ $('timer-display').textContent = `${min}:${sec.toString().padStart(2, '0')}`;
964
+
965
+ // Update SVG ring
966
+ const circle = $('timer-progress-circle');
967
+ if (circle) {
968
+ const radius = 22;
969
+ const circumference = 2 * Math.PI * radius; // ~138.2
970
+ const fraction = timerSeconds / TURN_TIME;
971
+ const offset = circumference * (1 - fraction);
972
+ circle.style.strokeDashoffset = offset;
973
+
974
+ // Color shift when time is low
975
+ if (timerSeconds <= 20) {
976
+ circle.style.stroke = 'var(--accent-red)';
977
+ $('timer-display').style.color = 'var(--accent-red)';
978
+ } else if (timerSeconds <= 45) {
979
+ circle.style.stroke = 'var(--accent-amber)';
980
+ $('timer-display').style.color = 'var(--accent-amber)';
981
+ } else {
982
+ circle.style.stroke = 'var(--accent-cyan)';
983
+ $('timer-display').style.color = 'var(--accent-cyan)';
984
+ }
985
+ }
986
+ }
987
+
988
+
989
+ // ─── Input helpers ────────────────────────────────────────────────────────────
990
+
991
+ function enableInput() {
992
+ const area = $('input-area');
993
+ const waitingBanner = $('turn-waiting-banner');
994
+ const waitingText = $('turn-waiting-text');
995
+
996
+ if (!isMyTurn()) {
997
+ // Other player's turn or spectator
998
+ area.classList.add('disabled');
999
+ textarea.disabled = true;
1000
+ submitBtn.disabled = true;
1001
+ if (voiceBtn) voiceBtn.disabled = true;
1002
+
1003
+ if (waitingBanner) {
1004
+ waitingBanner.style.display = 'flex';
1005
+ if (myRole === 'spectator') {
1006
+ waitingText.textContent = '👀 Spectator Mode · Live Debate in Progress';
1007
+ } else {
1008
+ const curName = matchConfig ? (currentPlayer === 'p1' ? matchConfig.p1Name : matchConfig.p2Name) : 'opponent';
1009
+ waitingText.textContent = `⏳ Waiting for ${curName} to submit argument from their laptop...`;
1010
+ }
1011
+ }
1012
+ return;
1013
+ }
1014
+
1015
+ // It IS this device's turn
1016
+ if (waitingBanner) waitingBanner.style.display = 'none';
1017
+ area.classList.remove('disabled');
1018
+ textarea.disabled = false;
1019
+ if (voiceBtn) voiceBtn.disabled = false;
1020
+ textarea.focus();
1021
+ updateWordCount();
1022
+ }
1023
+
1024
+ function disableInput() {
1025
+ const area = $('input-area');
1026
+ area.classList.add('disabled');
1027
+ textarea.disabled = true;
1028
+ submitBtn.disabled = true;
1029
+ if (voiceBtn) voiceBtn.disabled = true;
1030
+ }
1031
+
1032
+ textarea.addEventListener('input', updateWordCount);
1033
+
1034
+ function updateWordCount() {
1035
+ const words = countWords(textarea.value);
1036
+ wordCount.textContent = `${words} / ${MAX_WORDS} words`;
1037
+ wordCount.style.color = words > MAX_WORDS * 0.9
1038
+ ? 'var(--accent-amber)'
1039
+ : 'var(--text-muted)';
1040
+
1041
+ submitBtn.disabled = textarea.value.trim().length === 0;
1042
+ }
1043
+
1044
+
1045
+ // ─── Voice Input (PDF Section 5) ─────────────────────────────────────────────
1046
+
1047
+ function initVoiceRecognition() {
1048
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
1049
+ if (!SpeechRecognition) {
1050
+ voiceBtn.style.display = 'none';
1051
+ return;
1052
+ }
1053
+
1054
+ recognition = new SpeechRecognition();
1055
+ recognition.continuous = true;
1056
+ recognition.interimResults = true;
1057
+ recognition.lang = 'en-US'; // English enforced (PDF Section 5.4)
1058
+ recognition.maxAlternatives = 1;
1059
+
1060
+ let finalTranscript = '';
1061
+ let interimTranscript = '';
1062
+
1063
+ recognition.addEventListener('result', e => {
1064
+ interimTranscript = '';
1065
+ finalTranscript = '';
1066
+ for (let i = e.resultIndex; i < e.results.length; i++) {
1067
+ if (e.results[i].isFinal) {
1068
+ finalTranscript += e.results[i][0].transcript;
1069
+ } else {
1070
+ interimTranscript += e.results[i][0].transcript;
1071
+ }
1072
+ }
1073
+ // Show interim in textarea
1074
+ textarea.value = finalTranscript + interimTranscript;
1075
+ updateWordCount();
1076
+ });
1077
+
1078
+ recognition.addEventListener('end', () => {
1079
+ if (isRecording) {
1080
+ // Stopped naturally — show transcript confirmation (PDF Section 5.1)
1081
+ voiceTranscript = textarea.value;
1082
+ if (voiceTranscript.trim()) {
1083
+ showVoiceConfirmation(voiceTranscript);
1084
+ }
1085
+ setVoiceState(false);
1086
+ }
1087
+ });
1088
+
1089
+ recognition.addEventListener('error', e => {
1090
+ console.error('[Voice] Error:', e.error);
1091
+ setVoiceState(false);
1092
+
1093
+ if (e.error === 'not-allowed') {
1094
+ toast('Microphone access denied. Please use text input.', 'error');
1095
+ voiceBtn.style.display = 'none';
1096
+ } else if (e.error === 'network') {
1097
+ toast('Network error with speech recognition. Using text input.', 'warning');
1098
+ } else {
1099
+ toast('Voice input failed. Please type your argument.', 'warning');
1100
+ }
1101
+ });
1102
+ }
1103
+
1104
+ voiceBtn.addEventListener('click', () => {
1105
+ if (!recognition) {
1106
+ toast('Voice input not supported in this browser.', 'warning');
1107
+ return;
1108
+ }
1109
+
1110
+ if (!isRecording) {
1111
+ // Start recording
1112
+ textarea.value = '';
1113
+ voiceTranscript = '';
1114
+ hideVoicePreview();
1115
+ try {
1116
+ recognition.start();
1117
+ setVoiceState(true);
1118
+ toast('Recording... speak your argument.', 'info', 2000);
1119
+ } catch (e) {
1120
+ toast('Could not start microphone: ' + e.message, 'error');
1121
+ }
1122
+ } else {
1123
+ // Stop recording manually
1124
+ recognition.stop();
1125
+ setVoiceState(false);
1126
+ }
1127
+ });
1128
+
1129
+ /**
1130
+ * Voice transcript confirmation (PDF Section 5.1):
1131
+ * "Never silently score a transcript the participant cannot inspect."
1132
+ * Show transcript, allow correction, only judge confirmed version.
1133
+ */
1134
+ function showVoiceConfirmation(transcript) {
1135
+ voicePreviewText.textContent = transcript;
1136
+ voicePreview.classList.add('visible');
1137
+ voiceConfirm.style.display = '';
1138
+ voiceCancel.style.display = '';
1139
+ textarea.value = transcript;
1140
+ textarea.focus();
1141
+ toast('🎙️ Transcript ready — review and confirm before submitting.', 'info', 5000);
1142
+ }
1143
+
1144
+ function hideVoicePreview() {
1145
+ voicePreview.classList.remove('visible');
1146
+ voiceConfirm.style.display = 'none';
1147
+ voiceCancel.style.display = 'none';
1148
+ }
1149
+
1150
+ voiceConfirm.addEventListener('click', () => {
1151
+ // User confirmed — transcript is already in textarea, ready to submit
1152
+ hideVoicePreview();
1153
+ toast('Transcript confirmed. Submit when ready.', 'success', 2000);
1154
+ });
1155
+
1156
+ voiceCancel.addEventListener('click', () => {
1157
+ // Discard (PDF Section 5.1: participant controls the transcript)
1158
+ textarea.value = '';
1159
+ voiceTranscript = '';
1160
+ hideVoicePreview();
1161
+ updateWordCount();
1162
+ toast('Transcript discarded. Speak again or type your argument.', 'info', 3000);
1163
+ });
1164
+
1165
+ function setVoiceState(recording) {
1166
+ isRecording = recording;
1167
+ const icon = $('voice-btn-icon');
1168
+ const text = $('voice-btn-text');
1169
+
1170
+ if (recording) {
1171
+ voiceBtn.classList.add('recording');
1172
+ icon.textContent = '⏹️';
1173
+ text.textContent = 'Stop';
1174
+ voiceBtn.setAttribute('aria-label', 'Stop recording');
1175
+ } else {
1176
+ voiceBtn.classList.remove('recording');
1177
+ icon.textContent = '🎙️';
1178
+ text.textContent = 'Speak';
1179
+ voiceBtn.setAttribute('aria-label', 'Start voice input');
1180
+ }
1181
+ }
1182
+
1183
+
1184
+ // ─── Analyzing overlay ────────────────────────────────────────────────────────
1185
+
1186
+ const PIPELINE_STEPS = [
1187
+ { id: 'step-segment', label: 'Segmenting claims...', ms: 300 },
1188
+ { id: 'step-embed', label: 'Encoding semantics...', ms: 500 },
1189
+ { id: 'step-retrieve', label: 'Retrieving opponent points...', ms: 400 },
1190
+ { id: 'step-nli', label: 'Running NLI analysis...', ms: 600 },
1191
+ { id: 'step-score', label: 'Computing score...', ms: 400 },
1192
+ { id: 'step-rag', label: 'Fact-checking (background)...', ms: 200 },
1193
+ ];
1194
+
1195
+ function showAnalyzingOverlay() {
1196
+ analyzingOverlay.classList.add('visible');
1197
+ // Animate steps in sequence
1198
+ PIPELINE_STEPS.forEach((step, i) => {
1199
+ setTimeout(() => {
1200
+ const el = $(step.id);
1201
+ if (el) {
1202
+ // Mark previous as done
1203
+ if (i > 0) {
1204
+ const prev = $(PIPELINE_STEPS[i - 1].id);
1205
+ if (prev) { prev.classList.remove('active'); prev.classList.add('done'); }
1206
+ }
1207
+ el.classList.add('active');
1208
+ }
1209
+ }, PIPELINE_STEPS.slice(0, i).reduce((acc, s) => acc + s.ms, 0));
1210
+ });
1211
+ }
1212
+
1213
+ function hideAnalyzingOverlay() {
1214
+ analyzingOverlay.classList.remove('visible');
1215
+ PIPELINE_STEPS.forEach(step => {
1216
+ const el = $(step.id);
1217
+ if (el) { el.classList.remove('active', 'done'); }
1218
+ });
1219
+ }
1220
+
1221
+
1222
+ // ─── Reset ────────────────────────────────────────────────────────────────────
1223
+
1224
+ resetBtn.addEventListener('click', async () => {
1225
+ if (!matchId) return;
1226
+ if (!confirm('Reset the current match? This will clear all debate state.')) return;
1227
+
1228
+ try {
1229
+ await fetch(`${API_BASE}/api/match/${matchId}/reset`, { method: 'POST' });
1230
+ } catch (e) { }
1231
+
1232
+ stopTimer();
1233
+ goToSetup();
1234
+ toast('Match reset.', 'info');
1235
+ });
1236
+
1237
+ newMatchBtn.addEventListener('click', () => {
1238
+ goToSetup(false);
1239
+ });
1240
+
1241
+ const reuseRoomBtn = $('reuse-room-btn');
1242
+ if (reuseRoomBtn) {
1243
+ reuseRoomBtn.addEventListener('click', () => {
1244
+ goToSetup(true);
1245
+ });
1246
+ }
1247
+
1248
+ const cancelReuseBtn = $('cancel-room-reuse-btn');
1249
+ if (cancelReuseBtn) {
1250
+ cancelReuseBtn.addEventListener('click', () => {
1251
+ reusedMatchId = null;
1252
+ const banner = $('reusing-room-banner');
1253
+ if (banner) banner.style.display = 'none';
1254
+ toast('Switched to fresh room mode.', 'info');
1255
+ });
1256
+ }
1257
+
1258
+ function goToSetup(keepRoom = false) {
1259
+ stopTimer();
1260
+
1261
+ if (keepRoom && matchId) {
1262
+ reusedMatchId = matchId;
1263
+ const banner = $('reusing-room-banner');
1264
+ if (banner) {
1265
+ banner.style.display = 'flex';
1266
+ $('reused-room-code-tag').textContent = reusedMatchId;
1267
+ }
1268
+ const topicInput = $('topic-input');
1269
+ if (topicInput) {
1270
+ topicInput.value = '';
1271
+ setTimeout(() => topicInput.focus(), 250);
1272
+ }
1273
+ toast(`Configuring next debate for Room: ${reusedMatchId}`, 'info');
1274
+ } else {
1275
+ reusedMatchId = null;
1276
+ const banner = $('reusing-room-banner');
1277
+ if (banner) banner.style.display = 'none';
1278
+ matchId = null;
1279
+ matchConfig = null;
1280
+ }
1281
+
1282
+ currentPlayer = 'p1';
1283
+ isSubmitting = false;
1284
+ voiceTranscript = '';
1285
+
1286
+ // Reset final screen cards
1287
+ $('p1-final-card').classList.remove('winner');
1288
+ $('p2-final-card').classList.remove('winner', 'p2-win');
1289
+ $('p1-crown').style.display = 'none';
1290
+ $('p2-crown').style.display = 'none';
1291
+
1292
+ showScreen('setup-screen');
1293
+ }
1294
+
1295
+
1296
+ // ─── Confetti celebration ─────────────────────────────────────────────────────
1297
+
1298
+ function launchConfetti(winner) {
1299
+ const canvas = $('confetti-canvas');
1300
+ const ctx = canvas.getContext('2d');
1301
+ canvas.width = window.innerWidth;
1302
+ canvas.height = window.innerHeight;
1303
+
1304
+ const color = winner === 'p1' ? '#3b82f6' : '#f43f5e';
1305
+ const colors = [color, '#ffffff', '#8b5cf6', '#10b981', '#f59e0b'];
1306
+
1307
+ const particles = Array.from({ length: 120 }, () => ({
1308
+ x: Math.random() * canvas.width,
1309
+ y: -10,
1310
+ r: Math.random() * 6 + 2,
1311
+ d: Math.random() * 20,
1312
+ color: colors[Math.floor(Math.random() * colors.length)],
1313
+ tilt: Math.random() * 10 - 10,
1314
+ tiltAngle: 0,
1315
+ tiltAngleIncr: 0.07 + Math.random() * 0.05,
1316
+ speed: Math.random() * 3 + 2
1317
+ }));
1318
+
1319
+ let frame = 0;
1320
+ const maxFrames = 150;
1321
+
1322
+ function draw() {
1323
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
1324
+ particles.forEach(p => {
1325
+ ctx.beginPath();
1326
+ ctx.lineWidth = p.r / 2;
1327
+ ctx.strokeStyle = p.color;
1328
+ ctx.moveTo(p.x + p.tilt + p.r / 4, p.y);
1329
+ ctx.lineTo(p.x + p.tilt, p.y + p.tilt + p.r / 4);
1330
+ ctx.stroke();
1331
+
1332
+ p.y += p.speed;
1333
+ p.tiltAngle += p.tiltAngleIncr;
1334
+ p.tilt = Math.sin(p.tiltAngle) * 15;
1335
+
1336
+ // Respawn
1337
+ if (p.y > canvas.height + 10) {
1338
+ p.x = Math.random() * canvas.width;
1339
+ p.y = -10;
1340
+ }
1341
+ });
1342
+
1343
+ frame++;
1344
+ if (frame < maxFrames) {
1345
+ requestAnimationFrame(draw);
1346
+ } else {
1347
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
1348
+ }
1349
+ }
1350
+ draw();
1351
+ }
1352
+
1353
+
1354
+ // ─── Utility ─────────────────────────────────────────────────────────────────
1355
+
1356
+ function handleEvidenceUpdate(data) {
1357
+ const factItem = document.getElementById(`fact-claim-${data.claim_id}`);
1358
+ if (factItem) {
1359
+ factItem.className = `fact-item ${data.verdict.toLowerCase()}`;
1360
+ const verdictLabel = data.verdict.replace(/_/g, ' ');
1361
+ const icon = data.verdict === 'VERIFIED' ? '✅' : (data.verdict === 'INSUFFICIENT_EVIDENCE' ? '❓' : '❌');
1362
+ factItem.querySelector('.fact-verdict').innerHTML = `${icon} ${verdictLabel}`;
1363
+ }
1364
+
1365
+ document.querySelectorAll('.rag-pending-chip').forEach(badge => badge.remove());
1366
+
1367
+ if (data.score) {
1368
+ updatePlayerScores(data.player_id, data.score);
1369
+ }
1370
+ }
1371
+
1372
+ function escapeHtml(str) {
1373
+ if (!str) return '';
1374
+ return str
1375
+ .replace(/&/g, '&amp;')
1376
+ .replace(/</g, '&lt;')
1377
+ .replace(/>/g, '&gt;')
1378
+ .replace(/"/g, '&quot;');
1379
+ }
1380
+
1381
+
1382
+ // ─── Multi-Device Match Joining & Room Sharing ───────────────────────────────
1383
+
1384
+ async function joinMatch(targetMatchId, role) {
1385
+ try {
1386
+ toast(`Connecting to room ${targetMatchId}...`, 'info');
1387
+ const res = await fetch(`${API_BASE}/api/match/${targetMatchId}`);
1388
+ if (!res.ok) {
1389
+ throw new Error('Match room not found or expired.');
1390
+ }
1391
+ const data = await res.json();
1392
+ matchId = data.match_id;
1393
+ myRole = role || 'p2';
1394
+
1395
+ const p1Name = data.p1 ? data.p1.name : (data.players && data.players.p1 ? data.players.p1.name : 'Player 1');
1396
+ const p2Name = data.p2 ? data.p2.name : (data.players && data.players.p2 ? data.players.p2.name : 'Player 2');
1397
+ matchConfig = {
1398
+ p1Name,
1399
+ p2Name,
1400
+ topic: data.topic,
1401
+ maxRounds: data.max_rounds
1402
+ };
1403
+ currentPlayer = data.current_player || 'p1';
1404
+
1405
+ // Connect WebSocket
1406
+ connectWebSocket(matchId);
1407
+
1408
+ // Initialize UI
1409
+ initDebateUI(data);
1410
+
1411
+ // If there is existing turn history, replay into feed
1412
+ if (data.turn_log && data.turn_log.length > 0) {
1413
+ feedEmpty.style.display = 'none';
1414
+ data.turn_log.forEach(turn => {
1415
+ addDebateBubble(turn.player_id, turn.player_name, {
1416
+ text: turn.text,
1417
+ round_number: turn.round,
1418
+ score: { weighted_total: Math.round((turn.score || 0) * 100) },
1419
+ claims: []
1420
+ });
1421
+ });
1422
+ if (data.p1 && data.p1.total_score != null) {
1423
+ $('p1-total-score').textContent = data.p1.total_score.toFixed(1);
1424
+ $('p1-score-header').textContent = data.p1.total_score.toFixed(1);
1425
+ }
1426
+ if (data.p2 && data.p2.total_score != null) {
1427
+ $('p2-total-score').textContent = data.p2.total_score.toFixed(1);
1428
+ $('p2-score-header').textContent = data.p2.total_score.toFixed(1);
1429
+ }
1430
+ }
1431
+
1432
+ showScreen('debate-screen');
1433
+ startTimer();
1434
+
1435
+ const roleName = myRole === 'spectator' ? 'Spectator (Projector)' : (myRole === 'p2' ? 'Player 2 (AGAINST)' : 'Player 1 (FOR)');
1436
+ toast(`Joined room ${matchId} as ${roleName}!`, 'success');
1437
+
1438
+ } catch (err) {
1439
+ toast(`Could not join room: ${err.message}`, 'error');
1440
+ console.error(err);
1441
+ }
1442
+ }
1443
+
1444
+ async function checkForActiveMatch() {
1445
+ try {
1446
+ const res = await fetch(`${API_BASE}/api/match/latest`);
1447
+ if (res.ok) {
1448
+ const match = await res.json();
1449
+ const card = $('active-match-card');
1450
+ if (card && match && match.match_id) {
1451
+ card.style.display = 'block';
1452
+ $('active-match-topic').textContent = match.topic;
1453
+ const p1n = match.p1 ? match.p1.name : 'Player 1';
1454
+ const p2n = match.p2 ? match.p2.name : 'Player 2';
1455
+ $('active-match-players').textContent = `${p1n} (FOR) vs ${p2n} (AGAINST) · Round ${match.current_round}/${match.max_rounds} · Room: ${match.match_id}`;
1456
+
1457
+ const qP2 = $('quick-join-p2-btn');
1458
+ if (qP2) qP2.onclick = () => joinMatch(match.match_id, 'p2');
1459
+ const qSpec = $('quick-join-spectator-btn');
1460
+ if (qSpec) qSpec.onclick = () => joinMatch(match.match_id, 'spectator');
1461
+ const qP1 = $('quick-join-p1-btn');
1462
+ if (qP1) qP1.onclick = () => joinMatch(match.match_id, 'p1');
1463
+ }
1464
+ } else {
1465
+ const card = $('active-match-card');
1466
+ if (card) card.style.display = 'none';
1467
+ }
1468
+ } catch (_) {
1469
+ // Backend offline or no active match
1470
+ }
1471
+ }
1472
+
1473
+ function initMultiDeviceControls() {
1474
+ // Setup tabs
1475
+ const tabHostBtn = $('tab-host-btn');
1476
+ const tabJoinBtn = $('tab-join-btn');
1477
+ const hostPanel = $('host-tab-panel');
1478
+ const joinPanel = $('join-tab-panel');
1479
+
1480
+ if (tabHostBtn && tabJoinBtn) {
1481
+ tabHostBtn.addEventListener('click', () => {
1482
+ tabHostBtn.classList.add('active');
1483
+ tabJoinBtn.classList.remove('active');
1484
+ if (hostPanel) hostPanel.style.display = '';
1485
+ if (joinPanel) joinPanel.style.display = 'none';
1486
+ });
1487
+
1488
+ tabJoinBtn.addEventListener('click', () => {
1489
+ tabJoinBtn.classList.add('active');
1490
+ tabHostBtn.classList.remove('active');
1491
+ if (hostPanel) hostPanel.style.display = 'none';
1492
+ if (joinPanel) joinPanel.style.display = '';
1493
+ checkForActiveMatch();
1494
+ });
1495
+ }
1496
+
1497
+ // Manual join button
1498
+ const manualJoinBtn = $('manual-join-btn');
1499
+ if (manualJoinBtn) {
1500
+ manualJoinBtn.addEventListener('click', () => {
1501
+ const mId = $('join-match-id').value.trim();
1502
+ const role = $('join-role-select').value;
1503
+ if (!mId) {
1504
+ toast('Please enter a Debate Room ID.', 'error');
1505
+ return;
1506
+ }
1507
+ joinMatch(mId, role);
1508
+ });
1509
+ }
1510
+
1511
+ // Helper to generate a link that works on other laptops even if host opened localhost
1512
+ function buildShareLink(role) {
1513
+ if (!matchId) return '';
1514
+ const currentHost = window.location.hostname;
1515
+ let targetHost = currentHost;
1516
+ if (currentHost === 'localhost' || currentHost === '127.0.0.1') {
1517
+ targetHost = serverLanIp || '10.126.165.227';
1518
+ }
1519
+ const portPart = window.location.port ? `:${window.location.port}` : '';
1520
+ return `${window.location.protocol}//${targetHost}${portPart}${window.location.pathname}?match=${matchId}&role=${role}`;
1521
+ }
1522
+
1523
+ // Share invite link buttons
1524
+ const shareP2Btn = $('share-p2-btn');
1525
+ if (shareP2Btn) {
1526
+ shareP2Btn.addEventListener('click', () => {
1527
+ if (!matchId) return;
1528
+ const url = buildShareLink('p2');
1529
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1530
+ navigator.clipboard.writeText(url).then(() => {
1531
+ toast(`📋 Player 2 link copied (${url})! Send to Laptop 2.`, 'success', 6000);
1532
+ }).catch(() => {
1533
+ prompt('Copy Player 2 link:', url);
1534
+ });
1535
+ } else {
1536
+ prompt('Copy Player 2 link:', url);
1537
+ }
1538
+ });
1539
+ }
1540
+
1541
+ const shareSpecBtn = $('share-spectator-btn');
1542
+ if (shareSpecBtn) {
1543
+ shareSpecBtn.addEventListener('click', () => {
1544
+ if (!matchId) return;
1545
+ const url = buildShareLink('spectator');
1546
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1547
+ navigator.clipboard.writeText(url).then(() => {
1548
+ toast(`📺 Projector link copied (${url})! Open on audience screen.`, 'success', 6000);
1549
+ }).catch(() => {
1550
+ prompt('Copy Projector link:', url);
1551
+ });
1552
+ } else {
1553
+ prompt('Copy Projector link:', url);
1554
+ }
1555
+ });
1556
+ }
1557
+ }
1558
+
1559
+
1560
+ // ─── Init ─────────────────────────────────────────────────────────────────────
1561
+
1562
+ document.addEventListener('DOMContentLoaded', () => {
1563
+ initVoiceRecognition();
1564
+ initMultiDeviceControls();
1565
+ checkServerStatus();
1566
+
1567
+ // Periodic health check (exhibition reliability — PDF Section 24)
1568
+ setInterval(checkServerStatus, 30000);
1569
+
1570
+ // Check URL query parameters for auto-joining: ?match=<id>&role=<p1|p2|spectator>
1571
+ const urlParams = new URLSearchParams(window.location.search);
1572
+ const queryMatchId = urlParams.get('match');
1573
+ const queryRole = urlParams.get('role');
1574
+
1575
+ if (queryMatchId) {
1576
+ joinMatch(queryMatchId, queryRole || 'p2');
1577
+ } else {
1578
+ checkForActiveMatch();
1579
+ // Refresh active matches every 6 seconds on setup screen
1580
+ setInterval(() => {
1581
+ if ($('setup-screen').classList.contains('active')) {
1582
+ checkForActiveMatch();
1583
+ }
1584
+ }, 6000);
1585
+ }
1586
+
1587
+ // Enter key to submit
1588
+ textarea.addEventListener('keydown', e => {
1589
+ if (e.key === 'Enter' && e.ctrlKey) {
1590
+ e.preventDefault();
1591
+ submitBtn.click();
1592
+ }
1593
+ });
1594
+
1595
+ // Window resize for confetti canvas
1596
+ window.addEventListener('resize', () => {
1597
+ const canvas = $('confetti-canvas');
1598
+ if (canvas) {
1599
+ canvas.width = window.innerWidth;
1600
+ canvas.height = window.innerHeight;
1601
+ }
1602
+ });
1603
+ });
frontend/index.html ADDED
@@ -0,0 +1,678 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Clash of Minds — AI Debate Judge | CSES ML Exhibition</title>
7
+ <meta name="description" content="AI-powered live debate evaluation and evidence verification system. Two participants argue opposing sides; an AI judge evaluates every argument and declares a winner." />
8
+ <link rel="stylesheet" href="style.css" />
9
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
10
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
11
+ </head>
12
+ <body>
13
+
14
+ <!-- Connection offline banner -->
15
+ <div id="connection-banner" class="connection-banner" role="alert" aria-live="assertive">
16
+ ⚠️ Backend connection lost — attempting to reconnect...
17
+ </div>
18
+
19
+ <!-- Confetti canvas (winner celebration) -->
20
+ <canvas id="confetti-canvas" class="confetti-canvas" aria-hidden="true"></canvas>
21
+
22
+ <!-- Main app -->
23
+ <div id="app">
24
+
25
+ <!-- ══════════════════════════════════════════════
26
+ SETUP SCREEN
27
+ ══════════════════════════════════════════════ -->
28
+ <section id="setup-screen" class="screen active" aria-label="Match Setup">
29
+
30
+ <!-- Top bar -->
31
+ <header class="top-bar">
32
+ <div class="logo">
33
+ <div class="logo-icon" aria-hidden="true">⚡</div>
34
+ <div>
35
+ <div class="logo-text">Clash of Minds</div>
36
+ <div class="logo-sub">CSES ML Exhibition · NIT Warangal</div>
37
+ </div>
38
+ </div>
39
+ <div class="status-badge">
40
+ <span class="status-dot" id="server-status-dot" aria-label="Server status"></span>
41
+ <span id="server-status-text">Connecting...</span>
42
+ </div>
43
+ </header>
44
+
45
+ <!-- Hero -->
46
+ <div style="flex:1; display:flex; flex-direction:column; align-items:center; justify-content:center; padding: 40px 24px;">
47
+ <div class="setup-hero">
48
+ <h1>
49
+ <span class="word-clash">Clash</span> of <span class="word-minds">Minds</span>
50
+ </h1>
51
+ <p class="tagline">
52
+ AI-Powered Debate Judge &mdash;
53
+ <span>Claim-Level Evaluation</span> &middot;
54
+ <span>Internet Fact Verification</span> &middot;
55
+ <span>Live Scoring</span>
56
+ </p>
57
+ </div>
58
+
59
+ <!-- Setup card -->
60
+ <div class="setup-card" role="form" aria-label="Match setup form">
61
+
62
+ <!-- Setup Tabs: Host vs Join -->
63
+ <div class="setup-tabs">
64
+ <button id="tab-host-btn" class="setup-tab active" type="button">
65
+ ⚔️ Host Debate (Host)
66
+ </button>
67
+ <button id="tab-join-btn" class="setup-tab" type="button">
68
+ 🔗 Join Debate (2nd Laptop / Spectator)
69
+ </button>
70
+ </div>
71
+
72
+ <!-- TAB 1: HOST DEBATE -->
73
+ <div id="host-tab-panel">
74
+ <h2>⚔️ Configure Match</h2>
75
+
76
+ <!-- Reusing room code banner -->
77
+ <div id="reusing-room-banner" style="display:none; background:rgba(59,130,246,0.12); border:1px solid rgba(59,130,246,0.35); border-radius:var(--radius-xs); padding:10px 14px; margin-bottom:16px; font-size:12px; color:var(--accent-cyan); display:flex; justify-content:space-between; align-items:center;">
78
+ <span>🔄 <strong>Reusing Room:</strong> <code id="reused-room-code-tag" style="background:rgba(0,0,0,0.3); padding:2px 6px; border-radius:3px;">------</code> (Laptop 2 will auto-join)</span>
79
+ <button id="cancel-room-reuse-btn" class="btn btn-xs" type="button" style="background:rgba(255,255,255,0.08); color:var(--text-secondary); border:1px solid var(--border);">
80
+ Use Fresh Room
81
+ </button>
82
+ </div>
83
+
84
+ <!-- Player names -->
85
+ <div class="setup-grid">
86
+ <div class="field-group p1-field">
87
+ <label for="p1-name">
88
+ Player 1 <span class="player-badge p1-badge">FOR</span>
89
+ </label>
90
+ <input
91
+ id="p1-name"
92
+ class="input-field"
93
+ type="text"
94
+ placeholder="Enter name..."
95
+ maxlength="40"
96
+ autocomplete="off"
97
+ />
98
+ </div>
99
+ <div class="field-group p2-field">
100
+ <label for="p2-name">
101
+ Player 2 <span class="player-badge p2-badge">AGAINST</span>
102
+ </label>
103
+ <input
104
+ id="p2-name"
105
+ class="input-field"
106
+ type="text"
107
+ placeholder="Enter name..."
108
+ maxlength="40"
109
+ autocomplete="off"
110
+ />
111
+ </div>
112
+
113
+ <!-- Topic -->
114
+ <div class="field-group topic-field">
115
+ <label for="topic-input">Debate Topic / Proposition</label>
116
+ <textarea
117
+ id="topic-input"
118
+ class="input-field"
119
+ placeholder="e.g. Artificial Intelligence will do more good than harm to society."
120
+ rows="2"
121
+ maxlength="300"
122
+ ></textarea>
123
+ </div>
124
+ </div>
125
+
126
+ <!-- Side assignment display -->
127
+ <div class="side-display">
128
+ <div class="side-card for-side">
129
+ <span class="side-icon">✅</span>
130
+ <div>
131
+ <div style="font-size:10px; opacity:0.7; text-transform:uppercase; letter-spacing:0.1em">Player 1</div>
132
+ <div>Arguing <strong>FOR</strong> the proposition</div>
133
+ </div>
134
+ </div>
135
+ <div class="side-card against-side">
136
+ <span class="side-icon">🚫</span>
137
+ <div>
138
+ <div style="font-size:10px; opacity:0.7; text-transform:uppercase; letter-spacing:0.1em">Player 2</div>
139
+ <div>Arguing <strong>AGAINST</strong> the proposition</div>
140
+ </div>
141
+ </div>
142
+ </div>
143
+
144
+ <!-- Rounds selector -->
145
+ <div class="rounds-row">
146
+ <label for="max-rounds">Number of Rounds:</label>
147
+ <select id="max-rounds" class="rounds-select">
148
+ <option value="2">2 rounds (Quick)</option>
149
+ <option value="4" selected>4 rounds (Standard)</option>
150
+ <option value="6">6 rounds (Extended)</option>
151
+ </select>
152
+ <span style="font-size:12px; color:var(--text-muted); margin-left:4px">per player</span>
153
+ </div>
154
+
155
+ <!-- Host Device Role -->
156
+ <div class="role-selector-row">
157
+ <label>This Device Mode:</label>
158
+ <div class="role-options">
159
+ <label class="role-radio-label">
160
+ <input type="radio" name="host-device-role" value="p1" checked />
161
+ <span>⚡ Player 1 Laptop (Player 2 joins on separate laptop)</span>
162
+ </label>
163
+ <label class="role-radio-label">
164
+ <input type="radio" name="host-device-role" value="both" />
165
+ <span>💻 Single Laptop (Both players share this laptop)</span>
166
+ </label>
167
+ </div>
168
+ </div>
169
+
170
+ <button id="start-match-btn" class="btn btn-primary" aria-label="Start the debate match">
171
+ <span class="btn-icon">⚡</span>
172
+ Start Debate
173
+ </button>
174
+ </div>
175
+
176
+ <!-- TAB 2: JOIN DEBATE (FOR 2ND LAPTOP / SPECTATOR) -->
177
+ <div id="join-tab-panel" style="display:none;">
178
+ <h2>🔗 Join Ongoing Debate</h2>
179
+ <p style="font-size:13px; color:var(--text-secondary); margin-bottom:12px;">
180
+ Join a debate hosted on another laptop over the same Wi-Fi/Hotspot or Tunnel.
181
+ </p>
182
+ <div style="font-size:12px; color:var(--accent-amber); margin-bottom:14px; background:rgba(245,158,11,0.08); padding:8px 12px; border-radius:var(--radius-xs); border:1px solid rgba(245,158,11,0.2);">
183
+ 💡 <strong>Laptop 2 Note:</strong> Make sure you opened this browser using Laptop 1's Wi-Fi address (e.g. <code>http://10.137.243.227:8000</code>), not <code>localhost</code>.
184
+ </div>
185
+
186
+ <!-- Auto-detected active match card -->
187
+ <div id="active-match-card" class="active-match-card" style="display:none;">
188
+ <div class="active-match-badge">🔥 LIVE MATCH DETECTED</div>
189
+ <div id="active-match-topic" class="active-match-topic">Loading...</div>
190
+ <div id="active-match-players" class="active-match-players"></div>
191
+ <div class="active-match-actions">
192
+ <button id="quick-join-p2-btn" class="btn btn-sm btn-p2" type="button">
193
+ 👉 Join as Player 2 (AGAINST)
194
+ </button>
195
+ <button id="quick-join-spectator-btn" class="btn btn-sm btn-secondary" type="button">
196
+ 📺 Join as Spectator (Projector)
197
+ </button>
198
+ <button id="quick-join-p1-btn" class="btn btn-sm btn-p1" type="button">
199
+ Join as Player 1 (FOR)
200
+ </button>
201
+ </div>
202
+ </div>
203
+
204
+ <!-- Manual join input -->
205
+ <div style="background:rgba(255,255,255,0.02); padding:16px; border-radius:var(--radius-sm); border:1px solid var(--border);">
206
+ <div class="field-group" style="margin-bottom:12px;">
207
+ <label for="join-match-id">Debate Room ID:</label>
208
+ <input
209
+ id="join-match-id"
210
+ class="input-field"
211
+ type="text"
212
+ placeholder="e.g. 7b3a4f8910cd"
213
+ autocomplete="off"
214
+ />
215
+ </div>
216
+ <div class="field-group" style="margin-bottom:16px;">
217
+ <label for="join-role-select">Select Your Role on this Laptop:</label>
218
+ <select id="join-role-select" class="rounds-select" style="width:100%; height:40px;">
219
+ <option value="p2" selected>Player 2 (AGAINST the proposition)</option>
220
+ <option value="p1">Player 1 (FOR the proposition)</option>
221
+ <option value="spectator">Spectator / Projector / Audience</option>
222
+ <option value="both">Both Players (Single Screen)</option>
223
+ </select>
224
+ </div>
225
+ <button id="manual-join-btn" class="btn btn-primary" type="button" style="width:100%;">
226
+ 🚀 Join Debate Room
227
+ </button>
228
+ </div>
229
+ </div>
230
+
231
+ </div>
232
+ </div>
233
+ </section>
234
+
235
+
236
+ <!-- ══════════════════════════════════════════════
237
+ DEBATE SCREEN
238
+ ══════════════════════════════════════════════ -->
239
+ <section id="debate-screen" class="screen" aria-label="Live Debate">
240
+
241
+ <!-- Debate header bar -->
242
+ <header class="debate-header">
243
+ <!-- Player 1 mini-score -->
244
+ <div style="display:flex; align-items:center; gap:10px;">
245
+ <div class="turn-avatar p1" id="p1-avatar-header" aria-hidden="true">P1</div>
246
+ <div>
247
+ <div id="p1-name-header" style="font-weight:700; color:var(--p1-color); font-size:13px;">Player 1</div>
248
+ <div id="p1-score-header" style="font-size:22px; font-weight:800; color:var(--p1-color); font-family:'Space Grotesk',sans-serif;">0.0</div>
249
+ </div>
250
+ </div>
251
+
252
+ <!-- Center: Topic + Round -->
253
+ <div class="topic-display">
254
+ <div class="topic-label">DEBATE TOPIC</div>
255
+ <div class="topic-text" id="header-topic">—</div>
256
+ <div style="margin-top:8px; display:flex; justify-content:center;">
257
+ <div class="round-indicator">
258
+ <div class="round-dots" id="round-dots" aria-label="Round progress"></div>
259
+ <span id="round-label" style="font-size:12px; color:var(--text-secondary);">Round 1</span>
260
+ </div>
261
+ </div>
262
+ </div>
263
+
264
+ <!-- Player 2 mini-score -->
265
+ <div style="display:flex; align-items:center; gap:10px;">
266
+ <div>
267
+ <div id="p2-name-header" style="font-weight:700; color:var(--p2-color); font-size:13px; text-align:right;">Player 2</div>
268
+ <div id="p2-score-header" style="font-size:22px; font-weight:800; color:var(--p2-color); font-family:'Space Grotesk',sans-serif; text-align:right;">0.0</div>
269
+ </div>
270
+ <div class="turn-avatar p2" id="p2-avatar-header" aria-hidden="true">P2</div>
271
+ </div>
272
+
273
+ <!-- Operator controls & Room sharing -->
274
+ <div class="room-share-bar">
275
+ <span class="room-code-tag" id="room-code-badge" title="Debate Room ID">
276
+ Room: <strong id="room-id-text">------</strong>
277
+ </span>
278
+ <span class="device-role-tag" id="device-role-badge">Role: Player 1</span>
279
+ <button id="share-p2-btn" class="btn btn-xs btn-share" type="button" title="Copy join link for Player 2 laptop">
280
+ 📋 P2 Invite Link
281
+ </button>
282
+ <button id="share-spectator-btn" class="btn btn-xs btn-share" type="button" title="Copy link for projector / audience">
283
+ 📺 Projector Link
284
+ </button>
285
+ <button id="reset-btn" class="btn btn-reset" aria-label="Reset match" title="Operator: Reset match">
286
+ ↺ Reset
287
+ </button>
288
+ </div>
289
+ </header>
290
+
291
+ <!-- Main debate layout -->
292
+ <div class="debate-main">
293
+
294
+ <!-- ─ Left: Player 1 Panel ─ -->
295
+ <aside class="player-panel p1-panel" aria-label="Player 1 panel">
296
+ <div class="player-header">
297
+ <div class="player-name" id="p1-panel-name">Player 1</div>
298
+ <div class="player-side-tag">FOR the proposition</div>
299
+ <div class="total-score-display">
300
+ <div class="total-score-num" id="p1-total-score">0.0</div>
301
+ <div class="total-score-label">Total Score</div>
302
+ </div>
303
+ </div>
304
+
305
+ <!-- Score criteria bars -->
306
+ <div class="score-bars" aria-label="Player 1 scores">
307
+ <div class="score-bar-item">
308
+ <div class="score-bar-label">
309
+ <span>Rebuttal</span><span id="p1-rebuttal-val">—</span>
310
+ </div>
311
+ <div class="score-bar-track">
312
+ <div class="score-bar-fill" id="p1-rebuttal-bar" style="width:0%"></div>
313
+ </div>
314
+ </div>
315
+ <div class="score-bar-item">
316
+ <div class="score-bar-label">
317
+ <span>Reasoning</span><span id="p1-reasoning-val">—</span>
318
+ </div>
319
+ <div class="score-bar-track">
320
+ <div class="score-bar-fill" id="p1-reasoning-bar" style="width:0%"></div>
321
+ </div>
322
+ </div>
323
+ <div class="score-bar-item">
324
+ <div class="score-bar-label">
325
+ <span>Evidence</span><span id="p1-evidence-val">—</span>
326
+ </div>
327
+ <div class="score-bar-track">
328
+ <div class="score-bar-fill" id="p1-evidence-bar" style="width:0%"></div>
329
+ </div>
330
+ </div>
331
+ <div class="score-bar-item">
332
+ <div class="score-bar-label">
333
+ <span>Relevance</span><span id="p1-relevance-val">—</span>
334
+ </div>
335
+ <div class="score-bar-track">
336
+ <div class="score-bar-fill" id="p1-relevance-bar" style="width:0%"></div>
337
+ </div>
338
+ </div>
339
+ <div class="score-bar-item">
340
+ <div class="score-bar-label">
341
+ <span>Clarity</span><span id="p1-clarity-val">—</span>
342
+ </div>
343
+ <div class="score-bar-track">
344
+ <div class="score-bar-fill" id="p1-clarity-bar" style="width:0%"></div>
345
+ </div>
346
+ </div>
347
+ <div class="score-bar-item">
348
+ <div class="score-bar-label">
349
+ <span>Stance</span><span id="p1-stance-val">—</span>
350
+ </div>
351
+ <div class="score-bar-track">
352
+ <div class="score-bar-fill" id="p1-stance-bar" style="width:0%"></div>
353
+ </div>
354
+ </div>
355
+ </div>
356
+
357
+ <!-- Turn history -->
358
+ <div class="turn-history-title">Turn History</div>
359
+ <div class="turn-history" id="p1-turn-history" aria-label="Player 1 turn history"></div>
360
+ </aside>
361
+
362
+
363
+ <!-- ─ Center: Debate Arena ─ -->
364
+ <main class="debate-arena" aria-label="Debate arena">
365
+
366
+ <!-- Who's speaking now -->
367
+ <div class="turn-indicator" id="turn-indicator">
368
+ <div class="turn-avatar p1" id="current-avatar" aria-hidden="true">P1</div>
369
+ <div class="turn-info">
370
+ <div class="turn-player-name" id="current-player-name">Player 1</div>
371
+ <div class="turn-instruction" id="turn-instruction">Opening argument — FOR the proposition</div>
372
+ </div>
373
+ <!-- Timer -->
374
+ <div class="turn-timer" aria-label="Time remaining">
375
+ <div class="timer-ring">
376
+ <svg class="timer-svg" width="52" height="52" viewBox="0 0 52 52" aria-hidden="true">
377
+ <circle class="timer-track" cx="26" cy="26" r="22" fill="none" stroke-width="3"/>
378
+ <circle id="timer-progress-circle"
379
+ class="timer-progress" cx="26" cy="26" r="22"
380
+ fill="none" stroke-width="3"
381
+ stroke-dasharray="138.2"
382
+ stroke-dashoffset="0"/>
383
+ </svg>
384
+ <div class="timer-text" id="timer-display">—</div>
385
+ </div>
386
+ </div>
387
+ </div>
388
+
389
+ <!-- Debate transcript feed -->
390
+ <div class="debate-feed" id="debate-feed" aria-live="polite" aria-label="Debate transcript">
391
+ <div class="feed-empty" id="feed-empty">
392
+ <div class="empty-icon">🎙️</div>
393
+ <div>The debate will appear here as arguments are submitted.</div>
394
+ <div style="margin-top:8px; font-size:12px;">Player 1 (FOR) goes first.</div>
395
+ </div>
396
+ </div>
397
+
398
+ <!-- Argument input area -->
399
+ <div class="input-area" id="input-area" aria-label="Submit argument">
400
+
401
+ <!-- Turn waiting banner (shows when waiting for other device or in spectator mode) -->
402
+ <div id="turn-waiting-banner" class="turn-waiting-banner" style="display:none;">
403
+ <div class="waiting-pulse-dot"></div>
404
+ <div id="turn-waiting-text" class="turn-waiting-text">
405
+ Waiting for opponent's turn...
406
+ </div>
407
+ </div>
408
+
409
+ <!-- Voice transcript preview (shows before confirmation) -->
410
+ <div class="voice-transcript-preview" id="voice-preview">
411
+ <strong>🎙️ Voice Transcript — Review before submitting:</strong>
412
+ <span id="voice-preview-text"></span>
413
+ </div>
414
+
415
+ <textarea
416
+ id="argument-textarea"
417
+ class="argument-textarea"
418
+ placeholder="Type your argument here, or use the microphone to speak..."
419
+ aria-label="Argument text"
420
+ rows="3"
421
+ ></textarea>
422
+
423
+ <div class="input-toolbar">
424
+ <div class="input-left">
425
+ <!-- Voice input -->
426
+ <button
427
+ id="voice-btn"
428
+ class="btn btn-voice"
429
+ aria-label="Start voice input"
430
+ title="Hold to speak (Web Speech API)"
431
+ >
432
+ <span id="voice-btn-icon">🎙️</span>
433
+ <span id="voice-btn-text">Speak</span>
434
+ </button>
435
+
436
+ <!-- Voice confirm / cancel -->
437
+ <button
438
+ id="voice-confirm-btn"
439
+ class="btn"
440
+ style="display:none; background:rgba(16,185,129,0.15); color:var(--accent-green); border:1px solid rgba(16,185,129,0.25); border-radius:50px; padding:8px 16px; font-size:13px;"
441
+ aria-label="Confirm transcript and use as argument"
442
+ >
443
+ ✅ Use Transcript
444
+ </button>
445
+ <button
446
+ id="voice-cancel-btn"
447
+ class="btn"
448
+ style="display:none; background:rgba(239,68,68,0.10); color:var(--accent-red); border:1px solid rgba(239,68,68,0.25); border-radius:50px; padding:8px 14px; font-size:13px;"
449
+ aria-label="Discard transcript"
450
+ >
451
+ ✕ Discard
452
+ </button>
453
+
454
+ <span class="word-count" id="word-count" aria-live="polite">0 / 500 words</span>
455
+ </div>
456
+
457
+ <button id="submit-btn" class="btn btn-submit" aria-label="Submit argument for evaluation" disabled>
458
+ Submit Argument →
459
+ </button>
460
+ </div>
461
+ </div>
462
+ </main>
463
+
464
+
465
+ <!-- ─ Right: Analysis Panel ─ -->
466
+ <aside class="analysis-panel" aria-label="Live analysis panel">
467
+
468
+ <div>
469
+ <div class="panel-section-title">
470
+ 📊 Last Turn Analysis
471
+ </div>
472
+ <div id="no-analysis-msg" style="font-size:12px; color:var(--text-muted); margin-top:4px;">
473
+ Analysis will appear after the first submission.
474
+ </div>
475
+ </div>
476
+
477
+ <!-- Criterion score breakdown -->
478
+ <div id="criterion-section" style="display:none;">
479
+ <div class="panel-section-title">📐 Score Breakdown</div>
480
+ <div class="criterion-list">
481
+ <div class="criterion-row">
482
+ <div class="criterion-top">
483
+ <span class="criterion-name">Counterargument/Rebuttal</span>
484
+ <span class="criterion-weight">20%</span>
485
+ <span class="criterion-value" id="cr-rebuttal">—</span>
486
+ </div>
487
+ <div class="criterion-bar-track">
488
+ <div class="criterion-bar-fill rebuttal" id="crb-rebuttal" style="width:0%"></div>
489
+ </div>
490
+ </div>
491
+ <div class="criterion-row">
492
+ <div class="criterion-top">
493
+ <span class="criterion-name">Logical Reasoning</span>
494
+ <span class="criterion-weight">20%</span>
495
+ <span class="criterion-value" id="cr-reasoning">—</span>
496
+ </div>
497
+ <div class="criterion-bar-track">
498
+ <div class="criterion-bar-fill reasoning" id="crb-reasoning" style="width:0%"></div>
499
+ </div>
500
+ </div>
501
+ <div class="criterion-row">
502
+ <div class="criterion-top">
503
+ <span class="criterion-name">Evidence Quality</span>
504
+ <span class="criterion-weight">20%</span>
505
+ <span class="criterion-value" id="cr-evidence">—</span>
506
+ </div>
507
+ <div class="criterion-bar-track">
508
+ <div class="criterion-bar-fill evidence" id="crb-evidence" style="width:0%"></div>
509
+ </div>
510
+ </div>
511
+ <div class="criterion-row">
512
+ <div class="criterion-top">
513
+ <span class="criterion-name">Topic Relevance</span>
514
+ <span class="criterion-weight">15%</span>
515
+ <span class="criterion-value" id="cr-relevance">—</span>
516
+ </div>
517
+ <div class="criterion-bar-track">
518
+ <div class="criterion-bar-fill relevance" id="crb-relevance" style="width:0%"></div>
519
+ </div>
520
+ </div>
521
+ <div class="criterion-row">
522
+ <div class="criterion-top">
523
+ <span class="criterion-name">Clarity</span>
524
+ <span class="criterion-weight">15%</span>
525
+ <span class="criterion-value" id="cr-clarity">—</span>
526
+ </div>
527
+ <div class="criterion-bar-track">
528
+ <div class="criterion-bar-fill clarity" id="crb-clarity" style="width:0%"></div>
529
+ </div>
530
+ </div>
531
+ <div class="criterion-row">
532
+ <div class="criterion-top">
533
+ <span class="criterion-name">Stance Consistency</span>
534
+ <span class="criterion-weight">10%</span>
535
+ <span class="criterion-value" id="cr-stance">—</span>
536
+ </div>
537
+ <div class="criterion-bar-track">
538
+ <div class="criterion-bar-fill stance" id="crb-stance" style="width:0%"></div>
539
+ </div>
540
+ </div>
541
+ </div>
542
+ </div>
543
+
544
+ <!-- AI Feedback -->
545
+ <div id="feedback-section" style="display:none;">
546
+ <div class="panel-section-title">💬 Judge Feedback</div>
547
+ <div class="feedback-box" id="feedback-text"></div>
548
+ </div>
549
+
550
+ <!-- Claim types found -->
551
+ <div id="claims-section" style="display:none;">
552
+ <div class="panel-section-title">🧩 Claims Identified</div>
553
+ <div class="claim-chips" id="claims-chips"></div>
554
+ </div>
555
+
556
+ <!-- Argument relations (NLI output) -->
557
+ <div id="relations-section" style="display:none;">
558
+ <div class="panel-section-title">🔗 Argument Relations (NLI)</div>
559
+ <div class="relation-list" id="relation-list"></div>
560
+ </div>
561
+
562
+ <!-- Fact-check results (RAG) -->
563
+ <div id="factcheck-section" style="display:none;">
564
+ <div class="panel-section-title">🔍 Fact-Check Results</div>
565
+ <div class="fact-check-list" id="fact-check-list"></div>
566
+ </div>
567
+
568
+ <!-- Fairness note -->
569
+ <div style="padding:12px; border-radius:var(--radius-sm); background:rgba(255,255,255,0.03); border:1px solid var(--border); font-size:11px; color:var(--text-muted); line-height:1.7;">
570
+ <strong style="color:var(--text-secondary);">AI Judge Principles:</strong><br/>
571
+ • Contradiction ≠ strong rebuttal (reasoning required)<br/>
572
+ • True facts alone ≠ strong argument<br/>
573
+ • Unverified ≠ false — marked insufficient evidence<br/>
574
+ • New evidence on repeated claim = NOT penalized
575
+ </div>
576
+
577
+ </aside>
578
+ </div><!-- .debate-main -->
579
+
580
+ </section><!-- #debate-screen -->
581
+
582
+
583
+ <!-- ══════════════════════════════════════════════
584
+ FINAL / WINNER SCREEN
585
+ ══════════════════════════════════════════════ -->
586
+ <section id="final-screen" class="screen" aria-label="Debate result">
587
+
588
+ <header class="top-bar">
589
+ <div class="logo">
590
+ <div class="logo-icon">⚡</div>
591
+ <div>
592
+ <div class="logo-text">Clash of Minds</div>
593
+ <div class="logo-sub">CSES ML Exhibition · NIT Warangal</div>
594
+ </div>
595
+ </div>
596
+ </header>
597
+
598
+ <div style="flex:1; display:flex; flex-direction:column; align-items:center; justify-content:center; padding:40px 24px;">
599
+
600
+ <div class="winner-glow">
601
+ <div class="winner-label">🏆 Debate Winner</div>
602
+ <span class="winner-trophy" id="winner-trophy" aria-hidden="true">🏆</span>
603
+ <div class="winner-name" id="winner-name-display">—</div>
604
+ <div class="winner-side" id="winner-side-display">—</div>
605
+ </div>
606
+
607
+ <!-- Final scoreboard -->
608
+ <div class="final-scoreboard" aria-label="Final scores">
609
+ <!-- P1 card -->
610
+ <div class="final-score-card" id="p1-final-card">
611
+ <div class="player-name-final p1" id="p1-name-final">Player 1</div>
612
+ <div class="player-side-small">FOR the proposition</div>
613
+ <div class="final-total-score" id="p1-score-final" style="color:var(--p1-color);">0.0</div>
614
+ <div style="font-size:12px; color:var(--text-muted);">/ 100 pts</div>
615
+ <div class="crown-badge" id="p1-crown" style="display:none;">👑</div>
616
+ </div>
617
+ <!-- P2 card -->
618
+ <div class="final-score-card" id="p2-final-card">
619
+ <div class="player-name-final p2" id="p2-name-final">Player 2</div>
620
+ <div class="player-side-small">AGAINST the proposition</div>
621
+ <div class="final-total-score" id="p2-score-final" style="color:var(--p2-color);">0.0</div>
622
+ <div style="font-size:12px; color:var(--text-muted);">/ 100 pts</div>
623
+ <div class="crown-badge" id="p2-crown" style="display:none;">👑</div>
624
+ </div>
625
+ </div>
626
+
627
+ <!-- Topic reminder -->
628
+ <div style="max-width:560px; text-align:center; margin-bottom:40px;">
629
+ <div style="font-size:11px; text-transform:uppercase; letter-spacing:0.12em; color:var(--text-muted); margin-bottom:8px;">Debate Topic</div>
630
+ <div id="final-topic" style="font-size:16px; font-weight:600; color:var(--text-secondary); line-height:1.5;">—</div>
631
+ </div>
632
+
633
+ <!-- Actions -->
634
+ <div class="final-actions" style="display:flex; gap:12px; flex-wrap:wrap; justify-content:center;">
635
+ <button id="reuse-room-btn" class="btn btn-primary" type="button" style="background:linear-gradient(135deg, #3b82f6, #8b5cf6);" aria-label="Start next debate keeping this room code">
636
+ 🔄 Next Debate (Keep Room: <span id="reuse-room-code-label">------</span>)
637
+ </button>
638
+ <button id="new-match-btn" class="btn btn-new-match" aria-label="Start fresh match in new room">
639
+ ➕ Fresh Room
640
+ </button>
641
+ </div>
642
+ </div>
643
+ </section>
644
+
645
+ </div><!-- #app -->
646
+
647
+ <!-- Analyzing overlay (shown during pipeline processing) -->
648
+ <div id="analyzing-overlay" class="analyzing-overlay" role="status" aria-live="polite" aria-label="Analyzing argument">
649
+ <div class="analyzing-spinner"></div>
650
+ <div class="analyzing-label">Analyzing Argument...</div>
651
+ <div class="analyzing-steps">
652
+ <div class="analyzing-step" id="step-segment">
653
+ <span class="step-icon">🧩</span> Segmenting claims...
654
+ </div>
655
+ <div class="analyzing-step" id="step-embed">
656
+ <span class="step-icon">🔢</span> Encoding semantics...
657
+ </div>
658
+ <div class="analyzing-step" id="step-retrieve">
659
+ <span class="step-icon">🔍</span> Retrieving opponent points...
660
+ </div>
661
+ <div class="analyzing-step" id="step-nli">
662
+ <span class="step-icon">🔗</span> Running NLI relation analysis...
663
+ </div>
664
+ <div class="analyzing-step" id="step-score">
665
+ <span class="step-icon">📊</span> Computing score...
666
+ </div>
667
+ <div class="analyzing-step" id="step-rag">
668
+ <span class="step-icon">🌐</span> Fact-checking in background...
669
+ </div>
670
+ </div>
671
+ </div>
672
+
673
+ <!-- Toast container -->
674
+ <div id="toast-container" class="toast-container" aria-live="assertive" aria-atomic="true"></div>
675
+
676
+ <script src="app.js"></script>
677
+ </body>
678
+ </html>
frontend/pdf_content.txt ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CLASH OF MINDS | CSES ML EXHIBITION
2
+ Clash of Minds - Complete Workflow and Robustness Plan
3
+ CLASH OF MINDS
4
+ AI-Powered Live Debate Evaluation and Evidence
5
+ Verification System
6
+ Complete Project Workflow, NLP Architecture, Real-World Failure Handling, and
7
+ Exhibition Plan
8
+ Prepared for CSES Machine Learning Exhibition
9
+ NIT Warangal
10
+ Project basis: the provided Clash of Minds architecture proposal, expanded into a practical end-to-end
11
+ implementation plan.CLASH OF MINDS | CSES ML EXHIBITION
12
+ Clash of Minds - Complete Workflow and Robustness Plan
13
+ 1. Project Goal
14
+ Clash of Minds is an interactive debate platform in which two participants argue opposing sides of a
15
+ topic and an AI judge evaluates the quality of their arguments. The system supports both keyboard
16
+ input and voice input. The voice path converts speech into text and then feeds the same textual
17
+ argument pipeline, so the judging logic remains consistent across both input modes.
18
+ The main exhibition mode is a controlled multi-turn debate. Participants alternate turns for a fixed
19
+ number of rounds. After each turn, the system analyzes the new argument in relation to the topic, the
20
+ participant's own previous claims, and the opponent's relevant previous claims. Factual claims are
21
+ separately sent through an Internet-based retrieval and verification pipeline.
22
+ The design principle is claim-level evaluation. An entire paragraph is never reduced to one similarity
23
+ number. The system first identifies the individual claims inside an argument, determines which claims
24
+ are factual or argumentative, retrieves the relevant debate context, fact-checks checkable claims, and
25
+ then combines the resulting signals into a structured score.
26
+ 2. What the Exhibition System Must Handle
27
+ 1. Two participants with fixed opposing sides, using a common topic and equal turn structure.
28
+ 2. Both typed and spoken arguments, with transcript confirmation before the NLP judge evaluates a
29
+ spoken response.
30
+ 3. Multiple turns in which each participant is expected to listen to and respond to the opponent rather
31
+ than simply repeat an opening statement.
32
+ 4. Arguments with different wording but the same meaning, arguments with similar wording but
33
+ opposite meaning, and arguments that refer back to earlier statements using pronouns or phrases
34
+ such as "that point" or "your previous claim".
35
+ 5. Arguments containing one claim, several claims, mixed facts and opinions, conditional claims,
36
+ rhetorical questions, statistics, and claims requiring more than one source.
37
+ 6. Internet-based fact verification for checkable factual claims using reliable sources rather than a local-
38
+ only knowledge base.
39
+ 7. Continuous operation for approximately 5-6 hours, with repeated match resets and without requiring
40
+ a model reload between matches.
41
+ 8. Graceful behavior when speech recognition, internet retrieval, model inference, or browser
42
+ interaction fails.
43
+ 3. Core Architecture Principle
44
+ The three original NLP pipelines remain the core retrieval and understanding layer: Semantic
45
+ Embedding Model, Claim Segmentation, and Relevant Point Retrieval. Two additional layers are added
46
+ around them because the original three are not sufficient to decide whether an argument contradicts an
47
+ opponent, whether a factual claim is supported by evidence, or whether a rebuttal is actually strong.
48
+ Pipeline A - Semantic Embedding Model: creates semantic representations for topic relevance, claim
49
+ similarity, repetition detection, and fast candidate retrieval.
50
+ Pipeline B - Claim Segmentation: breaks long responses into atomic or near-atomic claims and
51
+ classifies the type of each claim before deeper evaluation.
52
+ Pipeline C - Relevant Point Retrieval: retrieves the opponent's most relevant previous claims and also
53
+ tracks unanswered or partially answered points so the system does not only compare the current
54
+ response with the immediately previous sentence.CLASH OF MINDS | CSES ML EXHIBITION
55
+ Clash of Minds - Complete Workflow and Robustness Plan
56
+ Additional layer - NLI / Argument Relation: uses a cross-encoder to examine the relationship between
57
+ a current claim and a retrieved opponent claim. Similarity alone cannot distinguish support,
58
+ contradiction, qualification, or a merely related topic.
59
+ Additional layer - Internet RAG Fact Verification: retrieves evidence from reliable internet sources,
60
+ ranks the evidence, and compares the evidence with the participant's factual claim. RAG retrieval is not
61
+ treated as proof by itself.
62
+ 4. Complete User Journey
63
+ 1. Start match: the operator or exhibition interface creates a new match and clears previous participant
64
+ state.
65
+ 2. Enter names: Player 1 and Player 2 are registered.
66
+ 3. Assign topic and side: the system displays one clearly worded proposition and assigns For and
67
+ Against.
68
+ 4. Select input method: each turn can use keyboard text or voice.
69
+ 5. Submit argument: voice is converted to text, shown to the participant, and optionally corrected before
70
+ submission.
71
+ 6. Validate input: the system checks length, emptiness, duplicate submission, active player, and turn
72
+ state.
73
+ 7. Segment claims: the response is split into claims or argument units and each unit receives a type
74
+ label.
75
+ 8. Run the three core pipelines: semantic embedding, claim segmentation, and relevant point retrieval
76
+ operate on the current response and debate history.
77
+ 9. Run relation analysis: the system compares the current response to relevant opponent claims and
78
+ determines whether it supports, challenges, qualifies, elaborates, or fails to address them.
79
+ 10. Run fact verification: checkable claims are sent to the Internet RAG path for evidence retrieval and
80
+ verification.
81
+ 11. Compute turn score: relevance, reasoning, rebuttal, evidence, clarity, stance consistency, and
82
+ repetition signals are combined under a fixed rubric.
83
+ 12. Show structured feedback: the participant sees concise feedback and the current score without
84
+ exposing internal implementation details.
85
+ 13. Update debate memory: new claims, response relations, verified evidence, unanswered points, and
86
+ scores are stored for the next turn.
87
+ 14. After the final round, aggregate turn-level results, produce the final scorecard and leaderboard
88
+ entry, and then reset match state for the next pair.
89
+ 5. Input Layer: Text and Voice
90
+ 5.1 Voice input and transcript integrity
91
+ Problem: Speech-to-text can change or omit important words, especially negation such as "not",
92
+ "never", or "cannot".
93
+ What we do: Convert the audio to text, display the transcript to the participant, allow correction, and
94
+ only judge the confirmed transcript. Never silently score a transcript that the participant cannot inspect.
95
+ What we use: Speech-to-text engine; browser microphone APIs or a tested local/cloud ASR
96
+ implementation; transcript editor; validation rules.CLASH OF MINDS | CSES ML EXHIBITION
97
+ Clash of Minds - Complete Workflow and Robustness Plan
98
+ Expected result: The same clean text format enters the NLP pipeline regardless of whether the original
99
+ input was typed or spoken.
100
+ 5.2 Accent and pronunciation differences
101
+ Problem: Different accents and speaking styles can produce unequal transcription quality. The debate
102
+ judge should not penalize an accent simply because the ASR engine misheard it.
103
+ What we do: Keep speech quality separate from argument quality. Measure only the transcript after
104
+ confirmation. If transcription confidence is poor, request a retry or allow text input.
105
+ What we use: ASR confidence if available; transcript confirmation; text fallback.
106
+ Expected result: The participant is judged on argument content rather than accent.
107
+ 5.3 Background noise and microphone failure
108
+ Problem: An exhibition hall may contain crowd noise, fans, other conversations, or microphone
109
+ permission problems.
110
+ What we do: Provide push-to-talk, visible recording state, maximum recording duration, microphone
111
+ error handling, and an immediate switch-to-text option.
112
+ What we use: Browser microphone status; ASR; timeout; text fallback.
113
+ Expected result: A microphone failure cannot terminate the match.
114
+ 5.4 Mixed language or Hinglish
115
+ Problem: Participants may naturally mix languages, which can reduce ASR and NLP reliability if the
116
+ models are designed primarily for English.
117
+ What we do: For the first exhibition version, define English as the supported judging language. Treat
118
+ multilingual support as an optional extension only after dedicated testing.
119
+ What we use: English-focused ASR/NLP stack initially; optional multilingual ASR for a later version.
120
+ Expected result: Controlled input improves reliability without pretending multilingual accuracy that
121
+ has not been measured.
122
+ 6. Claim Segmentation and Claim Typing
123
+ Claim segmentation is central to robustness. The same participant response can contain several
124
+ independent factual assertions, an opinion, a conditional statement, and a rhetorical question. Each
125
+ should be handled differently rather than sending the entire paragraph through one verifier.
126
+ 6.1 Multiple claims inside one response
127
+ Problem: A response can contain 2, 3, 4, or many claims. One overall score may hide the fact that some
128
+ claims are supported while others are unsupported or contradicted.
129
+ What we do: Split the response into atomic or near-atomic claims and evaluate each claim
130
+ independently. Aggregate claim-level results only after each claim has been analyzed.
131
+ What we use: Claim segmentation model; sentence splitting; semantic clustering; claim confidence
132
+ score.
133
+ Expected result: Every claim becomes an addressable unit in debate memory and fact verification.CLASH OF MINDS | CSES ML EXHIBITION
134
+ Clash of Minds - Complete Workflow and Robustness Plan
135
+ 6.2 Mixed fact and opinion
136
+ Problem: Statements such as "AI is the future" and "AI increased test scores by 25%" are not the same
137
+ type of content.
138
+ What we do: Classify each segment as factual claim, opinion, prediction, conditional, value judgment,
139
+ rhetorical/argumentative, statistic, or unclear. Only checkable factual claims should normally trigger
140
+ web verification.
141
+ What we use: Claim-type classifier; lightweight linguistic rules; confidence threshold.
142
+ Expected result: The fact checker spends time on claims where verification is meaningful.
143
+ 6.3 Hidden argument inside a rhetorical question
144
+ Problem: A rhetorical question may imply a claim without literally stating it.
145
+ What we do: Mark the form as rhetorical/argumentative and use the surrounding debate context to
146
+ determine whether it expresses an argument. Do not automatically fact-check the literal question as a
147
+ factual statement.
148
+ What we use: Claim-type classifier; debate context.
149
+ Expected result: Rhetorical language is evaluated for debate relevance and reasoning instead of
150
+ producing a false fact-check.
151
+ 6.4 Conditional and qualified statements
152
+ Problem: "AI reduces costs" and "If AI becomes cheaper, it could reduce costs" have different truth
153
+ conditions.
154
+ What we do: Preserve conditions, qualifiers, scope, time, and uncertainty when creating the claim
155
+ representation. Do not strip terms such as if, only, may, could, not, or unless.
156
+ What we use: Transformer-based claim representation; linguistic parsing; claim metadata.
157
+ Expected result: The fact checker verifies the actual proposition rather than a simplified but incorrect
158
+ version.
159
+ 6.5 Numerical and statistical claims
160
+ Problem: A statement containing a number can look authoritative even when the number is incorrect,
161
+ out of date, or taken out of context.
162
+ What we do: Extract value, metric, direction, population, time, condition, and source when available.
163
+ Search for evidence that matches the exact statistic, not merely the topic.
164
+ What we use: Claim parser; number/entity extraction; Internet RAG; evidence verification.
165
+ Expected result: The system can distinguish a specific supported statistic from a broad claim that is not
166
+ established by the source.
167
+ 7. Semantic Embedding Pipeline
168
+ The semantic embedding model is used for meaning-aware retrieval. It should not be treated as the
169
+ final contradiction or truth detector. The model converts the topic, claims, and previous debate points
170
+ into vectors. Similarity is then used to retrieve semantically related candidates even when vocabulary
171
+ changes.
172
+ 7.1 Different wording, same meaning
173
+ Problem: Two arguments may use different vocabulary but express the same idea.CLASH OF MINDS | CSES ML EXHIBITION
174
+ Clash of Minds - Complete Workflow and Robustness Plan
175
+ What we do: Use sentence embeddings for semantic retrieval instead of lexical overlap. Validate the
176
+ embedding model on a custom paraphrase test set before choosing operational thresholds.
177
+ What we use: Sentence Transformer such as all-mpnet-base-v2 or a model selected during
178
+ benchmarking; cosine similarity only for retrieval/ranking.
179
+ Expected result: Semantically related points can be retrieved even without shared keywords.
180
+ 7.2 Similar wording, opposite meaning
181
+ Problem: Adding or changing a negation can reverse the meaning while keeping most words identical.
182
+ What we do: Do not infer agreement or contradiction from embedding similarity. Use a cross-
183
+ encoder/NLI model and a stance signal after retrieval.
184
+ What we use: Sentence embeddings for retrieval; DeBERTa-family NLI/cross-encoder or equivalent for
185
+ relation analysis; explicit negation-sensitive test cases.
186
+ Expected result: Similarity answers "related?" while NLI/stance answers "what relation?".
187
+ 7.3 Context changes meaning
188
+ Problem: A phrase can only make sense because it refers to an earlier statement in the debate.
189
+ What we do: Embed and retrieve claim-level context, not isolated turns. The current claim is evaluated
190
+ together with the relevant retrieved history.
191
+ What we use: Sentence Transformer; debate-memory store; contextual claim representation.
192
+ Expected result: Pronouns and contextual references have access to the necessary prior content.
193
+ 7.4 Repetition with different vocabulary
194
+ Problem: A participant can repeat the same idea using new wording and appear to provide a new
195
+ argument.
196
+ What we do: Compare the new claim with the participant's own previous claim embeddings. Then
197
+ classify the result as repeated, rephrased, elaborated, or repeated-with-new-evidence rather than
198
+ imposing a penalty from similarity alone.
199
+ What we use: Sentence embeddings; claim history; similarity thresholds tuned on examples; optional
200
+ claim-relation classifier.
201
+ Expected result: Repetition penalties apply to genuine repeated reasoning, not legitimate elaboration.
202
+ 8. Relevant Point Retrieval and Debate Memory
203
+ Relevant Point Retrieval is the mechanism that makes the debate genuinely interactive. The system
204
+ should not assume that the current participant is responding to the immediately previous sentence. It
205
+ should retrieve the opponent points that are most relevant and, where appropriate, unresolved.
206
+ 8.1 Does the response address the opponent at all?
207
+ Problem: A participant may speak about the general topic without responding to the opponent's actual
208
+ point.
209
+ What we do: Retrieve candidate opponent claims from the debate history, rerank them with a cross-
210
+ encoder, and measure whether the current response actually addresses one or more of those claims.
211
+ What we use: Embedding retrieval followed by cross-encoder reranking; debate-history store;
212
+ argument-relation classifier.
213
+ Expected result: The system can separate "same topic" from "directly addresses opponent point".CLASH OF MINDS | CSES ML EXHIBITION
214
+ Clash of Minds - Complete Workflow and Robustness Plan
215
+ 8.2 The participant repeats an old point instead of responding to the latest point
216
+ Problem: Simply comparing the new response with the latest opponent turn can cause the system to
217
+ miss an older but still unanswered claim, or reward repeated old arguments.
218
+ What we do: Maintain explicit claim status: unanswered, partially answered, addressed, or resolved.
219
+ Retrieval ranks unresolved and relevant claims while retaining full history for context.
220
+ What we use: Debate-memory structure; claim status tracking; embeddings; recency and unresolved-
221
+ point features.
222
+ Expected result: The response is evaluated against the right debate history, not just the last sentence.
223
+ 8.3 Multiple opponent points can be addressed at once
224
+ Problem: One response may challenge two, three, or more previous claims.
225
+ What we do: Retrieve top-k candidate opponent claims, evaluate each candidate pair, and keep all
226
+ materially relevant relationships instead of forcing a single matched point.
227
+ What we use: Top-k vector retrieval; cross-encoder reranking; relation classifier.
228
+ Expected result: A response can receive separate engagement signals for multiple opponent claims.
229
+ 8.4 Pronouns and references such as "that", "this", or "your previous point"
230
+ Problem: The current sentence may be incomplete without the previous turns.
231
+ What we do: Use the recent turn window plus retrieved older claims to reconstruct the relevant
232
+ context. Preserve claim references in debate memory.
233
+ What we use: Recent context window; claim embeddings; relevant-point retrieval; optional
234
+ coreference-aware preprocessing.
235
+ Expected result: The system can associate references with the appropriate earlier claim.
236
+ 8.5 Logical relation is more nuanced than contradiction
237
+ Problem: A rebuttal may partially agree, qualify a point, introduce a limitation, or elaborate without
238
+ directly contradicting it.
239
+ What we do: Use relation labels such as support, contradict, qualify, elaborate, neutral, and unrelated.
240
+ Then derive rebuttal quality from the relation plus reasoning and evidence signals.
241
+ What we use: Cross-encoder/NLI model; debate-specific relation classifier or calibrated relation rules.
242
+ Expected result: The judge distinguishes disagreement from meaningful rebuttal.
243
+ 9. Internet RAG Fact-Verification Pipeline
244
+ The fact-checking layer is Internet-based rather than a local-only RAG database. Its job is to retrieve
245
+ evidence for checkable claims and determine whether the retrieved evidence supports, refutes,
246
+ partially supports, or fails to establish the claim. Search retrieval and verification are separate steps.
247
+ Sources should be prioritized by reliability and relevance. Suitable sources include government sites,
248
+ official institutions, research papers, reputable reference sources such as Wikipedia for general
249
+ background, and established news organizations when the claim is time-sensitive. No single source type
250
+ should be treated as universally correct for every topic.
251
+ 9.1 Search result is relevant but is not evidence
252
+ Problem: A search result can mention a topic without actually supporting the specific claim.CLASH OF MINDS | CSES ML EXHIBITION
253
+ Clash of Minds - Complete Workflow and Robustness Plan
254
+ What we do: Retrieve passages, not just URLs. Re-rank passages against the claim and only use the
255
+ passages that directly bear on the claim.
256
+ What we use: Internet search/retrieval; passage extraction; cross-encoder reranker; source metadata.
257
+ Expected result: The verifier sees claim-relevant evidence rather than a generic topic page.
258
+ 9.2 Sources disagree
259
+ Problem: Two reliable sources can report different numbers, dates, interpretations, or findings.
260
+ What we do: Retrieve multiple sources, retain conflicting evidence, and return a conflict/uncertainty
261
+ status instead of blindly selecting the first result.
262
+ What we use: Multi-source retrieval; source metadata; evidence comparison; verification model.
263
+ Expected result: The system can report conflicting evidence rather than pretending there is one certain
264
+ answer.
265
+ 9.3 Source quality varies
266
+ Problem: A random blog and a primary research report should not automatically receive equal
267
+ evidential weight.
268
+ What we do: Use source-quality rules and metadata to prioritize primary or authoritative sources. A
269
+ lower-quality source may be used as a lead but not as the sole basis for a strong verification verdict.
270
+ What we use: Source-domain allowlist/priority rules; source-type classifier; metadata scoring.
271
+ Expected result: Evidence quality becomes part of the verification result.
272
+ 9.4 Outdated information
273
+ Problem: A claim can depend on the date, especially for technology, policy, population figures, prices,
274
+ or current events.
275
+ What we do: Record source publication date and retrieval date. Prefer recent authoritative sources
276
+ when the claim is time-sensitive.
277
+ What we use: Date extraction; source metadata; query generation using time constraints when
278
+ required.
279
+ Expected result: Time-sensitive claims are not judged using stale evidence when newer authoritative
280
+ evidence exists.
281
+ 9.5 No reliable evidence found
282
+ Problem: Failure to find evidence does not prove that the participant is wrong.
283
+ What we do: Return insufficient evidence rather than refuted. Keep the evidence-quality score
284
+ conservative and continue evaluating the rest of the debate.
285
+ What we use: Retrieval confidence thresholds; verifier confidence; explicit insufficient-evidence state.
286
+ Expected result: No false certainty is introduced by a failed search.
287
+ 9.6 Partial support
288
+ Problem: A source may support only one part of a multi-part claim.
289
+ What we do: Verify each atomic claim separately and aggregate them. Do not label the entire sentence
290
+ as fully supported when only one component is supported.
291
+ What we use: Claim segmentation; per-claim retrieval; per-claim verification; aggregation logic.
292
+ Expected result: Multi-claim arguments receive claim-level evidence outcomes.CLASH OF MINDS | CSES ML EXHIBITION
293
+ Clash of Minds - Complete Workflow and Robustness Plan
294
+ 10. Fact Verification Decision Logic
295
+ The recommended output states are SUPPORTED, PARTIALLY SUPPORTED, REFUTED, INSUFFICIENT
296
+ EVIDENCE, and AMBIGUOUS. The verifier should also return evidence excerpts, source information,
297
+ and a confidence or uncertainty indicator.
298
+ 1. Extract the factual claim exactly as expressed by the participant, preserving qualifiers and numbers.
299
+ 2. Generate a focused search query from the claim. For numerical claims, include the relevant entities,
300
+ metric, and time context where available.
301
+ 3. Retrieve multiple candidate sources from the Internet.
302
+ 4. Extract relevant passages from those sources.
303
+ 5. Rank the passages against the claim using semantic retrieval followed by a more precise cross-
304
+ encoder reranker.
305
+ 6. Run claim-evidence verification using an NLI/verification model and source-quality signals.
306
+ 7. Check whether the evidence supports the entire claim, only part of it, or contradicts it.
307
+ 8. Return the verdict with evidence and uncertainty instead of forcing a binary true/false decision.
308
+ 11. Debate Scoring Layer
309
+ Scoring is a deterministic aggregation layer over several independently measured signals. The system
310
+ should not use a single model to predict a winner directly. This makes the judge easier to test, explain,
311
+ and debug.
312
+ Topic relevance - 15%: semantic relation between the topic/question and the participant's actual
313
+ claims.
314
+ Clarity - 15%: structure, readability, and coherent expression of the argument. This should not reward
315
+ unnecessarily complex vocabulary.
316
+ Logical reasoning - 20%: quality of the reasoning connecting claims to the participant's position,
317
+ supported by argument structure signals.
318
+ Counterargument / rebuttal - 20%: whether the participant directly addresses relevant opponent
319
+ claims and provides a meaningful response.
320
+ Evidence quality - 20%: quality and support of factual claims, with Internet RAG evidence and
321
+ uncertainty handling.
322
+ Stance consistency - 10%: whether the participant remains aligned with the assigned side while
323
+ allowing nuanced qualifications.
324
+ These weights are an initial engineering rubric. They should be calibrated and tested on manually
325
+ labeled examples before the exhibition rather than treated as mathematically optimal by default.
326
+ 12. Important Fairness and Interpretation Rules
327
+ 1. A contradiction is not automatically a strong rebuttal. "That is wrong" contains disagreement but little
328
+ reasoning.
329
+ 2. A true fact is not automatically a strong argument. Evidence quality and logical reasoning remain
330
+ separate dimensions.
331
+ 3. A participant should not be rewarded simply for using complicated English. Clarity and reasoning are
332
+ scored separately from vocabulary sophistication.
333
+ 4. A repeated claim should not always be penalized if the participant adds new evidence or materially
334
+ stronger reasoning.CLASH OF MINDS | CSES ML EXHIBITION
335
+ Clash of Minds - Complete Workflow and Robustness Plan
336
+ 5. A factual verification failure should not automatically decide the entire match. It primarily affects the
337
+ evidence component unless it materially changes the argument itself.
338
+ 6. Unverified claims should be labeled unverified or insufficiently supported instead of being presented
339
+ as definitively false.
340
+ 13. Live Multi-Turn Debate Workflow
341
+ 1. Round 1: Player 1 opening argument. The system evaluates topic relevance, claims, stance, reasoning,
342
+ and evidence.
343
+ 2. Round 1 response: Player 2 opening argument. The system starts building the opponent-claim graph
344
+ and unresolved-point list.
345
+ 3. Round 2: Each participant responds after seeing the opponent's previous contribution. Relevant-point
346
+ retrieval becomes active.
347
+ 4. Round 3: Participants continue with counterarguments, evidence, qualifications, and direct rebuttals.
348
+ The system checks repetition and unresolved claims.
349
+ 5. Final round: Each participant gives a closing argument. The system evaluates the final response using
350
+ the accumulated debate memory.
351
+ 6. Final score: Turn scores are aggregated with bounded penalties for repetition or unsupported claims
352
+ and without allowing one anomalous turn to dominate the entire match.
353
+ The main exhibition configuration should use a fixed number of rounds and a fixed
354
+ speaking/submission limit. This keeps the experience predictable, keeps both participants under the
355
+ same conditions, and prevents an extremely long response from dominating simply because it contains
356
+ more text.
357
+ 14. Latency Strategy
358
+ Low latency comes from architectural separation rather than removing the deeper NLP components.
359
+ The fast path handles operations that are required for immediate debate progression, while the fact-
360
+ checking path can run in parallel where practical.
361
+ 1. Preload the local NLP models once when the application starts. Do not reload models for every
362
+ participant or every turn.
363
+ 2. Use semantic embeddings to retrieve a small candidate set rather than sending the entire debate
364
+ history into an expensive cross-encoder.
365
+ 3. Use cross-encoder/NLI only on top-k relevant candidate pairs.
366
+ 4. Run factual-claim retrieval in parallel with debate-relation analysis when the backend architecture
367
+ permits it.
368
+ 5. Cache repeated fact-check queries and repeated retrieval results during the exhibition.
369
+ 6. Bound argument length and maximum claim count so inference cost cannot grow without limit.
370
+ 7. Use explicit timeouts for Internet operations. A slow web search should not freeze the entire debate
371
+ UI.
372
+ 8. If RAG is delayed, present the debate score with the evidence component marked pending/unverified,
373
+ then update the evidence result when the verification completes or when the timeout occurs.
374
+ 15. Failure Handling and Exhibition Reliability
375
+ 15.1 Internet unavailable
376
+ Problem: The RAG layer cannot retrieve new evidence.CLASH OF MINDS | CSES ML EXHIBITION
377
+ Clash of Minds - Complete Workflow and Robustness Plan
378
+ What we do: Keep the debate NLP engine operational. Mark fact verification as temporarily
379
+ unavailable and do not invent a verdict.
380
+ What we use: HTTP timeout; retry policy; pending/unverified status; cached results for repeated claims.
381
+ Expected result: A web outage affects evidence verification, not the entire match.
382
+ 15.2 Model inference failure
383
+ Problem: A model can fail because of malformed input, resource exhaustion, or an unexpected runtime
384
+ error.
385
+ What we do: Catch exceptions at the pipeline boundary, log the failing stage, and return a controlled
386
+ fallback status. The UI should remain responsive and allow a retry.
387
+ What we use: Python exception handling; structured logging; bounded input; watchdog/health checks.
388
+ Expected result: A single bad argument does not crash the application.
389
+ 15.3 Duplicate or out-of-order submissions
390
+ Problem: Fast clicks, browser retries, or multiple tabs can corrupt turn order.
391
+ What we do: Validate player ID, match ID, turn ID, and server-side turn state before accepting a
392
+ submission. Make processing idempotent for a turn ID.
393
+ What we use: FastAPI validation; unique turn IDs; server-side state machine; database or in-memory
394
+ state store.
395
+ Expected result: Only one valid result is committed per turn.
396
+ 15.4 Browser refresh or participant abandonment
397
+ Problem: The page may reload or a participant may leave before finishing.
398
+ What we do: Store active match state on the backend, provide an operator reset, and expire abandoned
399
+ matches after a timeout.
400
+ What we use: Backend session state; reset endpoint; inactivity timeout.
401
+ Expected result: The system can recover without restarting the application.
402
+ 15.5 Long-running memory growth
403
+ Problem: Repeated matches can accumulate embeddings, transcripts, cache entries, or temporary
404
+ objects.
405
+ What we do: Separate persistent model state from per-match state. Bound caches and histories. Delete
406
+ match-specific objects on reset and monitor RAM/VRAM during stress testing.
407
+ What we use: Explicit match state object; cache size limits; Python garbage collection where needed;
408
+ GPU cache management if applicable.
409
+ Expected result: Memory use stays bounded across many matches.
410
+ 15.6 Search rate limits
411
+ Problem: A five-to-six-hour exhibition can generate many Internet searches.
412
+ What we do: Cache repeated claims, combine related retrieval where possible, cap requests per turn,
413
+ and handle rate-limit responses without crashing the system.
414
+ What we use: Caching; request counters; backoff; timeout and error states.
415
+ Expected result: The fact-checking subsystem degrades gracefully under API or web limits.CLASH OF MINDS | CSES ML EXHIBITION
416
+ Clash of Minds - Complete Workflow and Robustness Plan
417
+ 16. Debate Memory Design
418
+ The debate memory should be structured rather than a raw transcript. Each participant has a claim
419
+ history, each opponent claim has a response status, and each claim may have associated evidence and
420
+ relation labels.
421
+ Topic state: topic text, proposition, assigned stance for each player.
422
+ Claim state: claim text, player, turn, claim type, embedding, stance, verification status.
423
+ Response state: which opponent claims are addressed, partially addressed, or still unanswered.
424
+ Evidence state: retrieved sources, evidence passages, verification verdict, source date, and verification
425
+ confidence.
426
+ Scoring state: per-turn criterion values and aggregate score.
427
+ On reset, all match-specific state is cleared while model weights and static configuration remain loaded.
428
+ This is the key distinction between a persistent application process and a temporary debate session.
429
+ 17. Secondary One-Shot Mode
430
+ The system can also support a simpler mode in which both participants submit a longer opening
431
+ argument and the system evaluates them without live rebuttal. This mode should be treated as a backup
432
+ or optional demonstration mode, not as the flagship experience, because it does not exercise the full
433
+ relevant-point retrieval and cross-turn reasoning pipeline.
434
+ In one-shot mode, the same claim segmentation, semantic embedding, RAG verification, stance, and
435
+ scoring components remain usable. Only the live debate memory and response-to-opponent logic
436
+ become less important.
437
+ 18. Proposed Technology and Model Stack
438
+ The exact model versions should be finalized only after benchmarking on the robustness test set. The
439
+ following stack is the initial engineering proposal.
440
+ Speech-to-text: a tested speech recognition engine; browser Web Speech API can be the first prototype,
441
+ with a more controllable ASR option evaluated for exhibition deployment.
442
+ Semantic embeddings: Sentence Transformers, initially benchmark all-mpnet-base-v2 against a
443
+ smaller faster alternative if latency requires it.
444
+ Cross-encoder / NLI: a DeBERTa-family model trained for NLI or an equivalent cross-encoder,
445
+ benchmarked on negation, contradiction, qualification, and neutral relations.
446
+ Claim segmentation: a transformer-based classifier/sequence labeling approach plus deterministic
447
+ preprocessing rules for sentence boundaries. Exact model chosen after testing multi-claim examples.
448
+ Relevant point retrieval: embedding retrieval followed by top-k cross-encoder reranking, with debate-
449
+ memory status features.
450
+ RAG retrieval: Internet search/retrieval, source filtering, passage extraction, semantic retrieval, and
451
+ cross-encoder reranking.
452
+ Fact verification: NLI/claim-evidence verification model plus source-quality and scope checks.
453
+ Backend: FastAPI with asynchronous endpoints and WebSocket updates for the live interface.
454
+ Frontend: React/Vite or equivalent web interface with transcript display, timers, turn controls, and
455
+ score panels.
456
+ Storage: SQLite or another lightweight store for match results, with in-memory active debate state.CLASH OF MINDS | CSES ML EXHIBITION
457
+ Clash of Minds - Complete Workflow and Robustness Plan
458
+ 19. Core Libraries
459
+  FastAPI, Uvicorn, Pydantic, WebSockets / asyncio for backend control and live updates.
460
+  PyTorch and Hugging Face Transformers for neural inference.
461
+  Sentence Transformers and scikit-learn for embeddings, cosine similarity, and evaluation.
462
+  NumPy for vector operations and numerical processing.
463
+  FAISS or another local in-process index only for fast retrieval over the active debate history; it is not
464
+ the factual knowledge base.
465
+  Requests/httpx and HTML parsing tools for Internet evidence retrieval.
466
+  PyMuPDF where PDF-based web evidence needs text extraction.
467
+  RapidFuzz for lightweight lexical duplicate detection alongside semantic comparison.
468
+  SQLite / sqlite3 for match logs and results.
469
+  Pytest and HTTPX for unit, integration, and API testing.
470
+  Optional ONNX Runtime / Optimum after the baseline pipeline is measured and optimization targets
471
+ are known.
472
+ 20. Robustness Test Plan Before Exhibition
473
+ The project should not go directly from coding to exhibition. A dedicated robustness dataset should be
474
+ created from manually written and reviewed examples that represent the situations visitors are likely
475
+ to produce.
476
+ 1. Paraphrase cases: different vocabulary with the same meaning.
477
+ 2. Negation cases: identical wording with a change in polarity.
478
+ 3. Context-reference cases: pronouns and phrases referring to previous turns.
479
+ 4. Repeated-claim cases: same idea rewritten, with and without new evidence.
480
+ 5. Multi-claim cases: 2, 3, 4, and more claims in one response.
481
+ 6. Fact/opinion cases: mixed checkable and non-checkable statements.
482
+ 7. Conditional cases: if, may, might, only if, unless, and similar qualifiers.
483
+ 8. Statistical cases: exact numbers with varying context or source quality.
484
+ 9. Rhetorical-question cases: argumentive questions that should not be treated as literal facts.
485
+ 10. Rebuttal cases: directly addressed, partially addressed, unrelated, and old-unanswered opponent
486
+ points.
487
+ 11. Multiple-point cases: one response intentionally addresses several previous opponent claims.
488
+ 12. Evidence cases: supported, refuted, partially supported, conflicting, and insufficient-evidence claims.
489
+ 13. Voice cases: controlled accent variation, background noise, speech speed changes, and negation-
490
+ sensitive phrases.
491
+ 14. System cases: duplicate submission, refresh, reset, timeout, Internet loss, and repeated-match
492
+ memory growth.
493
+ Evaluation should track accuracy/F1 for classifiers and relation labels, retrieval recall for relevant point
494
+ retrieval, verification precision/recall for fact-checking, word error rate for speech recognition where
495
+ applicable, and latency/RAM/VRAM across repeated matches. Exact target values should be established
496
+ after the baseline measurements rather than invented in advance.
497
+ 21. Final End-to-End Workflow
498
+ 1. A new match is created and the topic plus opposing sides are fixed.
499
+ 2. A participant selects text or voice input.CLASH OF MINDS | CSES ML EXHIBITION
500
+ Clash of Minds - Complete Workflow and Robustness Plan
501
+ 3. If voice is selected, speech-to-text creates a transcript; the participant reviews and confirms or edits it.
502
+ 4. The backend validates the submission and assigns a unique turn ID.
503
+ 5. Claim Segmentation identifies each argument unit and classifies whether it is factual, opinion-based,
504
+ conditional, rhetorical, statistical, or otherwise.
505
+ 6. The Semantic Embedding Model encodes the topic, current claims, and debate-history claims.
506
+ 7. Topic relevance and semantic retrieval use the embeddings to find the most relevant historical points
507
+ without relying on exact vocabulary overlap.
508
+ 8. Relevant Point Retrieval selects candidate opponent claims and candidate own claims. It considers
509
+ semantic similarity, recency, and whether a point is still unanswered or partially answered.
510
+ 9. A cross-encoder/NLI stage deeply compares the current response with the selected opponent claims
511
+ and classifies relations such as support, contradiction, qualification, elaboration, neutral, or
512
+ unrelated.
513
+ 10. The system separately checks stance consistency and semantic repetition against the participant's
514
+ own history.
515
+ 11. Every checkable factual claim enters the Internet RAG path: focused search, multi-source retrieval,
516
+ passage extraction, evidence reranking, claim-evidence verification, and source-quality assessment.
517
+ 12. The scoring engine combines relevance, clarity, reasoning, rebuttal, evidence, stance consistency,
518
+ and repetition signals into a turn score.
519
+ 13. The interface displays concise feedback and the score, while the backend updates debate memory.
520
+ 14. The next participant turn repeats the process using the updated history.
521
+ 15. After the final round, the system aggregates the turn scores, presents the final scorecard and
522
+ leaderboard, and records the result.
523
+ 16. The operator resets the match. All participant-specific memory, claims, temporary evidence, and
524
+ scores are cleared while loaded models remain in memory for rapid reuse.
525
+ 22. What We Will Deliberately NOT Do
526
+  We will not use cosine similarity alone to determine contradiction, agreement, or debate quality.
527
+  We will not treat the first web search result as proof of a factual claim.
528
+  We will not send every long argument directly into one monolithic model and expect a single
529
+ winner score.
530
+  We will not force every sentence into true/false when evidence is incomplete or the statement is an
531
+ opinion or prediction.
532
+  We will not penalize participants for accent, vocabulary complexity, or a speech-recognition error
533
+ that the participant can correct.
534
+  We will not reload the NLP models after every match.
535
+  We will not claim 0 percent error. Instead, we will demonstrate measured robustness on a defined
536
+ test set and provide safe uncertainty behavior for cases the system cannot confidently resolve.
537
+ 23. Recommended Build Order
538
+ 1. Build and benchmark semantic embeddings on paraphrase, relevance, negation, and repetition
539
+ examples.
540
+ 2. Build claim segmentation and claim-type classification using manually labeled multi-claim examples.
541
+ 3. Build relevant point retrieval over a small simulated debate history and validate that the correct
542
+ opponent points are retrieved.CLASH OF MINDS | CSES ML EXHIBITION
543
+ Clash of Minds - Complete Workflow and Robustness Plan
544
+ 4. Add cross-encoder/NLI relation analysis and test support, contradiction, qualification, and unrelated
545
+ examples.
546
+ 5. Build the Internet RAG fact-checking prototype independently. Validate evidence retrieval before
547
+ connecting it to scoring.
548
+ 6. Create the scoring engine and calibrate weights/thresholds against human-labeled examples.
549
+ 7. Connect the three NLP pipelines, relation analysis, RAG, and debate memory into the backend.
550
+ 8. Add voice input and transcript confirmation.
551
+ 9. Build the live frontend and fixed-round debate flow.
552
+ 10. Perform long-run stress tests with repeated matches, Internet failures, duplicate submissions, resets,
553
+ and memory monitoring.
554
+ 11. Only after the baseline passes the robustness tests, add ONNX or other optimization if measured
555
+ latency justifies it.
556
+ 24. Exhibition Readiness Checklist
557
+  A clean topic list with clearly worded propositions and fixed For/Against assignments.
558
+  A tested speech-to-text path plus reliable text fallback.
559
+  A visible transcript correction step for spoken input.
560
+  Fixed round count and timers so both participants receive the same interaction conditions.
561
+  Claim-level semantic analysis and debate-memory tracking.
562
+  Relevant-point retrieval that can explain which opponent claim a response addressed.
563
+  Internet RAG with multiple-source retrieval and clear insufficient-evidence handling.
564
+  Fast-path debate scoring that does not freeze when web retrieval is slow.
565
+  Per-match reset and operator recovery controls.
566
+  Logging, health checks, request timeouts, and repeated-match stress-test results.
567
+  A robustness report showing performance on paraphrase, negation, multi-claim, retrieval, fact-
568
+ checking, voice, and failure cases.
569
+ 25. Final Project Position
570
+ Clash of Minds should be presented as a modular NLP judging system rather than a single "AI judge"
571
+ model. The strongest part of the architecture is the separation of responsibilities: semantic embeddings
572
+ handle meaning-aware retrieval; claim segmentation creates atomic units; relevant point retrieval
573
+ connects the response to the real debate history; NLI/argument-relation analysis determines the
574
+ relationship between claims; Internet RAG verifies factual assertions; and a deterministic scoring layer
575
+ combines these signals into a structured judgment.
576
+ This architecture is intentionally designed around the real-world failure cases expected at a live
577
+ exhibition. It keeps the main debate interaction fast, gives the fact-checker access to broad Internet
578
+ information, prevents individual failures from taking down the entire application, and keeps match-
579
+ specific memory isolated so the same system can run repeatedly throughout the exhibition.
frontend/start_backend_wsl.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Clash of Minds — WSL Startup Script
3
+ # Run this inside Ubuntu/WSL terminal
4
+
5
+ echo "🧠 Clash of Minds — Starting Backend..."
6
+
7
+ cd /mnt/d/Debate
8
+
9
+ # Create venv in Linux home directory to avoid Windows NTFS permission issues
10
+ VENV_PATH="$HOME/.debate_venv"
11
+
12
+ if [ ! -d "$VENV_PATH" ]; then
13
+ echo "[1/3] Creating Python virtual environment..."
14
+ sudo apt install python3-full -y
15
+ python3 -m venv $VENV_PATH
16
+ source $VENV_PATH/bin/activate
17
+ echo "[2/3] Installing dependencies..."
18
+ pip install -r backend/requirements.txt
19
+ else
20
+ source $VENV_PATH/bin/activate
21
+ fi
22
+
23
+ echo "[3/3] Starting FastAPI backend on port 8000..."
24
+ cd backend
25
+ python3 -m uvicorn main:app --host 0.0.0.0 --port 8000
frontend/start_debate.bat ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ echo Starting Clash of Minds AI Debate System...
3
+
4
+ echo.
5
+ echo [1/2] Starting FastAPI Backend via WSL (Linux)...
6
+ start cmd /k "wsl bash /mnt/d/Debate/start_backend_wsl.sh"
7
+
8
+ echo [2/2] Starting Frontend HTTP Server on port 8080...
9
+ start cmd /k "cd /d d:\Debate\frontend && python -m http.server 8080"
10
+
11
+ echo.
12
+ echo Servers are starting up in new windows.
13
+ echo Please wait 30-60 seconds for the AI models to load.
14
+ echo.
15
+ echo Opening browser to http://localhost:8080...
16
+ timeout /t 10 > nul
17
+ start http://localhost:8080
18
+
19
+ echo Done! You can close this window.
frontend/style.css ADDED
@@ -0,0 +1,1664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* =========================================================
2
+ Clash of Minds — Premium Dark Glassmorphism Design
3
+ CSES ML Exhibition | NIT Warangal
4
+ ========================================================= */
5
+
6
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=Space+Grotesk:wght@400;500;600;700&display=swap');
7
+
8
+ /* ── Design Tokens ─────────────────────────────────────── */
9
+ :root {
10
+ /* Color palette */
11
+ --bg-deep: #050a12;
12
+ --bg-dark: #080e1a;
13
+ --bg-card: rgba(13, 21, 38, 0.75);
14
+ --bg-card-hover: rgba(18, 28, 50, 0.85);
15
+ --bg-glass: rgba(255, 255, 255, 0.04);
16
+ --bg-input: rgba(10, 18, 32, 0.9);
17
+
18
+ --accent-blue: #3b82f6;
19
+ --accent-cyan: #06b6d4;
20
+ --accent-purple: #8b5cf6;
21
+ --accent-amber: #f59e0b;
22
+ --accent-green: #10b981;
23
+ --accent-red: #ef4444;
24
+ --accent-rose: #f43f5e;
25
+
26
+ --p1-color: #3b82f6; /* Player 1: Blue (FOR) */
27
+ --p2-color: #f43f5e; /* Player 2: Rose (AGAINST) */
28
+
29
+ --text-primary: #f0f6ff;
30
+ --text-secondary:#8ba3c7;
31
+ --text-muted: #4a6080;
32
+
33
+ --border: rgba(59, 130, 246, 0.18);
34
+ --border-glow: rgba(59, 130, 246, 0.40);
35
+
36
+ /* Gradients */
37
+ --gradient-blue: linear-gradient(135deg, #1e3a5f 0%, #0f1e3a 100%);
38
+ --gradient-hero: linear-gradient(135deg, #0a0f1e 0%, #0d1730 50%, #060c18 100%);
39
+ --gradient-p1: linear-gradient(135deg, #1d3461, #2563eb);
40
+ --gradient-p2: linear-gradient(135deg, #3d0a1a, #f43f5e);
41
+ --gradient-accent: linear-gradient(90deg, #3b82f6, #8b5cf6);
42
+ --gradient-score: linear-gradient(90deg, #10b981, #3b82f6);
43
+
44
+ /* Shadows */
45
+ --shadow-card: 0 8px 32px rgba(0,0,0,0.5), 0 0 0 1px rgba(59,130,246,0.10);
46
+ --shadow-glow: 0 0 40px rgba(59,130,246,0.20), 0 0 80px rgba(59,130,246,0.08);
47
+ --shadow-btn: 0 4px 20px rgba(59,130,246,0.30);
48
+
49
+ /* Spacing & radius */
50
+ --radius-sm: 8px;
51
+ --radius-md: 14px;
52
+ --radius-lg: 20px;
53
+ --radius-xl: 28px;
54
+
55
+ /* Animation */
56
+ --transition: 0.25s cubic-bezier(0.4, 0, 0.2, 1);
57
+ }
58
+
59
+ /* ── Reset & Base ──────────────────────────────────────── */
60
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
61
+
62
+ html { scroll-behavior: smooth; }
63
+
64
+ body {
65
+ font-family: 'Inter', system-ui, sans-serif;
66
+ background: var(--bg-deep);
67
+ color: var(--text-primary);
68
+ min-height: 100vh;
69
+ line-height: 1.6;
70
+ overflow-x: hidden;
71
+ }
72
+
73
+ /* Animated background grid */
74
+ body::before {
75
+ content: '';
76
+ position: fixed;
77
+ inset: 0;
78
+ background-image:
79
+ linear-gradient(rgba(59,130,246,0.04) 1px, transparent 1px),
80
+ linear-gradient(90deg, rgba(59,130,246,0.04) 1px, transparent 1px);
81
+ background-size: 40px 40px;
82
+ pointer-events: none;
83
+ z-index: 0;
84
+ }
85
+
86
+ /* Ambient glow orbs */
87
+ body::after {
88
+ content: '';
89
+ position: fixed;
90
+ top: -20%;
91
+ left: -10%;
92
+ width: 70vw;
93
+ height: 70vw;
94
+ border-radius: 50%;
95
+ background: radial-gradient(circle, rgba(59,130,246,0.06) 0%, transparent 70%);
96
+ pointer-events: none;
97
+ z-index: 0;
98
+ animation: drift 20s ease-in-out infinite;
99
+ }
100
+
101
+ @keyframes drift {
102
+ 0%, 100% { transform: translate(0, 0); }
103
+ 50% { transform: translate(5vw, 3vh); }
104
+ }
105
+
106
+ /* ── Layout ────────────────────────────────────────────── */
107
+ #app {
108
+ position: relative;
109
+ z-index: 1;
110
+ min-height: 100vh;
111
+ display: flex;
112
+ flex-direction: column;
113
+ }
114
+
115
+ .container {
116
+ max-width: 1280px;
117
+ margin: 0 auto;
118
+ padding: 0 24px;
119
+ width: 100%;
120
+ }
121
+
122
+ /* ── Screens ───────────────────────────────────────────── */
123
+ .screen {
124
+ display: none;
125
+ min-height: 100vh;
126
+ }
127
+ .screen.active { display: flex; flex-direction: column; }
128
+
129
+ /* ── Header / Nav ──────────────────────────────────────── */
130
+ .top-bar {
131
+ display: flex;
132
+ align-items: center;
133
+ justify-content: space-between;
134
+ padding: 18px 32px;
135
+ border-bottom: 1px solid var(--border);
136
+ background: rgba(5,10,18,0.85);
137
+ backdrop-filter: blur(12px);
138
+ position: sticky;
139
+ top: 0;
140
+ z-index: 100;
141
+ }
142
+
143
+ .logo {
144
+ display: flex;
145
+ align-items: center;
146
+ gap: 12px;
147
+ }
148
+
149
+ .logo-icon {
150
+ width: 40px;
151
+ height: 40px;
152
+ border-radius: 10px;
153
+ background: var(--gradient-accent);
154
+ display: flex;
155
+ align-items: center;
156
+ justify-content: center;
157
+ font-size: 18px;
158
+ box-shadow: 0 0 20px rgba(59,130,246,0.4);
159
+ }
160
+
161
+ .logo-text {
162
+ font-family: 'Space Grotesk', sans-serif;
163
+ font-weight: 700;
164
+ font-size: 18px;
165
+ background: var(--gradient-accent);
166
+ -webkit-background-clip: text;
167
+ -webkit-text-fill-color: transparent;
168
+ background-clip: text;
169
+ }
170
+
171
+ .logo-sub {
172
+ font-size: 10px;
173
+ color: var(--text-muted);
174
+ letter-spacing: 0.1em;
175
+ text-transform: uppercase;
176
+ }
177
+
178
+ .status-badge {
179
+ display: flex;
180
+ align-items: center;
181
+ gap: 6px;
182
+ padding: 6px 14px;
183
+ border-radius: 20px;
184
+ border: 1px solid var(--border);
185
+ background: var(--bg-glass);
186
+ font-size: 12px;
187
+ color: var(--text-secondary);
188
+ }
189
+
190
+ .status-dot {
191
+ width: 6px;
192
+ height: 6px;
193
+ border-radius: 50%;
194
+ background: var(--accent-green);
195
+ animation: pulse-dot 2s ease-in-out infinite;
196
+ }
197
+
198
+ @keyframes pulse-dot {
199
+ 0%, 100% { opacity: 1; transform: scale(1); }
200
+ 50% { opacity: 0.5; transform: scale(0.8); }
201
+ }
202
+
203
+ /* ── Setup Screen ──────────────────────────────────────── */
204
+ #setup-screen {
205
+ align-items: center;
206
+ justify-content: center;
207
+ padding: 60px 24px;
208
+ }
209
+
210
+ .setup-hero {
211
+ text-align: center;
212
+ margin-bottom: 60px;
213
+ }
214
+
215
+ .setup-hero h1 {
216
+ font-family: 'Space Grotesk', sans-serif;
217
+ font-size: clamp(3rem, 8vw, 6rem);
218
+ font-weight: 800;
219
+ line-height: 1.1;
220
+ letter-spacing: -0.03em;
221
+ }
222
+
223
+ .setup-hero h1 .word-clash {
224
+ background: var(--gradient-accent);
225
+ -webkit-background-clip: text;
226
+ -webkit-text-fill-color: transparent;
227
+ background-clip: text;
228
+ }
229
+
230
+ .setup-hero h1 .word-minds {
231
+ background: linear-gradient(135deg, #f0f6ff, #8ba3c7);
232
+ -webkit-background-clip: text;
233
+ -webkit-text-fill-color: transparent;
234
+ background-clip: text;
235
+ }
236
+
237
+ .setup-hero .tagline {
238
+ font-size: 16px;
239
+ color: var(--text-secondary);
240
+ margin-top: 16px;
241
+ letter-spacing: 0.05em;
242
+ }
243
+
244
+ .setup-hero .tagline span {
245
+ color: var(--accent-cyan);
246
+ font-weight: 600;
247
+ }
248
+
249
+ .setup-card {
250
+ background: var(--bg-card);
251
+ border: 1px solid var(--border);
252
+ border-radius: var(--radius-xl);
253
+ padding: 48px;
254
+ width: 100%;
255
+ max-width: 680px;
256
+ box-shadow: var(--shadow-card);
257
+ backdrop-filter: blur(20px);
258
+ position: relative;
259
+ overflow: hidden;
260
+ }
261
+
262
+ .setup-card::before {
263
+ content: '';
264
+ position: absolute;
265
+ top: 0; left: 0; right: 0;
266
+ height: 2px;
267
+ background: var(--gradient-accent);
268
+ }
269
+
270
+ .setup-card h2 {
271
+ font-family: 'Space Grotesk', sans-serif;
272
+ font-size: 22px;
273
+ font-weight: 700;
274
+ margin-bottom: 32px;
275
+ color: var(--text-primary);
276
+ }
277
+
278
+ .setup-grid {
279
+ display: grid;
280
+ grid-template-columns: 1fr 1fr;
281
+ gap: 20px;
282
+ margin-bottom: 20px;
283
+ }
284
+
285
+ .field-group {
286
+ display: flex;
287
+ flex-direction: column;
288
+ gap: 8px;
289
+ }
290
+
291
+ .field-group label {
292
+ font-size: 12px;
293
+ font-weight: 600;
294
+ letter-spacing: 0.08em;
295
+ text-transform: uppercase;
296
+ color: var(--text-secondary);
297
+ }
298
+
299
+ .field-group.p1-field label { color: var(--p1-color); }
300
+ .field-group.p2-field label { color: var(--p2-color); }
301
+
302
+ .player-badge {
303
+ display: inline-block;
304
+ padding: 2px 10px;
305
+ border-radius: 20px;
306
+ font-size: 10px;
307
+ font-weight: 700;
308
+ letter-spacing: 0.1em;
309
+ margin-left: 8px;
310
+ }
311
+
312
+ .p1-badge { background: rgba(59,130,246,0.2); color: var(--p1-color); }
313
+ .p2-badge { background: rgba(244,63,94,0.2); color: var(--p2-color); }
314
+
315
+ .input-field {
316
+ padding: 12px 16px;
317
+ background: var(--bg-input);
318
+ border: 1px solid var(--border);
319
+ border-radius: var(--radius-sm);
320
+ color: var(--text-primary);
321
+ font-family: 'Inter', sans-serif;
322
+ font-size: 14px;
323
+ outline: none;
324
+ transition: var(--transition);
325
+ width: 100%;
326
+ }
327
+
328
+ .input-field:focus {
329
+ border-color: var(--accent-blue);
330
+ box-shadow: 0 0 0 3px rgba(59,130,246,0.15);
331
+ }
332
+
333
+ .topic-field { grid-column: 1 / -1; }
334
+ .topic-field .input-field {
335
+ font-size: 15px;
336
+ padding: 14px 18px;
337
+ min-height: 80px;
338
+ resize: none;
339
+ }
340
+
341
+ .rounds-row {
342
+ display: flex;
343
+ align-items: center;
344
+ gap: 12px;
345
+ margin-bottom: 24px;
346
+ }
347
+
348
+ .rounds-row label {
349
+ font-size: 12px;
350
+ font-weight: 600;
351
+ text-transform: uppercase;
352
+ letter-spacing: 0.08em;
353
+ color: var(--text-secondary);
354
+ white-space: nowrap;
355
+ }
356
+
357
+ .rounds-select {
358
+ background: var(--bg-input);
359
+ border: 1px solid var(--border);
360
+ border-radius: var(--radius-sm);
361
+ color: var(--text-primary);
362
+ font-family: 'Inter', sans-serif;
363
+ font-size: 14px;
364
+ padding: 10px 14px;
365
+ outline: none;
366
+ cursor: pointer;
367
+ }
368
+
369
+ .side-display {
370
+ display: grid;
371
+ grid-template-columns: 1fr 1fr;
372
+ gap: 12px;
373
+ margin-bottom: 28px;
374
+ }
375
+
376
+ .side-card {
377
+ padding: 16px;
378
+ border-radius: var(--radius-md);
379
+ border: 1px solid;
380
+ display: flex;
381
+ align-items: center;
382
+ gap: 10px;
383
+ font-size: 13px;
384
+ font-weight: 600;
385
+ }
386
+
387
+ .side-card.for-side {
388
+ background: rgba(59,130,246,0.08);
389
+ border-color: rgba(59,130,246,0.30);
390
+ color: var(--p1-color);
391
+ }
392
+
393
+ .side-card.against-side {
394
+ background: rgba(244,63,94,0.08);
395
+ border-color: rgba(244,63,94,0.30);
396
+ color: var(--p2-color);
397
+ }
398
+
399
+ .side-icon { font-size: 20px; }
400
+
401
+ /* ── Buttons ───────────────────────────────────────────── */
402
+ .btn {
403
+ display: inline-flex;
404
+ align-items: center;
405
+ justify-content: center;
406
+ gap: 8px;
407
+ padding: 14px 28px;
408
+ border: none;
409
+ border-radius: var(--radius-md);
410
+ font-family: 'Inter', sans-serif;
411
+ font-size: 14px;
412
+ font-weight: 600;
413
+ cursor: pointer;
414
+ transition: var(--transition);
415
+ letter-spacing: 0.02em;
416
+ }
417
+
418
+ .btn:disabled { opacity: 0.45; cursor: not-allowed; }
419
+
420
+ .btn-primary {
421
+ background: var(--gradient-accent);
422
+ color: white;
423
+ box-shadow: var(--shadow-btn);
424
+ width: 100%;
425
+ padding: 16px;
426
+ font-size: 16px;
427
+ }
428
+
429
+ .btn-primary:hover:not(:disabled) {
430
+ transform: translateY(-2px);
431
+ box-shadow: 0 6px 30px rgba(59,130,246,0.45);
432
+ }
433
+
434
+ .btn-voice {
435
+ background: rgba(139,92,246,0.15);
436
+ color: var(--accent-purple);
437
+ border: 1px solid rgba(139,92,246,0.30);
438
+ border-radius: 50px;
439
+ padding: 10px 20px;
440
+ font-size: 13px;
441
+ }
442
+
443
+ .btn-voice:hover:not(:disabled) {
444
+ background: rgba(139,92,246,0.25);
445
+ }
446
+
447
+ .btn-voice.recording {
448
+ background: rgba(239,68,68,0.15);
449
+ color: var(--accent-red);
450
+ border-color: rgba(239,68,68,0.40);
451
+ animation: recording-pulse 1.5s ease-in-out infinite;
452
+ }
453
+
454
+ @keyframes recording-pulse {
455
+ 0%, 100% { box-shadow: 0 0 0 0 rgba(239,68,68,0.3); }
456
+ 50% { box-shadow: 0 0 0 8px rgba(239,68,68,0); }
457
+ }
458
+
459
+ .btn-submit {
460
+ background: var(--gradient-accent);
461
+ color: white;
462
+ box-shadow: var(--shadow-btn);
463
+ border-radius: 50px;
464
+ padding: 12px 28px;
465
+ }
466
+
467
+ .btn-submit:hover:not(:disabled) {
468
+ transform: translateY(-1px);
469
+ box-shadow: 0 6px 25px rgba(59,130,246,0.40);
470
+ }
471
+
472
+ .btn-reset {
473
+ background: rgba(239,68,68,0.12);
474
+ color: var(--accent-red);
475
+ border: 1px solid rgba(239,68,68,0.25);
476
+ font-size: 13px;
477
+ padding: 10px 20px;
478
+ }
479
+
480
+ .btn-reset:hover { background: rgba(239,68,68,0.20); }
481
+
482
+ .btn-icon { font-size: 16px; }
483
+
484
+ /* ── Debate Screen ─────────────────────────────────────── */
485
+ #debate-screen {
486
+ flex-direction: column;
487
+ }
488
+
489
+ .debate-header {
490
+ display: flex;
491
+ align-items: center;
492
+ justify-content: space-between;
493
+ padding: 16px 28px;
494
+ background: rgba(5,10,18,0.90);
495
+ border-bottom: 1px solid var(--border);
496
+ backdrop-filter: blur(12px);
497
+ gap: 16px;
498
+ flex-wrap: wrap;
499
+ }
500
+
501
+ .topic-display {
502
+ flex: 1;
503
+ text-align: center;
504
+ }
505
+
506
+ .topic-label {
507
+ font-size: 10px;
508
+ letter-spacing: 0.12em;
509
+ text-transform: uppercase;
510
+ color: var(--text-muted);
511
+ margin-bottom: 2px;
512
+ }
513
+
514
+ .topic-text {
515
+ font-family: 'Space Grotesk', sans-serif;
516
+ font-size: 15px;
517
+ font-weight: 600;
518
+ color: var(--text-primary);
519
+ max-width: 500px;
520
+ margin: 0 auto;
521
+ }
522
+
523
+ .round-indicator {
524
+ display: flex;
525
+ align-items: center;
526
+ gap: 8px;
527
+ padding: 8px 16px;
528
+ border-radius: 20px;
529
+ background: var(--bg-glass);
530
+ border: 1px solid var(--border);
531
+ }
532
+
533
+ .round-dots {
534
+ display: flex;
535
+ gap: 4px;
536
+ }
537
+
538
+ .round-dot {
539
+ width: 8px;
540
+ height: 8px;
541
+ border-radius: 50%;
542
+ background: var(--text-muted);
543
+ transition: var(--transition);
544
+ }
545
+ .round-dot.active {
546
+ background: var(--accent-cyan);
547
+ box-shadow: 0 0 8px var(--accent-cyan);
548
+ }
549
+ .round-dot.done { background: var(--accent-blue); }
550
+
551
+ /* ── Main Debate Layout ────────────────────────────────── */
552
+ .debate-main {
553
+ flex: 1;
554
+ display: grid;
555
+ grid-template-columns: 280px 1fr 320px;
556
+ gap: 0;
557
+ overflow: hidden;
558
+ }
559
+
560
+ /* ── Player Panels (side columns) ──────────────────────── */
561
+ .player-panel {
562
+ display: flex;
563
+ flex-direction: column;
564
+ border-right: 1px solid var(--border);
565
+ overflow-y: auto;
566
+ padding: 20px;
567
+ gap: 16px;
568
+ }
569
+
570
+ .player-panel.p2-panel {
571
+ border-right: none;
572
+ border-left: 1px solid var(--border);
573
+ }
574
+
575
+ .player-header {
576
+ padding: 18px;
577
+ border-radius: var(--radius-md);
578
+ text-align: center;
579
+ position: relative;
580
+ overflow: hidden;
581
+ }
582
+
583
+ .player-panel.p1-panel .player-header {
584
+ background: linear-gradient(135deg, rgba(37,99,235,0.15), rgba(59,130,246,0.06));
585
+ border: 1px solid rgba(59,130,246,0.25);
586
+ }
587
+
588
+ .player-panel.p2-panel .player-header {
589
+ background: linear-gradient(135deg, rgba(244,63,94,0.15), rgba(239,68,68,0.06));
590
+ border: 1px solid rgba(244,63,94,0.25);
591
+ }
592
+
593
+ .player-name {
594
+ font-family: 'Space Grotesk', sans-serif;
595
+ font-size: 18px;
596
+ font-weight: 700;
597
+ margin-bottom: 4px;
598
+ }
599
+
600
+ .p1-panel .player-name { color: var(--p1-color); }
601
+ .p2-panel .player-name { color: var(--p2-color); }
602
+
603
+ .player-side-tag {
604
+ display: inline-block;
605
+ padding: 3px 12px;
606
+ border-radius: 20px;
607
+ font-size: 10px;
608
+ font-weight: 700;
609
+ letter-spacing: 0.1em;
610
+ text-transform: uppercase;
611
+ margin-bottom: 16px;
612
+ }
613
+
614
+ .p1-panel .player-side-tag { background: rgba(59,130,246,0.2); color: var(--p1-color); }
615
+ .p2-panel .player-side-tag { background: rgba(244,63,94,0.2); color: var(--p2-color); }
616
+
617
+ .total-score-display {
618
+ text-align: center;
619
+ }
620
+
621
+ .total-score-num {
622
+ font-family: 'Space Grotesk', sans-serif;
623
+ font-size: 36px;
624
+ font-weight: 800;
625
+ line-height: 1;
626
+ }
627
+
628
+ .p1-panel .total-score-num { color: var(--p1-color); }
629
+ .p2-panel .total-score-num { color: var(--p2-color); }
630
+
631
+ .total-score-label {
632
+ font-size: 10px;
633
+ text-transform: uppercase;
634
+ letter-spacing: 0.1em;
635
+ color: var(--text-muted);
636
+ margin-top: 2px;
637
+ }
638
+
639
+ /* Score bars */
640
+ .score-bars {
641
+ display: flex;
642
+ flex-direction: column;
643
+ gap: 10px;
644
+ }
645
+
646
+ .score-bar-item {
647
+ display: flex;
648
+ flex-direction: column;
649
+ gap: 4px;
650
+ }
651
+
652
+ .score-bar-label {
653
+ display: flex;
654
+ justify-content: space-between;
655
+ font-size: 11px;
656
+ color: var(--text-secondary);
657
+ }
658
+
659
+ .score-bar-track {
660
+ height: 5px;
661
+ background: rgba(255,255,255,0.06);
662
+ border-radius: 3px;
663
+ overflow: hidden;
664
+ }
665
+
666
+ .score-bar-fill {
667
+ height: 100%;
668
+ border-radius: 3px;
669
+ background: var(--gradient-score);
670
+ transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
671
+ width: 0%;
672
+ }
673
+
674
+ .p2-panel .score-bar-fill {
675
+ background: linear-gradient(90deg, #f43f5e, #f59e0b);
676
+ }
677
+
678
+ /* Turn history log */
679
+ .turn-history {
680
+ flex: 1;
681
+ overflow-y: auto;
682
+ display: flex;
683
+ flex-direction: column;
684
+ gap: 8px;
685
+ }
686
+
687
+ .turn-history-title {
688
+ font-size: 11px;
689
+ font-weight: 600;
690
+ text-transform: uppercase;
691
+ letter-spacing: 0.1em;
692
+ color: var(--text-muted);
693
+ }
694
+
695
+ .turn-entry {
696
+ padding: 10px 12px;
697
+ border-radius: var(--radius-sm);
698
+ border-left: 2px solid;
699
+ background: var(--bg-glass);
700
+ font-size: 12px;
701
+ color: var(--text-secondary);
702
+ line-height: 1.5;
703
+ }
704
+
705
+ .turn-entry.p1 { border-color: var(--p1-color); }
706
+ .turn-entry.p2 { border-color: var(--p2-color); }
707
+
708
+ .turn-entry-score {
709
+ font-weight: 700;
710
+ margin-bottom: 2px;
711
+ }
712
+
713
+ .turn-entry.p1 .turn-entry-score { color: var(--p1-color); }
714
+ .turn-entry.p2 .turn-entry-score { color: var(--p2-color); }
715
+
716
+ /* ── Center / Arena ────────────────────────────────────── */
717
+ .debate-arena {
718
+ display: flex;
719
+ flex-direction: column;
720
+ overflow: hidden;
721
+ background: linear-gradient(180deg, rgba(8,14,26,0.6) 0%, transparent 100%);
722
+ }
723
+
724
+ /* Turn indicator */
725
+ .turn-indicator {
726
+ padding: 20px 24px;
727
+ display: flex;
728
+ align-items: center;
729
+ gap: 16px;
730
+ border-bottom: 1px solid var(--border);
731
+ }
732
+
733
+ .turn-avatar {
734
+ width: 48px;
735
+ height: 48px;
736
+ border-radius: 50%;
737
+ display: flex;
738
+ align-items: center;
739
+ justify-content: center;
740
+ font-family: 'Space Grotesk', sans-serif;
741
+ font-size: 18px;
742
+ font-weight: 800;
743
+ flex-shrink: 0;
744
+ }
745
+
746
+ .turn-avatar.p1 { background: var(--gradient-p1); box-shadow: 0 0 20px rgba(59,130,246,0.40); }
747
+ .turn-avatar.p2 { background: var(--gradient-p2); box-shadow: 0 0 20px rgba(244,63,94,0.40); }
748
+
749
+ .turn-info { flex: 1; }
750
+ .turn-player-name {
751
+ font-family: 'Space Grotesk', sans-serif;
752
+ font-size: 16px;
753
+ font-weight: 700;
754
+ }
755
+ .turn-instruction {
756
+ font-size: 12px;
757
+ color: var(--text-secondary);
758
+ margin-top: 2px;
759
+ }
760
+
761
+ /* Timer */
762
+ .turn-timer {
763
+ display: flex;
764
+ flex-direction: column;
765
+ align-items: center;
766
+ }
767
+
768
+ .timer-ring {
769
+ position: relative;
770
+ width: 52px;
771
+ height: 52px;
772
+ }
773
+
774
+ .timer-svg { transform: rotate(-90deg); }
775
+ .timer-track { stroke: rgba(255,255,255,0.08); }
776
+ .timer-progress {
777
+ stroke: var(--accent-cyan);
778
+ stroke-linecap: round;
779
+ transition: stroke-dashoffset 1s linear, stroke 0.3s;
780
+ }
781
+ .timer-text {
782
+ position: absolute;
783
+ inset: 0;
784
+ display: flex;
785
+ align-items: center;
786
+ justify-content: center;
787
+ font-family: 'Space Grotesk', sans-serif;
788
+ font-size: 14px;
789
+ font-weight: 700;
790
+ color: var(--accent-cyan);
791
+ }
792
+
793
+ /* Debate transcript feed */
794
+ .debate-feed {
795
+ flex: 1;
796
+ overflow-y: auto;
797
+ padding: 20px 24px;
798
+ display: flex;
799
+ flex-direction: column;
800
+ gap: 16px;
801
+ }
802
+
803
+ .debate-feed::-webkit-scrollbar { width: 4px; }
804
+ .debate-feed::-webkit-scrollbar-track { background: transparent; }
805
+ .debate-feed::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
806
+
807
+ .feed-empty {
808
+ text-align: center;
809
+ color: var(--text-muted);
810
+ font-size: 14px;
811
+ padding: 60px 20px;
812
+ }
813
+
814
+ .feed-empty .empty-icon { font-size: 48px; margin-bottom: 16px; opacity: 0.3; }
815
+
816
+ .argument-bubble {
817
+ max-width: 85%;
818
+ padding: 16px 18px;
819
+ border-radius: var(--radius-lg);
820
+ position: relative;
821
+ animation: bubble-in 0.35s cubic-bezier(0.4, 0, 0.2, 1);
822
+ }
823
+
824
+ @keyframes bubble-in {
825
+ from { opacity: 0; transform: translateY(12px) scale(0.97); }
826
+ to { opacity: 1; transform: translateY(0) scale(1); }
827
+ }
828
+
829
+ .argument-bubble.p1 {
830
+ align-self: flex-start;
831
+ background: rgba(37,99,235,0.12);
832
+ border: 1px solid rgba(59,130,246,0.25);
833
+ border-top-left-radius: 4px;
834
+ }
835
+
836
+ .argument-bubble.p2 {
837
+ align-self: flex-end;
838
+ background: rgba(244,63,94,0.12);
839
+ border: 1px solid rgba(244,63,94,0.25);
840
+ border-top-right-radius: 4px;
841
+ }
842
+
843
+ .bubble-header {
844
+ display: flex;
845
+ align-items: center;
846
+ gap: 8px;
847
+ margin-bottom: 8px;
848
+ font-size: 11px;
849
+ font-weight: 700;
850
+ text-transform: uppercase;
851
+ letter-spacing: 0.1em;
852
+ }
853
+
854
+ .argument-bubble.p1 .bubble-header { color: var(--p1-color); }
855
+ .argument-bubble.p2 .bubble-header { color: var(--p2-color); }
856
+
857
+ .bubble-text {
858
+ font-size: 14px;
859
+ line-height: 1.65;
860
+ color: var(--text-primary);
861
+ }
862
+
863
+ .bubble-score {
864
+ display: flex;
865
+ align-items: center;
866
+ gap: 6px;
867
+ margin-top: 10px;
868
+ padding-top: 10px;
869
+ border-top: 1px solid rgba(255,255,255,0.06);
870
+ font-size: 12px;
871
+ color: var(--text-secondary);
872
+ flex-wrap: wrap;
873
+ }
874
+
875
+ .bubble-score-num {
876
+ font-family: 'Space Grotesk', sans-serif;
877
+ font-weight: 700;
878
+ font-size: 14px;
879
+ padding: 2px 8px;
880
+ border-radius: 8px;
881
+ }
882
+
883
+ .argument-bubble.p1 .bubble-score-num { color: var(--p1-color); background: rgba(59,130,246,0.15); }
884
+ .argument-bubble.p2 .bubble-score-num { color: var(--p2-color); background: rgba(244,63,94,0.15); }
885
+
886
+ .rag-pending-chip {
887
+ display: inline-flex;
888
+ align-items: center;
889
+ gap: 4px;
890
+ padding: 2px 8px;
891
+ border-radius: 10px;
892
+ background: rgba(245,158,11,0.15);
893
+ color: var(--accent-amber);
894
+ font-size: 10px;
895
+ font-weight: 600;
896
+ }
897
+
898
+ .claim-chips {
899
+ display: flex;
900
+ gap: 4px;
901
+ flex-wrap: wrap;
902
+ margin-top: 8px;
903
+ }
904
+
905
+ .claim-chip {
906
+ padding: 2px 8px;
907
+ border-radius: 10px;
908
+ font-size: 10px;
909
+ font-weight: 600;
910
+ text-transform: uppercase;
911
+ letter-spacing: 0.06em;
912
+ }
913
+
914
+ .claim-chip.factual { background: rgba(16,185,129,0.15); color: var(--accent-green); }
915
+ .claim-chip.opinion { background: rgba(59,130,246,0.15); color: var(--accent-cyan); }
916
+ .claim-chip.conditional { background: rgba(139,92,246,0.15); color: var(--accent-purple); }
917
+ .claim-chip.rhetorical { background: rgba(245,158,11,0.15); color: var(--accent-amber); }
918
+ .claim-chip.statistical { background: rgba(16,185,129,0.15); color: #34d399; }
919
+ .claim-chip.unclear { background: rgba(255,255,255,0.06); color: var(--text-muted); }
920
+
921
+ /* ── Input Area ────────────────────────────────────────── */
922
+ .input-area {
923
+ padding: 16px 24px 20px;
924
+ border-top: 1px solid var(--border);
925
+ background: rgba(5,10,18,0.8);
926
+ backdrop-filter: blur(8px);
927
+ }
928
+
929
+ .input-area.disabled { opacity: 0.4; pointer-events: none; }
930
+
931
+ .voice-transcript-preview {
932
+ padding: 10px 14px;
933
+ background: rgba(139,92,246,0.08);
934
+ border: 1px solid rgba(139,92,246,0.25);
935
+ border-radius: var(--radius-sm);
936
+ margin-bottom: 10px;
937
+ font-size: 13px;
938
+ color: var(--text-secondary);
939
+ display: none;
940
+ }
941
+
942
+ .voice-transcript-preview.visible { display: block; }
943
+
944
+ .voice-transcript-preview strong {
945
+ color: var(--accent-purple);
946
+ font-size: 11px;
947
+ text-transform: uppercase;
948
+ letter-spacing: 0.08em;
949
+ display: block;
950
+ margin-bottom: 4px;
951
+ }
952
+
953
+ .argument-textarea {
954
+ width: 100%;
955
+ min-height: 90px;
956
+ max-height: 200px;
957
+ padding: 14px 16px;
958
+ background: var(--bg-input);
959
+ border: 1px solid var(--border);
960
+ border-radius: var(--radius-md);
961
+ color: var(--text-primary);
962
+ font-family: 'Inter', sans-serif;
963
+ font-size: 14px;
964
+ line-height: 1.65;
965
+ resize: none;
966
+ outline: none;
967
+ transition: var(--transition);
968
+ margin-bottom: 12px;
969
+ }
970
+
971
+ .argument-textarea:focus {
972
+ border-color: var(--accent-blue);
973
+ box-shadow: 0 0 0 3px rgba(59,130,246,0.12);
974
+ }
975
+
976
+ .argument-textarea::placeholder { color: var(--text-muted); }
977
+
978
+ .input-toolbar {
979
+ display: flex;
980
+ align-items: center;
981
+ justify-content: space-between;
982
+ gap: 10px;
983
+ }
984
+
985
+ .input-left { display: flex; align-items: center; gap: 8px; }
986
+
987
+ .word-count {
988
+ font-size: 11px;
989
+ color: var(--text-muted);
990
+ }
991
+
992
+ /* ── Analysis Panel (right) ────────────────────────────── */
993
+ .analysis-panel {
994
+ border-left: 1px solid var(--border);
995
+ overflow-y: auto;
996
+ padding: 20px;
997
+ display: flex;
998
+ flex-direction: column;
999
+ gap: 16px;
1000
+ background: rgba(5,8,15,0.4);
1001
+ }
1002
+
1003
+ .analysis-panel::-webkit-scrollbar { width: 4px; }
1004
+ .analysis-panel::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
1005
+
1006
+ .panel-section-title {
1007
+ font-size: 11px;
1008
+ font-weight: 700;
1009
+ text-transform: uppercase;
1010
+ letter-spacing: 0.12em;
1011
+ color: var(--text-muted);
1012
+ margin-bottom: 8px;
1013
+ display: flex;
1014
+ align-items: center;
1015
+ gap: 6px;
1016
+ }
1017
+
1018
+ /* Criterion score breakdown */
1019
+ .criterion-list {
1020
+ display: flex;
1021
+ flex-direction: column;
1022
+ gap: 10px;
1023
+ }
1024
+
1025
+ .criterion-row {
1026
+ display: flex;
1027
+ flex-direction: column;
1028
+ gap: 4px;
1029
+ }
1030
+
1031
+ .criterion-top {
1032
+ display: flex;
1033
+ justify-content: space-between;
1034
+ align-items: center;
1035
+ font-size: 12px;
1036
+ }
1037
+
1038
+ .criterion-name { color: var(--text-secondary); }
1039
+ .criterion-weight { color: var(--text-muted); font-size: 10px; }
1040
+ .criterion-value { color: var(--text-primary); font-weight: 600; }
1041
+
1042
+ .criterion-bar-track {
1043
+ height: 4px;
1044
+ background: rgba(255,255,255,0.06);
1045
+ border-radius: 2px;
1046
+ overflow: hidden;
1047
+ }
1048
+
1049
+ .criterion-bar-fill {
1050
+ height: 100%;
1051
+ border-radius: 2px;
1052
+ transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
1053
+ }
1054
+
1055
+ .criterion-bar-fill.rebuttal { background: linear-gradient(90deg, #3b82f6, #60a5fa); }
1056
+ .criterion-bar-fill.reasoning { background: linear-gradient(90deg, #8b5cf6, #a78bfa); }
1057
+ .criterion-bar-fill.evidence { background: linear-gradient(90deg, #10b981, #34d399); }
1058
+ .criterion-bar-fill.relevance { background: linear-gradient(90deg, #06b6d4, #67e8f9); }
1059
+ .criterion-bar-fill.clarity { background: linear-gradient(90deg, #f59e0b, #fcd34d); }
1060
+ .criterion-bar-fill.stance { background: linear-gradient(90deg, #f43f5e, #fb7185); }
1061
+
1062
+ /* Fact-check results */
1063
+ .fact-check-list {
1064
+ display: flex;
1065
+ flex-direction: column;
1066
+ gap: 8px;
1067
+ }
1068
+
1069
+ .fact-item {
1070
+ padding: 10px 12px;
1071
+ border-radius: var(--radius-sm);
1072
+ border: 1px solid;
1073
+ font-size: 12px;
1074
+ line-height: 1.5;
1075
+ }
1076
+
1077
+ .fact-item.supported { background: rgba(16,185,129,0.08); border-color: rgba(16,185,129,0.25); }
1078
+ .fact-item.partially_supported { background: rgba(245,158,11,0.08); border-color: rgba(245,158,11,0.25); }
1079
+ .fact-item.refuted { background: rgba(239,68,68,0.08); border-color: rgba(239,68,68,0.25); }
1080
+ .fact-item.insufficient_evidence { background: rgba(255,255,255,0.04); border-color: rgba(255,255,255,0.10); }
1081
+ .fact-item.ambiguous { background: rgba(139,92,246,0.08); border-color: rgba(139,92,246,0.25); }
1082
+ .fact-item.pending { background: rgba(245,158,11,0.06); border-color: rgba(245,158,11,0.20); }
1083
+
1084
+ .fact-verdict {
1085
+ font-size: 10px;
1086
+ font-weight: 700;
1087
+ text-transform: uppercase;
1088
+ letter-spacing: 0.08em;
1089
+ margin-bottom: 2px;
1090
+ }
1091
+
1092
+ .fact-item.supported .fact-verdict { color: var(--accent-green); }
1093
+ .fact-item.partially_supported .fact-verdict { color: var(--accent-amber); }
1094
+ .fact-item.refuted .fact-verdict { color: var(--accent-red); }
1095
+ .fact-item.insufficient_evidence .fact-verdict { color: var(--text-muted); }
1096
+ .fact-item.ambiguous .fact-verdict { color: var(--accent-purple); }
1097
+ .fact-item.pending .fact-verdict { color: var(--accent-amber); }
1098
+
1099
+ .fact-text { color: var(--text-secondary); }
1100
+
1101
+ /* Relation tags */
1102
+ .relation-list { display: flex; flex-direction: column; gap: 6px; }
1103
+
1104
+ .relation-tag {
1105
+ display: flex;
1106
+ align-items: center;
1107
+ gap: 8px;
1108
+ padding: 8px 10px;
1109
+ border-radius: var(--radius-sm);
1110
+ background: var(--bg-glass);
1111
+ border: 1px solid var(--border);
1112
+ font-size: 11px;
1113
+ }
1114
+
1115
+ .relation-label {
1116
+ font-weight: 700;
1117
+ text-transform: uppercase;
1118
+ letter-spacing: 0.06em;
1119
+ font-size: 10px;
1120
+ padding: 2px 7px;
1121
+ border-radius: 8px;
1122
+ }
1123
+
1124
+ .relation-label.contradict { background: rgba(239,68,68,0.2); color: var(--accent-red); }
1125
+ .relation-label.support { background: rgba(16,185,129,0.2); color: var(--accent-green); }
1126
+ .relation-label.qualify { background: rgba(245,158,11,0.2); color: var(--accent-amber); }
1127
+ .relation-label.elaborate { background: rgba(59,130,246,0.2); color: var(--accent-blue); }
1128
+ .relation-label.neutral { background: rgba(255,255,255,0.08); color: var(--text-muted); }
1129
+ .relation-label.unrelated { background: rgba(239,68,68,0.08); color: #f87171; }
1130
+
1131
+ .relation-hint { color: var(--text-secondary); flex: 1; }
1132
+
1133
+ /* Feedback panel */
1134
+ .feedback-box {
1135
+ padding: 14px;
1136
+ border-radius: var(--radius-md);
1137
+ background: rgba(59,130,246,0.06);
1138
+ border: 1px solid rgba(59,130,246,0.15);
1139
+ font-size: 12px;
1140
+ color: var(--text-secondary);
1141
+ line-height: 1.7;
1142
+ }
1143
+
1144
+ /* ── Final Screen ──────────────────────────────────────── */
1145
+ #final-screen {
1146
+ align-items: center;
1147
+ justify-content: center;
1148
+ padding: 60px 24px;
1149
+ text-align: center;
1150
+ }
1151
+
1152
+ .winner-glow {
1153
+ position: relative;
1154
+ margin-bottom: 48px;
1155
+ }
1156
+
1157
+ .winner-label {
1158
+ font-size: 13px;
1159
+ font-weight: 700;
1160
+ text-transform: uppercase;
1161
+ letter-spacing: 0.2em;
1162
+ color: var(--text-muted);
1163
+ margin-bottom: 16px;
1164
+ }
1165
+
1166
+ .winner-trophy { font-size: 80px; display: block; margin-bottom: 16px; animation: trophy-bounce 1s ease 0.5s both; }
1167
+
1168
+ @keyframes trophy-bounce {
1169
+ from { opacity: 0; transform: scale(0.5) translateY(20px); }
1170
+ to { opacity: 1; transform: scale(1) translateY(0); }
1171
+ }
1172
+
1173
+ .winner-name {
1174
+ font-family: 'Space Grotesk', sans-serif;
1175
+ font-size: clamp(2.5rem, 6vw, 4.5rem);
1176
+ font-weight: 800;
1177
+ letter-spacing: -0.03em;
1178
+ animation: name-reveal 0.6s ease 0.8s both;
1179
+ }
1180
+
1181
+ @keyframes name-reveal {
1182
+ from { opacity: 0; transform: translateY(10px); }
1183
+ to { opacity: 1; transform: translateY(0); }
1184
+ }
1185
+
1186
+ .winner-name.p1-win {
1187
+ background: linear-gradient(135deg, #3b82f6, #60a5fa);
1188
+ -webkit-background-clip: text;
1189
+ -webkit-text-fill-color: transparent;
1190
+ background-clip: text;
1191
+ }
1192
+
1193
+ .winner-name.p2-win {
1194
+ background: linear-gradient(135deg, #f43f5e, #fb7185);
1195
+ -webkit-background-clip: text;
1196
+ -webkit-text-fill-color: transparent;
1197
+ background-clip: text;
1198
+ }
1199
+
1200
+ .winner-side { font-size: 14px; color: var(--text-secondary); margin-top: 8px; }
1201
+
1202
+ .final-scoreboard {
1203
+ display: grid;
1204
+ grid-template-columns: 1fr 1fr;
1205
+ gap: 20px;
1206
+ max-width: 640px;
1207
+ width: 100%;
1208
+ margin: 0 auto 40px;
1209
+ }
1210
+
1211
+ .final-score-card {
1212
+ background: var(--bg-card);
1213
+ border: 1px solid var(--border);
1214
+ border-radius: var(--radius-xl);
1215
+ padding: 32px;
1216
+ position: relative;
1217
+ overflow: hidden;
1218
+ }
1219
+
1220
+ .final-score-card.winner {
1221
+ border-color: rgba(59,130,246,0.50);
1222
+ box-shadow: var(--shadow-glow);
1223
+ }
1224
+
1225
+ .final-score-card.winner.p2-win {
1226
+ border-color: rgba(244,63,94,0.50);
1227
+ box-shadow: 0 0 40px rgba(244,63,94,0.20);
1228
+ }
1229
+
1230
+ .final-score-card .player-name-final {
1231
+ font-family: 'Space Grotesk', sans-serif;
1232
+ font-size: 20px;
1233
+ font-weight: 700;
1234
+ margin-bottom: 4px;
1235
+ }
1236
+
1237
+ .final-score-card .player-name-final.p1 { color: var(--p1-color); }
1238
+ .final-score-card .player-name-final.p2 { color: var(--p2-color); }
1239
+
1240
+ .final-total-score {
1241
+ font-family: 'Space Grotesk', sans-serif;
1242
+ font-size: 52px;
1243
+ font-weight: 800;
1244
+ line-height: 1;
1245
+ margin: 12px 0 4px;
1246
+ }
1247
+
1248
+ .final-score-card .player-name-final.p1 + .player-side-small + .final-total-score { color: var(--p1-color); }
1249
+
1250
+ .player-side-small {
1251
+ font-size: 11px;
1252
+ text-transform: uppercase;
1253
+ letter-spacing: 0.1em;
1254
+ color: var(--text-muted);
1255
+ margin-bottom: 16px;
1256
+ }
1257
+
1258
+ .crown-badge {
1259
+ position: absolute;
1260
+ top: 12px;
1261
+ right: 12px;
1262
+ font-size: 24px;
1263
+ }
1264
+
1265
+ .final-actions {
1266
+ display: flex;
1267
+ gap: 12px;
1268
+ justify-content: center;
1269
+ }
1270
+
1271
+ .btn-new-match {
1272
+ background: var(--gradient-accent);
1273
+ color: white;
1274
+ box-shadow: var(--shadow-btn);
1275
+ padding: 14px 32px;
1276
+ }
1277
+
1278
+ .btn-new-match:hover {
1279
+ transform: translateY(-2px);
1280
+ box-shadow: 0 8px 30px rgba(59,130,246,0.4);
1281
+ }
1282
+
1283
+ /* ── Analysis Loading ──────────────────────────────────── */
1284
+ .analyzing-overlay {
1285
+ display: none;
1286
+ position: fixed;
1287
+ inset: 0;
1288
+ background: rgba(5,10,18,0.85);
1289
+ backdrop-filter: blur(4px);
1290
+ z-index: 500;
1291
+ align-items: center;
1292
+ justify-content: center;
1293
+ flex-direction: column;
1294
+ gap: 24px;
1295
+ }
1296
+
1297
+ .analyzing-overlay.visible { display: flex; }
1298
+
1299
+ .analyzing-spinner {
1300
+ width: 64px;
1301
+ height: 64px;
1302
+ border: 3px solid rgba(59,130,246,0.15);
1303
+ border-top-color: var(--accent-blue);
1304
+ border-radius: 50%;
1305
+ animation: spin 1s linear infinite;
1306
+ }
1307
+
1308
+ @keyframes spin { to { transform: rotate(360deg); } }
1309
+
1310
+ .analyzing-label {
1311
+ font-family: 'Space Grotesk', sans-serif;
1312
+ font-size: 18px;
1313
+ font-weight: 600;
1314
+ color: var(--text-primary);
1315
+ }
1316
+
1317
+ .analyzing-steps {
1318
+ display: flex;
1319
+ flex-direction: column;
1320
+ gap: 8px;
1321
+ text-align: left;
1322
+ }
1323
+
1324
+ .analyzing-step {
1325
+ display: flex;
1326
+ align-items: center;
1327
+ gap: 8px;
1328
+ font-size: 13px;
1329
+ color: var(--text-muted);
1330
+ transition: var(--transition);
1331
+ }
1332
+
1333
+ .analyzing-step.active { color: var(--accent-cyan); }
1334
+ .analyzing-step.done { color: var(--accent-green); }
1335
+
1336
+ .step-icon { font-size: 14px; }
1337
+
1338
+ /* ── Toast notifications ────────────────────────────────── */
1339
+ .toast-container {
1340
+ position: fixed;
1341
+ bottom: 24px;
1342
+ right: 24px;
1343
+ z-index: 1000;
1344
+ display: flex;
1345
+ flex-direction: column;
1346
+ gap: 8px;
1347
+ pointer-events: none;
1348
+ }
1349
+
1350
+ .toast {
1351
+ padding: 12px 18px;
1352
+ border-radius: var(--radius-md);
1353
+ background: var(--bg-card);
1354
+ border: 1px solid var(--border);
1355
+ backdrop-filter: blur(12px);
1356
+ font-size: 13px;
1357
+ color: var(--text-primary);
1358
+ max-width: 320px;
1359
+ display: flex;
1360
+ align-items: center;
1361
+ gap: 8px;
1362
+ animation: toast-in 0.35s cubic-bezier(0.4, 0, 0.2, 1);
1363
+ box-shadow: 0 8px 24px rgba(0,0,0,0.4);
1364
+ pointer-events: auto;
1365
+ }
1366
+
1367
+ @keyframes toast-in {
1368
+ from { opacity: 0; transform: translateX(20px); }
1369
+ to { opacity: 1; transform: translateX(0); }
1370
+ }
1371
+
1372
+ .toast.info .toast-icon { color: var(--accent-cyan); }
1373
+ .toast.success .toast-icon { color: var(--accent-green); }
1374
+ .toast.warning .toast-icon { color: var(--accent-amber); }
1375
+ .toast.error .toast-icon { color: var(--accent-red); }
1376
+
1377
+ /* ── Connection status ─────────────────────────────────── */
1378
+ .connection-banner {
1379
+ display: none;
1380
+ position: fixed;
1381
+ top: 0; left: 0; right: 0;
1382
+ padding: 10px;
1383
+ text-align: center;
1384
+ font-size: 13px;
1385
+ font-weight: 600;
1386
+ z-index: 999;
1387
+ }
1388
+
1389
+ .connection-banner.offline {
1390
+ display: block;
1391
+ background: rgba(239,68,68,0.90);
1392
+ color: white;
1393
+ backdrop-filter: blur(4px);
1394
+ }
1395
+
1396
+ /* ── Confetti placeholder ──────────────────────────────── */
1397
+ .confetti-canvas {
1398
+ position: fixed;
1399
+ inset: 0;
1400
+ pointer-events: none;
1401
+ z-index: 200;
1402
+ }
1403
+
1404
+ /* ── Scrollbars ────────────────────────────────────────── */
1405
+ ::-webkit-scrollbar { width: 5px; height: 5px; }
1406
+ ::-webkit-scrollbar-track { background: transparent; }
1407
+ ::-webkit-scrollbar-thumb { background: rgba(59,130,246,0.20); border-radius: 3px; }
1408
+
1409
+ /* ── Responsive ────────────────────────────────────────── */
1410
+ @media (max-width: 1024px) {
1411
+ .debate-main {
1412
+ grid-template-columns: 240px 1fr 260px;
1413
+ }
1414
+ }
1415
+
1416
+ @media (max-width: 768px) {
1417
+ .debate-main {
1418
+ grid-template-columns: 1fr;
1419
+ grid-template-rows: auto 1fr auto;
1420
+ }
1421
+
1422
+ .player-panel {
1423
+ border: none;
1424
+ border-bottom: 1px solid var(--border);
1425
+ flex-direction: row;
1426
+ flex-wrap: wrap;
1427
+ padding: 12px 16px;
1428
+ gap: 12px;
1429
+ max-height: 120px;
1430
+ overflow: hidden;
1431
+ }
1432
+
1433
+ .analysis-panel {
1434
+ border-left: none;
1435
+ border-top: 1px solid var(--border);
1436
+ max-height: 300px;
1437
+ }
1438
+
1439
+ .setup-grid { grid-template-columns: 1fr; }
1440
+ .final-scoreboard { grid-template-columns: 1fr; }
1441
+ }
1442
+
1443
+ /* ── Multi-Device & 2-Laptop Styles ──────────────────── */
1444
+ .setup-tabs {
1445
+ display: flex;
1446
+ gap: 8px;
1447
+ background: rgba(255, 255, 255, 0.04);
1448
+ padding: 4px;
1449
+ border-radius: var(--radius-sm);
1450
+ margin-bottom: 20px;
1451
+ border: 1px solid var(--border);
1452
+ }
1453
+
1454
+ .setup-tab {
1455
+ flex: 1;
1456
+ padding: 10px 14px;
1457
+ background: transparent;
1458
+ border: none;
1459
+ border-radius: var(--radius-xs);
1460
+ color: var(--text-muted);
1461
+ font-family: inherit;
1462
+ font-size: 13px;
1463
+ font-weight: 600;
1464
+ cursor: pointer;
1465
+ transition: all 0.2s ease;
1466
+ display: flex;
1467
+ align-items: center;
1468
+ justify-content: center;
1469
+ gap: 6px;
1470
+ }
1471
+
1472
+ .setup-tab.active {
1473
+ background: rgba(59, 130, 246, 0.20);
1474
+ color: var(--text-primary);
1475
+ border: 1px solid rgba(59, 130, 246, 0.40);
1476
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
1477
+ }
1478
+
1479
+ .setup-tab:hover:not(.active) {
1480
+ color: var(--text-secondary);
1481
+ background: rgba(255, 255, 255, 0.02);
1482
+ }
1483
+
1484
+ .role-selector-row {
1485
+ margin-top: 14px;
1486
+ margin-bottom: 18px;
1487
+ background: rgba(255, 255, 255, 0.03);
1488
+ padding: 12px 16px;
1489
+ border-radius: var(--radius-sm);
1490
+ border: 1px solid var(--border);
1491
+ }
1492
+
1493
+ .role-selector-row label {
1494
+ font-size: 11px;
1495
+ color: var(--text-muted);
1496
+ text-transform: uppercase;
1497
+ letter-spacing: 0.08em;
1498
+ font-weight: 700;
1499
+ display: block;
1500
+ margin-bottom: 8px;
1501
+ }
1502
+
1503
+ .role-options {
1504
+ display: flex;
1505
+ gap: 16px;
1506
+ flex-wrap: wrap;
1507
+ }
1508
+
1509
+ .role-radio-label {
1510
+ display: flex;
1511
+ align-items: center;
1512
+ gap: 8px;
1513
+ font-size: 13px;
1514
+ color: var(--text-secondary);
1515
+ cursor: pointer;
1516
+ }
1517
+
1518
+ .role-radio-label input[type="radio"] {
1519
+ accent-color: var(--accent-cyan);
1520
+ cursor: pointer;
1521
+ }
1522
+
1523
+ .active-match-card {
1524
+ background: linear-gradient(135deg, rgba(59, 130, 246, 0.12), rgba(139, 92, 246, 0.12));
1525
+ border: 1px solid rgba(59, 130, 246, 0.3);
1526
+ border-radius: var(--radius-sm);
1527
+ padding: 16px;
1528
+ margin-bottom: 20px;
1529
+ text-align: left;
1530
+ }
1531
+
1532
+ .active-match-badge {
1533
+ font-size: 10px;
1534
+ font-weight: 800;
1535
+ letter-spacing: 0.1em;
1536
+ color: var(--accent-cyan);
1537
+ margin-bottom: 6px;
1538
+ display: inline-block;
1539
+ }
1540
+
1541
+ .active-match-topic {
1542
+ font-size: 15px;
1543
+ font-weight: 700;
1544
+ color: var(--text-primary);
1545
+ margin-bottom: 6px;
1546
+ line-height: 1.4;
1547
+ }
1548
+
1549
+ .active-match-players {
1550
+ font-size: 12px;
1551
+ color: var(--text-muted);
1552
+ margin-bottom: 14px;
1553
+ }
1554
+
1555
+ .active-match-actions {
1556
+ display: flex;
1557
+ gap: 8px;
1558
+ flex-wrap: wrap;
1559
+ }
1560
+
1561
+ .btn-p1 {
1562
+ background: rgba(59, 130, 246, 0.25);
1563
+ color: #60a5fa;
1564
+ border: 1px solid rgba(59, 130, 246, 0.4);
1565
+ }
1566
+ .btn-p1:hover {
1567
+ background: rgba(59, 130, 246, 0.4);
1568
+ }
1569
+
1570
+ .btn-p2 {
1571
+ background: rgba(239, 68, 68, 0.25);
1572
+ color: #f87171;
1573
+ border: 1px solid rgba(239, 68, 68, 0.4);
1574
+ }
1575
+ .btn-p2:hover {
1576
+ background: rgba(239, 68, 68, 0.4);
1577
+ }
1578
+
1579
+ .btn-xs {
1580
+ font-size: 11px;
1581
+ padding: 5px 10px;
1582
+ border-radius: var(--radius-xs);
1583
+ font-weight: 600;
1584
+ }
1585
+
1586
+ .room-share-bar {
1587
+ display: flex;
1588
+ align-items: center;
1589
+ gap: 8px;
1590
+ flex-wrap: wrap;
1591
+ }
1592
+
1593
+ .room-code-tag {
1594
+ background: rgba(255, 255, 255, 0.06);
1595
+ border: 1px solid var(--border);
1596
+ padding: 4px 10px;
1597
+ border-radius: 50px;
1598
+ font-size: 11px;
1599
+ color: var(--text-secondary);
1600
+ font-family: 'Space Grotesk', monospace;
1601
+ }
1602
+
1603
+ .room-code-tag strong {
1604
+ color: var(--accent-cyan);
1605
+ }
1606
+
1607
+ .device-role-tag {
1608
+ background: rgba(139, 92, 246, 0.15);
1609
+ border: 1px solid rgba(139, 92, 246, 0.3);
1610
+ color: #c4b5fd;
1611
+ padding: 4px 10px;
1612
+ border-radius: 50px;
1613
+ font-size: 11px;
1614
+ font-weight: 600;
1615
+ }
1616
+
1617
+ .btn-share {
1618
+ background: rgba(255, 255, 255, 0.05);
1619
+ border: 1px solid var(--border);
1620
+ color: var(--text-secondary);
1621
+ transition: all 0.2s;
1622
+ cursor: pointer;
1623
+ }
1624
+
1625
+ .btn-share:hover {
1626
+ background: rgba(255, 255, 255, 0.12);
1627
+ color: var(--text-primary);
1628
+ border-color: rgba(255, 255, 255, 0.2);
1629
+ }
1630
+
1631
+ /* Waiting banner on input */
1632
+ .turn-waiting-banner {
1633
+ display: flex;
1634
+ align-items: center;
1635
+ justify-content: center;
1636
+ gap: 12px;
1637
+ background: rgba(0, 0, 0, 0.4);
1638
+ border: 1px dashed rgba(255, 255, 255, 0.15);
1639
+ border-radius: var(--radius-sm);
1640
+ padding: 24px;
1641
+ margin-bottom: 12px;
1642
+ backdrop-filter: blur(4px);
1643
+ }
1644
+
1645
+ .waiting-pulse-dot {
1646
+ width: 10px;
1647
+ height: 10px;
1648
+ border-radius: 50%;
1649
+ background: var(--accent-cyan);
1650
+ box-shadow: 0 0 10px var(--accent-cyan);
1651
+ animation: pulse-glow 1.5s infinite ease-in-out;
1652
+ }
1653
+
1654
+ @keyframes pulse-glow {
1655
+ 0%, 100% { transform: scale(0.9); opacity: 0.6; }
1656
+ 50% { transform: scale(1.3); opacity: 1; }
1657
+ }
1658
+
1659
+ .turn-waiting-text {
1660
+ font-size: 14px;
1661
+ font-weight: 600;
1662
+ color: var(--text-secondary);
1663
+ }
1664
+
render.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ - type: web
3
+ name: clash-of-minds
4
+ env: docker
5
+ dockerfilePath: ./Dockerfile
6
+ plan: free
7
+ healthCheckPath: /api/health
8
+ autoDeploy: true