World Cup Agent Cursor commited on
Commit
8f20aeb
·
1 Parent(s): 3fea406

Improve prediction pipeline, dashboard UX, and HF Space assets.

Browse files

Add evidence synthesis and stress-testing via prediction_intel, show full country names and model probabilities in expanded cards, and document the research pipeline in the README.

Co-authored-by: Cursor <cursoragent@cursor.com>

Files changed (8) hide show
  1. README.md +88 -31
  2. app.py +55 -8
  3. gemini.py +14 -2
  4. make_thumbnail.py +77 -0
  5. predict.py +76 -56
  6. prediction_intel.py +377 -0
  7. templates/index.html +42 -32
  8. thumbnail.png +0 -0
README.md CHANGED
@@ -24,22 +24,31 @@ Each match goes through two automated phases:
24
 
25
  ### 1. Predict (`predict.py`) — runs 30 minutes before kickoff
26
 
27
- ```
28
  python predict.py HOME AWAY [KICKOFF_UTC]
29
- # e.g. python predict.py NED JPN 2026-06-14T20:00Z
 
30
  ```
31
 
32
- **Stage 1 — Analyst:** Gemini reads the current strategy document and the service directory of available x402 data endpoints, then produces a structured list of *information needs* (what it wants to know about the match) and a *research plan* (which endpoints to call and why, given the $0.50 per-match budget).
 
 
 
 
33
 
34
- **Stage 2 — Shopper:** A second Gemini call takes the research plan and the actual OpenAPI specs of the available services, maps needs to real endpoints with their prices, and produces the final purchase list.
35
 
36
- **Data fetch:** The agent calls each planned endpoint through an x402-aware `requests` session. When a server responds with HTTP 402, the client automatically signs and submits an on-chain USDC micropayment on Base, then retries — no manual payment step. Each response (up to 2,000 chars) is collected as context.
 
 
37
 
38
  **Prediction:** A final Gemini call reasons over the purchased data, the strategy, and recent match history, then outputs:
39
  - `PICK`: home / away / draw
40
- - `CONFIDENCE`: 1–10
41
- - `BET`: suggested stake in USD
42
- - `REASONING`: one-sentence justification
 
 
43
 
44
  Results are saved to `results.json`, a Discord notification is sent, and the commit is pushed to GitHub and the HF Space.
45
 
@@ -47,7 +56,7 @@ Results are saved to `results.json`, a Discord notification is sent, and the com
47
 
48
  ### 2. Reflect (`reflect.py`) — runs 2.5 hours after kickoff
49
 
50
- ```
51
  python reflect.py HOME AWAY
52
  # e.g. python reflect.py NED JPN
53
  ```
@@ -62,11 +71,51 @@ python reflect.py HOME AWAY
62
 
63
  ---
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  ## Self-improving strategy
66
 
67
  `strategy.md` is the agent's accumulated knowledge — a short document (≤500 words) of rules and learnings. It grows one rule at a time, each tagged with the match that informed it. The predictor reads the full strategy before every match; the reflector updates it after every result.
68
 
69
- The strategy also tracks which x402 data services have been useful across past matches, so the agent learns to allocate its $0.50 budget more efficiently over time.
70
 
71
  ---
72
 
@@ -81,21 +130,22 @@ The agent pays for data using USDC on Base (mainnet or testnet). Key pieces:
81
 
82
  **Balance check:** At startup, `predict.py` reads the on-chain USDC balance by calling `balanceOf` on the USDC contract. If it's below $0.10, the run aborts.
83
 
84
- **x402 session:** `wallet.get_x402_client()` returns a `requests.Session` wired with `ExactEvmScheme` for the configured chain. Any `GET` that returns `402 Payment Required` is handled automatically: the client signs a payment transaction with the wallet's private key, submits it on-chain, and retries the request — all transparent to the calling code.
85
 
86
- **Cost tracking:** `total_spent` accumulates per-match. `balance_after = balance - total_spent` is an estimate (the on-chain balance is not re-fetched mid-run). Both figures are saved to `results.json` for analysis.
87
 
88
  ---
89
 
90
  ## Web dashboard (`app.py`)
91
 
92
- FastAPI app deployed on HF Spaces. Three routes:
93
 
94
  | Route | Content |
95
  |-------|---------|
96
- | `/` | Live dashboard: upcoming fixtures, all predictions with badges, x402 spend table, strategy snippet |
97
  | `/match/HOME_AWAY` | Full detail: analyst needs, purchased endpoints with raw data, research gaps, Gemini reasoning, evaluation, strategy at prediction time |
98
- | `/strategy` | Current strategy + full evolution history across all matches |
 
99
  | `/api/results` | Raw `results.json` as JSON |
100
  | `/api/schedule` | Raw `schedule.json` as JSON |
101
 
@@ -153,25 +203,29 @@ python setup_wallet.py
153
 
154
  ## Scheduling
155
 
156
- Matches are scheduled automatically with cron via `schedule_match.py`:
157
 
158
  ```bash
159
- # Schedule a single match (adds two cron entries: predict + reflect)
160
- python schedule_match.py NED JPN 2026-06-14T20:00:00Z
161
-
162
- # Or use setup_schedule.py to load from schedule.json in bulk
163
  python setup_schedule.py
 
 
 
 
 
 
164
  ```
165
 
166
- Predict runs 30 minutes before kickoff; reflect runs 2 hours 30 minutes after kickoff. Logs go to `logs/HOME_AWAY.log`.
167
 
168
  ---
169
 
170
  ## Manual run
171
 
172
  ```bash
173
- # Predict (can be run after kickoff with a past timestamp for retroactive mode)
174
- python predict.py NED JPN 2026-06-14T20:00Z
 
175
 
176
  # Reflect (after the match is complete)
177
  python reflect.py NED JPN
@@ -180,14 +234,14 @@ python reflect.py NED JPN
180
  uvicorn app:app --reload --port 7860
181
  ```
182
 
183
- Retroactive mode is automatically detected when the kickoff timestamp is in the past, and constrains research to pre-match sources only.
184
 
185
  ---
186
 
187
  ## File structure
188
 
189
  ```
190
- predict.py # Pre-match: research + prediction
191
  reflect.py # Post-match: result + evaluation + strategy update
192
  app.py # FastAPI web dashboard
193
  wallet.py # USDC balance check + x402 payment session
@@ -195,18 +249,21 @@ gemini.py # Gemini REST API wrapper
195
  discord_notify.py # Discord bot notifications
196
  setup_wallet.py # One-time wallet keypair generation
197
  schedule_match.py # Add cron entries for a single match
198
- setup_schedule.py # Bulk-load schedule.json into cron
199
- results.json # All predictions and outcomes (append-only)
 
200
  strategy.md # Agent's accumulated strategy (rewritten each match)
201
- schedule.json # Fixture list with kickoff times
 
202
  ```
203
 
204
  ---
205
 
206
  ## Dependencies
207
 
208
- - **Gemini Flash** — two-stage reasoning (analyst → shopper → predictor; separate evaluator + reflector)
209
- - **x402** — HTTP 402 micropayment protocol for real-time sports data
210
  - **Web3 / eth-account** — Base chain interaction for balance checks and payment signing
211
  - **FastAPI / uvicorn** — web dashboard
212
- - **ESPN public API** — free post-match result fetching
 
 
24
 
25
  ### 1. Predict (`predict.py`) — runs 30 minutes before kickoff
26
 
27
+ ```bash
28
  python predict.py HOME AWAY [KICKOFF_UTC]
29
+ # e.g. python predict.py NED JPN
30
+ # optional kickoff override: python predict.py NED JPN 2026-06-14T20:00Z
31
  ```
32
 
33
+ Kickoff is read from `schedule.json` by default; pass `KICKOFF_UTC` only for retroactive re-runs.
34
+
35
+ **Stage 1 — Analyst:** Gemini lists 8–12 specific questions grouped by category (FORM, PLAYERS, TACTICS, H2H, CONTEXT, MARKET, NEWS, VENUE). No data services are shown yet — this is pure information-needs planning.
36
+
37
+ **Stage 2 — Shopper:** A second Gemini call receives those needs, the current strategy, and the full x402 service directory. It maps each need to concrete endpoints and prices, and flags any *research gaps* (needs with no available service).
38
 
39
+ **Baseline searches (always run):** Six mandatory Tavily/Brave search calls cover match preview, squad news, both teams' form, head-to-head, and group context. They cost **$0.056** (2× Tavily @ $0.012 + 4× Brave @ $0.008) and are always included in the plan first; the shopper stages additional calls against whatever remains of the per-match budget.
40
 
41
+ **Data fetch:** The agent calls each planned endpoint through an x402-aware `requests` session. When a server responds with HTTP 402, the client automatically signs and submits an on-chain USDC micropayment on Base, then retries. Responses are cleaned before being passed to the predictor — skim402 nav junk is stripped, and Tavily/Brave/Swerver JSON is condensed to readable snippets.
42
+
43
+ **Fallback research:** If most calls fail, return low-quality data, or no search results were obtained, a third Gemini call plans up to five alternative endpoints (preferring Tavily/Brave) within the remaining budget.
44
 
45
  **Prediction:** A final Gemini call reasons over the purchased data, the strategy, and recent match history, then outputs:
46
  - `PICK`: home / away / draw
47
+ - `CONFIDENCE`: 1–10 (calibrated — not defaulted to 5)
48
+ - `CONFIDENCE_REASON`: one sentence explaining the confidence level
49
+ - `REASONING`: one-sentence justification for the pick
50
+
51
+ There is **no bet sizing** — the agent predicts outcomes only, not stake amounts. The dashboard shows pick, confidence (with hover tooltip for the reason), and research cost. Older entries in `results.json` may still have a legacy `bet` field from earlier runs.
52
 
53
  Results are saved to `results.json`, a Discord notification is sent, and the commit is pushed to GitHub and the HF Space.
54
 
 
56
 
57
  ### 2. Reflect (`reflect.py`) — runs 2.5 hours after kickoff
58
 
59
+ ```bash
60
  python reflect.py HOME AWAY
61
  # e.g. python reflect.py NED JPN
62
  ```
 
71
 
72
  ---
73
 
74
+ ## Research pipeline detail
75
+
76
+ ### x402 data sources
77
+
78
+ The agent pulls from two layers:
79
+
80
+ 1. **Service directory** — fetched live from [x402-list.com](https://x402-list.com/api/v1/services), filtered to online services on the configured network (Base mainnet or Sepolia). OpenAPI specs are fetched per service to discover real endpoint paths and prices.
81
+
82
+ 2. **Supplemental services** — verified working endpoints not yet in the directory:
83
+
84
+ | Service | Endpoint | Cost | Use |
85
+ |---------|----------|------|-----|
86
+ | SignalFuse Tavily | `POST /v1/gateway/search/tavily` | $0.012 | AI-ranked news/previews, injury reports |
87
+ | SignalFuse Brave | `GET /v1/gateway/search/brave` | $0.008 | Structured web search |
88
+ | Swerver Search | `POST /search` | $0.010 | Fast headless browser search |
89
+ | Swerver Scrape | `POST /scrape` | $0.010 | Scrape any URL when skim402 fails |
90
+ | Skim402 | `GET /api/v2/read?url=...` | ~$0.002 | Read verified team/tournament pages |
91
+ | GDELT | `GET /news/recent?topic=...` | varies | Recent news by topic |
92
+
93
+ ### Verified team URLs
94
+
95
+ For skim402 page reads, `predict.py` maintains a lookup table (`TEAM_DATA`) of empirically verified URLs per team — Transfermarkt squad/results pages, national-football-teams.com, Soccerway, and Guardian team pages. Sites known to fail (Wikipedia, FBref, ESPN, etc.) are excluded.
96
+
97
+ ### Budget allocation
98
+
99
+ `MATCH_RESEARCH_BUDGET` defaults to **$0.50** per match (set in `.env`). All spending — baseline, agent-planned, and fallback — must stay within that cap.
100
+
101
+ ```
102
+ MATCH_RESEARCH_BUDGET ($0.50 default)
103
+ ├── Baseline searches ($0.056 — always merged first)
104
+ ├── Agent-chosen calls (Skim402, GDELT, extra Tavily/Brave, etc.)
105
+ │ └── Shopper plans against ~$0.44 remaining after baseline
106
+ └── Fallback calls (if data quality is poor)
107
+ └── Uses whatever is left: BUDGET − total_spent so far
108
+ ```
109
+
110
+ **Wallet checks:** `predict.py` aborts if on-chain USDC balance is below **$0.10**. Recommended starting balance is **$2.00** (~4 matches at default budget). Actual spend per match varies — baseline alone is $0.056; with agent and fallback calls, recent matches typically land around **$0.08–$0.12**.
111
+
112
+ ---
113
+
114
  ## Self-improving strategy
115
 
116
  `strategy.md` is the agent's accumulated knowledge — a short document (≤500 words) of rules and learnings. It grows one rule at a time, each tagged with the match that informed it. The predictor reads the full strategy before every match; the reflector updates it after every result.
117
 
118
+ The strategy also tracks which x402 data services have been useful across past matches, so the agent learns to allocate its budget more efficiently over time.
119
 
120
  ---
121
 
 
130
 
131
  **Balance check:** At startup, `predict.py` reads the on-chain USDC balance by calling `balanceOf` on the USDC contract. If it's below $0.10, the run aborts.
132
 
133
+ **x402 session:** `wallet.get_x402_client()` returns a `requests.Session` wired with `ExactEvmScheme` for the configured chain. Any request that returns `402 Payment Required` is handled automatically: the client signs a payment transaction with the wallet's private key, submits it on-chain, and retries — all transparent to the calling code. Both GET and POST endpoints are supported.
134
 
135
+ **Cost tracking:** `research_cost`, `wallet_before`, and `wallet_after` are saved per match in `results.json`. `wallet_after` is an estimate (`balance − total_spent`); the on-chain balance is not re-fetched mid-run.
136
 
137
  ---
138
 
139
  ## Web dashboard (`app.py`)
140
 
141
+ FastAPI app deployed on HF Spaces. Routes:
142
 
143
  | Route | Content |
144
  |-------|---------|
145
+ | `/` | Live dashboard: upcoming fixtures, predictions (pick + confidence + research cost — no bet sizing), x402 spend table, strategy snippet |
146
  | `/match/HOME_AWAY` | Full detail: analyst needs, purchased endpoints with raw data, research gaps, Gemini reasoning, evaluation, strategy at prediction time |
147
+ | `/strategy` | Current strategy + snapshot history across all matches |
148
+ | `/learnings` | Git-tracked strategy evolution with line diffs and post-match evaluations |
149
  | `/api/results` | Raw `results.json` as JSON |
150
  | `/api/schedule` | Raw `schedule.json` as JSON |
151
 
 
203
 
204
  ## Scheduling
205
 
206
+ Matches are scheduled automatically with cron.
207
 
208
  ```bash
209
+ # Fetch all WC 2026 fixtures from ESPN and schedule upcoming matches
 
 
 
210
  python setup_schedule.py
211
+
212
+ # Preview without writing cron entries
213
+ python setup_schedule.py --dry-run
214
+
215
+ # Schedule a single match manually
216
+ python schedule_match.py NED JPN 2026-06-14T20:00:00Z
217
  ```
218
 
219
+ `setup_schedule.py` fetches fixtures from the ESPN public API, writes `schedule.json`, adds cron entries for all upcoming matches, and pushes the schedule to GitHub. Predict runs 30 minutes before kickoff; reflect runs 2 hours 30 minutes after kickoff. Logs go to `logs/HOME_AWAY.log`.
220
 
221
  ---
222
 
223
  ## Manual run
224
 
225
  ```bash
226
+ # Predict (kickoff read from schedule.json; pass timestamp for retroactive mode)
227
+ python predict.py NED JPN
228
+ python predict.py NED JPN 2026-06-14T20:00Z # retroactive override
229
 
230
  # Reflect (after the match is complete)
231
  python reflect.py NED JPN
 
234
  uvicorn app:app --reload --port 7860
235
  ```
236
 
237
+ Retroactive mode is automatically detected when the kickoff timestamp is in the past, and constrains research to pre-match sources only (no live scoreboards or post-match reports).
238
 
239
  ---
240
 
241
  ## File structure
242
 
243
  ```
244
+ predict.py # Pre-match: analyst → shopper → baseline search → fetch → fallback → predict
245
  reflect.py # Post-match: result + evaluation + strategy update
246
  app.py # FastAPI web dashboard
247
  wallet.py # USDC balance check + x402 payment session
 
249
  discord_notify.py # Discord bot notifications
250
  setup_wallet.py # One-time wallet keypair generation
251
  schedule_match.py # Add cron entries for a single match
252
+ setup_schedule.py # Fetch ESPN fixtures + bulk-load cron + push schedule.json
253
+ make_thumbnail.py # Generate HF Space thumbnail (1280×720)
254
+ results.json # All predictions and outcomes
255
  strategy.md # Agent's accumulated strategy (rewritten each match)
256
+ schedule.json # Fixture list with kickoff times (from ESPN)
257
+ logs/ # Per-match cron output
258
  ```
259
 
260
  ---
261
 
262
  ## Dependencies
263
 
264
+ - **Gemini Flash** — multi-stage reasoning (analyst → shopper → predictor; separate evaluator + reflector)
265
+ - **x402** — HTTP 402 micropayment protocol for real-time sports data and search APIs
266
  - **Web3 / eth-account** — Base chain interaction for balance checks and payment signing
267
  - **FastAPI / uvicorn** — web dashboard
268
+ - **ESPN public API** — free fixture list and post-match result fetching
269
+ - **Pillow** — HF Space thumbnail generation
app.py CHANGED
@@ -64,6 +64,46 @@ def _team(code: str) -> str:
64
  flag = _flag(code)
65
  return f"{flag} {code}" if flag else code
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  CSS = """
68
  <style>
69
  * { box-sizing: border-box; margin: 0; padding: 0; }
@@ -345,12 +385,14 @@ def _kickoff_sort_key(r: dict) -> float:
345
  return kdt.timestamp() if kdt else 0.0
346
 
347
 
348
- def _render_match_card(r: dict) -> str:
349
  pred = r.get("prediction", {})
350
  res = r.get("result")
351
  used = r.get("services_used", [])
352
  planned = r.get("services_planned", [])
353
  state = _match_state(r)
 
 
354
 
355
  x402_html = ""
356
  if used:
@@ -370,25 +412,28 @@ def _render_match_card(r: dict) -> str:
370
  cls = "correct" if r.get("correct") else "incorrect"
371
  eval_snippet = _esc((r.get("evaluation") or "")[:180])
372
  result_html = f'''<div class="result-bar {cls}">
373
- Result: <span class="result-score">{_team(r['home'])} {res['home_score']}–{res['away_score']} {_team(r['away'])}</span>
374
  {f'<div class="eval-text">{eval_snippet}{"…" if len(r.get("evaluation", "")) > 180 else ""}</div>' if eval_snippet else ""}
375
  </div>'''
376
  elif res and not r.get("reflected"):
377
  result_html = f'''<div class="result-bar" style="background:#1a1810;border-left:3px solid #f9a825;">
378
- Provisional score: <span class="result-score">{_team(r['home'])} {res['home_score']}–{res['away_score']} {_team(r['away'])}</span>
379
  <div class="eval-text">Official reflection not run yet — win/loss not scored.</div>
380
  </div>'''
381
 
382
  rel, rel_color = _time_rel(r.get("kickoff", ""))
383
  kickoff_note = f'<span style="color:{rel_color}">{rel}</span>' if rel else ""
384
 
 
 
 
385
  return f"""<div class="match-card">
386
  <details>
387
  <summary style="list-style:none;cursor:pointer;">
388
  <div class="match-header">
389
  <div>
390
  <div class="match-title">{_team(r['home'])} vs {_team(r['away'])}</div>
391
- <div class="match-time">{kickoff_note}{' &nbsp;·&nbsp; ' if kickoff_note else ''}Pick: <b>{_team(_pick_display(pred.get('pick', '?'), r['home'], r['away']))}</b> &nbsp;·&nbsp; conf {pred.get("confidence", "?")}/10</div>
392
  <div class="status-line">{_esc(state['sublabel'])}</div>
393
  </div>
394
  <div style="display:flex;align-items:center;gap:8px;">{state['badge']}<span style="color:#444;font-size:16px;">⌄</span></div>
@@ -396,7 +441,7 @@ def _render_match_card(r: dict) -> str:
396
  </summary>
397
  <div class="match-body">
398
  <div class="pred-row">
399
- <div class="pred-item"><div class="label">Pick</div><div class="value pick">{_team(_pick_display(pred.get('pick', '?'), r['home'], r['away']))}</div></div>
400
  <div class="pred-item"><div class="label">Confidence</div><div class="value"><span class="tooltip-wrap">{pred.get("confidence", "?")}/10<span class="tooltip-box">{_esc(pred.get("confidence_reason", "Hover reason not available for this prediction."))}</span></span></div></div>
401
  <div class="pred-item"><div class="label">Research cost</div><div class="value" style="color:#f9a825;">${r.get("research_cost", 0):.4f}</div></div>
402
  </div>
@@ -495,6 +540,7 @@ async def dashboard():
495
  losses = len(reflected) - wins
496
 
497
  html = _pipeline_html(upcoming_total, len(awaiting_reflect), len(reflected), wins, losses)
 
498
 
499
  # ── 1. Awaiting prediction ──────────────────────────────────────────────
500
  stage_bar = _stage_indicator(schedule, results_raw) if schedule else ""
@@ -529,7 +575,7 @@ async def dashboard():
529
 
530
  # ── 2. Predicted — upcoming ───────────────────────────────────────────
531
  if upcoming_predicted:
532
- cards = "".join(_render_match_card(r) for r in upcoming_predicted)
533
  html += f"""<div class="section">
534
  <h2>Predicted — Upcoming</h2>
535
  <div class="section-desc">Pick is locked in before kickoff. Reflection runs automatically ~2.5h after the final whistle.</div>
@@ -540,7 +586,7 @@ async def dashboard():
540
  html += '<div class="section"><h2>Predicted — Awaiting Reflection</h2>'
541
  html += '<div class="section-desc">Match has kicked off. <code>reflect.py</code> fetches the result, scores the prediction, and updates strategy (~2.5h after kickoff).</div>'
542
  if awaiting_reflect:
543
- cards = "".join(_render_match_card(r) for r in awaiting_reflect)
544
  html += cards + "</div>"
545
  else:
546
  html += '<div class="empty-section">Nothing here — no played matches waiting on reflection.</div></div>'
@@ -554,7 +600,7 @@ async def dashboard():
554
  key=lambda r: r.get("reflected_at") or "",
555
  reverse=True,
556
  )
557
- cards = "".join(_render_match_card(r) for r in reflected_sorted)
558
  html += cards + "</div>"
559
  else:
560
  html += '<div class="empty-section">No reflections yet — they appear here after the first match finishes and <code>reflect.py</code> runs.</div></div>'
@@ -670,6 +716,7 @@ async def match_detail(match_key: str):
670
  <div class="pred-item"><div class="label">Pick</div><div class="value pick">{_team(_pick_display(pred.get('pick','?'), home, away))}</div></div>
671
  <div class="pred-item"><div class="label">Confidence</div><div class="value"><span class="tooltip-wrap">{pred.get("confidence","?")}/10<span class="tooltip-box">{_esc(pred.get("confidence_reason","Hover reason not available for this prediction."))}</span></span></div></div>
672
  </div>
 
673
  <div class="reasoning">"{_esc(pred.get("reasoning",""))}"</div>
674
  </div>
675
  {needs_html}
 
64
  flag = _flag(code)
65
  return f"{flag} {code}" if flag else code
66
 
67
+
68
+ def _team_names() -> dict[str, str]:
69
+ """FIFA code → full country name from schedule.json."""
70
+ names: dict[str, str] = {}
71
+ for f in _load("schedule.json", []):
72
+ if f.get("home") and f.get("home_name"):
73
+ names[f["home"]] = f["home_name"]
74
+ if f.get("away") and f.get("away_name"):
75
+ names[f["away"]] = f["away_name"]
76
+ return names
77
+
78
+
79
+ def _team_full(code: str, names: dict[str, str] | None = None) -> str:
80
+ """Team with flag emoji and full country name."""
81
+ flag = _flag(code)
82
+ name = (names or {}).get(code.upper(), "")
83
+ if name:
84
+ return f"{flag} {name}" if flag else name
85
+ return _team(code)
86
+
87
+
88
+ def _pick_display_full(pick: str, home: str, away: str, names: dict[str, str]) -> str:
89
+ """Translate home/away/draw to full team label."""
90
+ if pick == "home":
91
+ return _team_full(home, names)
92
+ if pick == "away":
93
+ return _team_full(away, names)
94
+ return "DRAW"
95
+
96
+
97
+ def _prob_summary(pred: dict, home: str, away: str) -> str:
98
+ """Win probability line when model outputs HOME/DRAW/AWAY percentages."""
99
+ probs = pred.get("probabilities") or {}
100
+ if not probs:
101
+ return ""
102
+ h = probs.get("home", "?")
103
+ d = probs.get("draw", "?")
104
+ a = probs.get("away", "?")
105
+ return f"model {h}%/{d}%/{a}% ({home}/{d}/{away})"
106
+
107
  CSS = """
108
  <style>
109
  * { box-sizing: border-box; margin: 0; padding: 0; }
 
385
  return kdt.timestamp() if kdt else 0.0
386
 
387
 
388
+ def _render_match_card(r: dict, names: dict[str, str] | None = None) -> str:
389
  pred = r.get("prediction", {})
390
  res = r.get("result")
391
  used = r.get("services_used", [])
392
  planned = r.get("services_planned", [])
393
  state = _match_state(r)
394
+ if names is None:
395
+ names = _team_names()
396
 
397
  x402_html = ""
398
  if used:
 
412
  cls = "correct" if r.get("correct") else "incorrect"
413
  eval_snippet = _esc((r.get("evaluation") or "")[:180])
414
  result_html = f'''<div class="result-bar {cls}">
415
+ Result: <span class="result-score">{_team_full(r['home'], names)} {res['home_score']}–{res['away_score']} {_team_full(r['away'], names)}</span>
416
  {f'<div class="eval-text">{eval_snippet}{"…" if len(r.get("evaluation", "")) > 180 else ""}</div>' if eval_snippet else ""}
417
  </div>'''
418
  elif res and not r.get("reflected"):
419
  result_html = f'''<div class="result-bar" style="background:#1a1810;border-left:3px solid #f9a825;">
420
+ Provisional score: <span class="result-score">{_team_full(r['home'], names)} {res['home_score']}–{res['away_score']} {_team_full(r['away'], names)}</span>
421
  <div class="eval-text">Official reflection not run yet — win/loss not scored.</div>
422
  </div>'''
423
 
424
  rel, rel_color = _time_rel(r.get("kickoff", ""))
425
  kickoff_note = f'<span style="color:{rel_color}">{rel}</span>' if rel else ""
426
 
427
+ prob_note = _prob_summary(pred, r["home"], r["away"])
428
+ prob_html = f' &nbsp;·&nbsp; {prob_note}' if prob_note else ""
429
+
430
  return f"""<div class="match-card">
431
  <details>
432
  <summary style="list-style:none;cursor:pointer;">
433
  <div class="match-header">
434
  <div>
435
  <div class="match-title">{_team(r['home'])} vs {_team(r['away'])}</div>
436
+ <div class="match-time">{kickoff_note}{' &nbsp;·&nbsp; ' if kickoff_note else ''}Pick: <b>{_team(_pick_display(pred.get('pick', '?'), r['home'], r['away']))}</b> &nbsp;·&nbsp; conf {pred.get("confidence", "?")}/10{prob_html}</div>
437
  <div class="status-line">{_esc(state['sublabel'])}</div>
438
  </div>
439
  <div style="display:flex;align-items:center;gap:8px;">{state['badge']}<span style="color:#444;font-size:16px;">⌄</span></div>
 
441
  </summary>
442
  <div class="match-body">
443
  <div class="pred-row">
444
+ <div class="pred-item"><div class="label">Pick</div><div class="value pick">{_pick_display_full(pred.get('pick', '?'), r['home'], r['away'], names)}</div></div>
445
  <div class="pred-item"><div class="label">Confidence</div><div class="value"><span class="tooltip-wrap">{pred.get("confidence", "?")}/10<span class="tooltip-box">{_esc(pred.get("confidence_reason", "Hover reason not available for this prediction."))}</span></span></div></div>
446
  <div class="pred-item"><div class="label">Research cost</div><div class="value" style="color:#f9a825;">${r.get("research_cost", 0):.4f}</div></div>
447
  </div>
 
540
  losses = len(reflected) - wins
541
 
542
  html = _pipeline_html(upcoming_total, len(awaiting_reflect), len(reflected), wins, losses)
543
+ team_names = _team_names()
544
 
545
  # ── 1. Awaiting prediction ──────────────────────────────────────────────
546
  stage_bar = _stage_indicator(schedule, results_raw) if schedule else ""
 
575
 
576
  # ── 2. Predicted — upcoming ───────────────────────────────────────────
577
  if upcoming_predicted:
578
+ cards = "".join(_render_match_card(r, team_names) for r in upcoming_predicted)
579
  html += f"""<div class="section">
580
  <h2>Predicted — Upcoming</h2>
581
  <div class="section-desc">Pick is locked in before kickoff. Reflection runs automatically ~2.5h after the final whistle.</div>
 
586
  html += '<div class="section"><h2>Predicted — Awaiting Reflection</h2>'
587
  html += '<div class="section-desc">Match has kicked off. <code>reflect.py</code> fetches the result, scores the prediction, and updates strategy (~2.5h after kickoff).</div>'
588
  if awaiting_reflect:
589
+ cards = "".join(_render_match_card(r, team_names) for r in awaiting_reflect)
590
  html += cards + "</div>"
591
  else:
592
  html += '<div class="empty-section">Nothing here — no played matches waiting on reflection.</div></div>'
 
600
  key=lambda r: r.get("reflected_at") or "",
601
  reverse=True,
602
  )
603
+ cards = "".join(_render_match_card(r, team_names) for r in reflected_sorted)
604
  html += cards + "</div>"
605
  else:
606
  html += '<div class="empty-section">No reflections yet — they appear here after the first match finishes and <code>reflect.py</code> runs.</div></div>'
 
716
  <div class="pred-item"><div class="label">Pick</div><div class="value pick">{_team(_pick_display(pred.get('pick','?'), home, away))}</div></div>
717
  <div class="pred-item"><div class="label">Confidence</div><div class="value"><span class="tooltip-wrap">{pred.get("confidence","?")}/10<span class="tooltip-box">{_esc(pred.get("confidence_reason","Hover reason not available for this prediction."))}</span></span></div></div>
718
  </div>
719
+ {f'<div style="font-size:12px;color:#666;margin-top:8px;">Win model: {_esc(_prob_summary(pred, home, away))}</div>' if _prob_summary(pred, home, away) else ""}
720
  <div class="reasoning">"{_esc(pred.get("reasoning",""))}"</div>
721
  </div>
722
  {needs_html}
gemini.py CHANGED
@@ -10,16 +10,28 @@ log = logging.getLogger(__name__)
10
  GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent"
11
 
12
 
13
- def generate(prompt: str, retries: int = 2) -> str:
 
 
 
 
 
14
  """Call Gemini and return the text response, retrying on empty replies."""
15
  key = os.getenv("GEMINI_API_KEY", "")
16
  last_err = None
 
 
 
 
17
  for attempt in range(retries + 1):
18
  try:
19
  resp = requests.post(
20
  GEMINI_URL,
21
  headers={"Content-Type": "application/json", "X-goog-api-key": key},
22
- json={"contents": [{"parts": [{"text": prompt}]}]},
 
 
 
23
  timeout=90,
24
  )
25
  resp.raise_for_status()
 
10
  GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent"
11
 
12
 
13
+ def generate(
14
+ prompt: str,
15
+ retries: int = 2,
16
+ temperature: float = 0.7,
17
+ json_mode: bool = False,
18
+ ) -> str:
19
  """Call Gemini and return the text response, retrying on empty replies."""
20
  key = os.getenv("GEMINI_API_KEY", "")
21
  last_err = None
22
+ generation_config: dict = {"temperature": temperature}
23
+ if json_mode:
24
+ generation_config["responseMimeType"] = "application/json"
25
+
26
  for attempt in range(retries + 1):
27
  try:
28
  resp = requests.post(
29
  GEMINI_URL,
30
  headers={"Content-Type": "application/json", "X-goog-api-key": key},
31
+ json={
32
+ "contents": [{"parts": [{"text": prompt}]}],
33
+ "generationConfig": generation_config,
34
+ },
35
  timeout=90,
36
  )
37
  resp.raise_for_status()
make_thumbnail.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate a 1280x720 thumbnail for the World Cup Prediction Agent."""
2
+
3
+ import math
4
+ from PIL import Image, ImageDraw, ImageFont
5
+
6
+ W, H = 1280, 720
7
+
8
+ NAVY = (8, 15, 40)
9
+ GOLD = (255, 200, 50)
10
+ WHITE = (255, 255, 255)
11
+ GREY = (140, 155, 180)
12
+
13
+ FONT_BOLD = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
14
+ FONT_PLAIN = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
15
+
16
+
17
+ def load(path, size):
18
+ return ImageFont.truetype(path, size)
19
+
20
+
21
+ def draw_soccer_ball(draw, cx, cy, r):
22
+ draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=WHITE, outline=(200, 200, 200), width=2)
23
+ n = 5
24
+ pts = []
25
+ for i in range(n):
26
+ angle = math.radians(-90 + i * 72)
27
+ pts.append((cx + r * 0.38 * math.cos(angle), cy + r * 0.38 * math.sin(angle)))
28
+ draw.polygon(pts, fill=(30, 30, 30))
29
+ outer_r = r * 0.72
30
+ for i in range(n):
31
+ angle = math.radians(-90 + i * 72)
32
+ ox = cx + outer_r * math.cos(angle)
33
+ oy = cy + outer_r * math.sin(angle)
34
+ inner = r * 0.22
35
+ pts2 = []
36
+ for j in range(5):
37
+ a2 = math.radians(angle * (180 / math.pi) + j * 72 + 36)
38
+ pts2.append((ox + inner * math.cos(a2), oy + inner * math.sin(a2)))
39
+ draw.polygon(pts2, fill=(30, 30, 30))
40
+ draw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(50, 50, 50), width=3)
41
+
42
+
43
+ def main():
44
+ img = Image.new("RGB", (W, H), NAVY)
45
+ draw = ImageDraw.Draw(img)
46
+
47
+ # Subtle horizontal rule (field centre line feel)
48
+ draw.line([(0, H // 2), (W, H // 2)], fill=(18, 30, 65), width=1)
49
+
50
+ # Gold top bar
51
+ draw.rectangle([0, 0, W, 5], fill=GOLD)
52
+
53
+ # Ball — left-of-centre, vertically centred
54
+ ball_cx, ball_cy, ball_r = 310, H // 2, 200
55
+ draw_soccer_ball(draw, ball_cx, ball_cy, ball_r)
56
+
57
+ # Right-side text
58
+ tx = 570
59
+ ty = 160
60
+
61
+ f_small = load(FONT_BOLD, 22)
62
+ f_title1 = load(FONT_BOLD, 100)
63
+ f_title2 = load(FONT_BOLD, 100)
64
+ f_tag = load(FONT_PLAIN, 28)
65
+
66
+ draw.text((tx, ty), "WORLD CUP 2026", font=f_small, fill=GOLD)
67
+ draw.text((tx, ty + 36), "PREDICTION", font=f_title1, fill=WHITE)
68
+ draw.text((tx, ty + 148), "AGENT", font=f_title2, fill=GOLD)
69
+ draw.text((tx, ty + 268), "Self-improving AI · x402 payments", font=f_tag, fill=GREY)
70
+
71
+ out_path = "thumbnail.png"
72
+ img.save(out_path, quality=95)
73
+ print(f"Saved {out_path}")
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
predict.py CHANGED
@@ -19,6 +19,7 @@ import requests
19
  from dotenv import load_dotenv
20
 
21
  import discord_notify
 
22
  import wallet
23
 
24
  # ── Setup ──────────────────────────────────────────────────────────────────
@@ -414,7 +415,7 @@ except Exception as e:
414
 
415
  # ── Step 3: Agent plans research ───────────────────────────────────────────
416
 
417
- recent_results = results[-3:] if results else []
418
 
419
  # Enrich services with actual endpoint paths from their OpenAPI specs
420
  def _get_endpoints(base_url):
@@ -993,7 +994,7 @@ log("Research complete. Spent $%.4f. Estimated balance: $%.4f", total_spent, bal
993
 
994
  useful_count = sum(1 for s in services_used if not _is_low_quality_data(s.get("data", "")))
995
 
996
- # ── Step 5: Make prediction ────────────────────────────────────────────────
997
 
998
  context_text = ""
999
  if context:
@@ -1002,75 +1003,91 @@ if context:
1002
  else:
1003
  context_text = "(no paid research data purchased)"
1004
 
1005
- predict_prompt = f"""You are a World Cup match predictor. Analyze the following and make a prediction.
1006
-
1007
- Match: {MATCH}
1008
- Home team: {home_name} ({HOME})
1009
- Away team: {away_name} ({AWAY})
1010
- Kickoff: {kickoff}
1011
- Research spent: ${total_spent:.4f} USDC on {len(services_used)} data source(s)
1012
- Useful sources: {useful_count} of {len(services_used)}
1013
-
1014
- Current strategy (your accumulated learnings):
1015
- {strategy if strategy else "(no strategy yet — first match)"}
1016
-
1017
- Research data purchased:
1018
- {context_text}
1019
-
1020
- Recent match history and outcomes:
1021
- {json.dumps(recent_results, indent=2) if recent_results else "(no history yet)"}
1022
 
1023
- INSTRUCTIONS:
1024
- - Base your prediction on the research data above. Search results (Tavily/Brave) contain the most current news.
1025
- - Weigh: form, injuries/squad news, tactics, H2H, group context. Ignore venue/weather unless clearly decisive.
1026
- - You MUST always output the required format lines below — never ask for more data or return tool calls.
 
 
 
 
 
 
 
 
 
1027
 
1028
- CONFIDENCE CALIBRATION (use the full 1-10 range — do NOT default to 5):
1029
- - 9-10: Clear favorite with 3+ corroborating signals (form, squad fitness, tactics, H2H) and no major unknowns
1030
- - 7-8: Solid edge for one side backed by multiple research sources; only minor gaps remain
1031
- - 5-6: Genuinely balanced matchup OR directly conflicting signals — use only when research shows a true toss-up
1032
- - 1-4: Near-total data failure only (rare with search data available)
1033
- You purchased {len(services_used)} sources ({useful_count} high-quality). With this research depth, confidence below 7 requires explicit justification in CONFIDENCE_REASON. When signals align, use 8-10.
 
 
 
 
 
 
 
 
1034
 
1035
- Analyze the match thoroughly, then end your response with EXACTLY these 4 lines:
1036
- PICK: [home|away|draw]
1037
- CONFIDENCE: [1-10]
1038
- CONFIDENCE_REASON: [one sentence explaining why confidence is that specific number — what raises or lowers it]
1039
- REASONING: [one sentence summarizing the key factor driving the pick]"""
1040
 
1041
- log("Asking Gemini for prediction...")
1042
  full_reasoning = ""
 
1043
  for attempt in range(3):
1044
  try:
1045
  suffix = ""
1046
  if attempt > 0:
1047
  suffix = (
1048
- "\n\nCRITICAL: Your previous response was invalid. "
1049
- "Do NOT request more data. Analyze what you have and end with EXACTLY:\n"
1050
- "PICK: [home|away|draw]\nCONFIDENCE: [1-10]\n"
1051
- "CONFIDENCE_REASON: [sentence]\nREASONING: [sentence]"
1052
  )
1053
- pred_resp_text = gemini.generate(predict_prompt + suffix)
 
 
 
1054
  if pred_resp_text.strip() and re.search(r"PICK:\s*(home|away|draw)", pred_resp_text, re.I):
 
1055
  full_reasoning = pred_resp_text
1056
  break
1057
  err("Prediction attempt %d: missing PICK line", attempt + 1)
1058
  except Exception as e:
1059
- err("Gemini prediction call failed (attempt %d): %s", attempt + 1, e)
1060
-
1061
- # Parse structured fields
1062
- def _parse(pattern, text, default):
1063
- m = re.search(pattern, text, re.IGNORECASE)
1064
- return m.group(1).strip() if m else default
1065
-
1066
- pick_raw = _parse(r"PICK:\s*(\w+)", full_reasoning, "home").lower()
1067
- pick = pick_raw if pick_raw in ("home", "away", "draw") else "home"
1068
- confidence_raw = _parse(r"CONFIDENCE:\s*(\d+)", full_reasoning, "5")
1069
- confidence = max(1, min(10, int(confidence_raw)))
1070
- confidence_reason = _parse(r"CONFIDENCE_REASON:\s*(.+)", full_reasoning, "")
1071
- reasoning = _parse(r"REASONING:\s*(.+)", full_reasoning, "Insufficient data for strong prediction")
1072
-
1073
- log("Prediction: PICK=%s CONFIDENCE=%d", pick, confidence)
 
 
 
 
 
 
 
1074
  log("Reasoning: %s", reasoning)
1075
 
1076
  # ── Step 6: Save state and push to GitHub ─────────────────────────────────
@@ -1091,9 +1108,12 @@ entry = {
1091
  "prediction": {
1092
  "pick": pick,
1093
  "confidence": confidence,
1094
- "confidence_reason": confidence_reason,
1095
  "reasoning": reasoning,
 
1096
  },
 
 
1097
  "full_reasoning": full_reasoning,
1098
  "retroactive": RETROACTIVE,
1099
  "result": None,
 
19
  from dotenv import load_dotenv
20
 
21
  import discord_notify
22
+ import prediction_intel
23
  import wallet
24
 
25
  # ── Setup ──────────────────────────────────────────────────────────────────
 
415
 
416
  # ── Step 3: Agent plans research ───────────────────────────────────────────
417
 
418
+ recent_results = results[-3:] if results else [] # unused — kept for log compatibility
419
 
420
  # Enrich services with actual endpoint paths from their OpenAPI specs
421
  def _get_endpoints(base_url):
 
994
 
995
  useful_count = sum(1 for s in services_used if not _is_low_quality_data(s.get("data", "")))
996
 
997
+ # ── Step 5: Intelligent prediction pipeline ────────────────────────────────
998
 
999
  context_text = ""
1000
  if context:
 
1003
  else:
1004
  context_text = "(no paid research data purchased)"
1005
 
1006
+ learning_context = prediction_intel.build_learning_context(results)
1007
+ fixture_context = prediction_intel.build_fixture_context(
1008
+ HOME, AWAY, home_name, away_name, schedule, results, kickoff,
1009
+ )
1010
+ espn_form = prediction_intel.fetch_espn_tournament_form(HOME, AWAY, kickoff)
1011
+ log("Fixture context loaded; ESPN form: %d chars", len(espn_form))
 
 
 
 
 
 
 
 
 
 
 
1012
 
1013
+ synthesis = {}
1014
+ stress_test = {}
1015
+ try:
1016
+ log("Stage 3: Synthesizing evidence...")
1017
+ synthesis = prediction_intel.synthesize_evidence(
1018
+ MATCH, home_name, away_name, kickoff, strategy, context_text,
1019
+ learning_context, fixture_context, espn_form,
1020
+ useful_count, len(services_used), RETROACTIVE,
1021
+ )
1022
+ log("Stage 3 complete — data_quality=%s", synthesis.get("data_quality"))
1023
+ except Exception as e:
1024
+ err("Stage 3 synthesis failed: %s", e)
1025
+ synthesis = {"data_quality": "low", "contradictions": [str(e)]}
1026
 
1027
+ try:
1028
+ log("Stage 4: Stress-testing evidence...")
1029
+ stress_test = prediction_intel.stress_test_evidence(
1030
+ MATCH, home_name, away_name, synthesis, strategy,
1031
+ )
1032
+ log(
1033
+ "Stage 4 complete — favorite=%s cap=%s draw_risk=%s",
1034
+ stress_test.get("favorite"),
1035
+ stress_test.get("confidence_cap"),
1036
+ stress_test.get("draw_risk"),
1037
+ )
1038
+ except Exception as e:
1039
+ err("Stage 4 stress test failed: %s", e)
1040
+ stress_test = {"confidence_cap": 6, "draw_risk": "medium"}
1041
 
1042
+ stress_cap = stress_test.get("confidence_cap")
1043
+ if isinstance(stress_cap, str) and stress_cap.isdigit():
1044
+ stress_cap = int(stress_cap)
1045
+ elif not isinstance(stress_cap, int):
1046
+ stress_cap = None
1047
 
1048
+ log("Stage 5: Final calibrated prediction...")
1049
  full_reasoning = ""
1050
+ parsed = None
1051
  for attempt in range(3):
1052
  try:
1053
  suffix = ""
1054
  if attempt > 0:
1055
  suffix = (
1056
+ "\n\nCRITICAL: End with HOME_PCT, DRAW_PCT, AWAY_PCT (sum 100), "
1057
+ "then PICK, CONFIDENCE, CONFIDENCE_REASON, REASONING."
 
 
1058
  )
1059
+ pred_resp_text = prediction_intel.make_final_prediction(
1060
+ MATCH, HOME, AWAY, home_name, away_name, kickoff,
1061
+ strategy, synthesis, stress_test, useful_count, len(services_used),
1062
+ ) + suffix
1063
  if pred_resp_text.strip() and re.search(r"PICK:\s*(home|away|draw)", pred_resp_text, re.I):
1064
+ parsed = prediction_intel.parse_prediction_response(pred_resp_text, stress_cap)
1065
  full_reasoning = pred_resp_text
1066
  break
1067
  err("Prediction attempt %d: missing PICK line", attempt + 1)
1068
  except Exception as e:
1069
+ err("Prediction attempt %d failed: %s", attempt + 1, e)
1070
+
1071
+ if parsed is None:
1072
+ parsed = {
1073
+ "pick": "home",
1074
+ "confidence": 4,
1075
+ "confidence_reason": "Pipeline failed — low-confidence fallback",
1076
+ "reasoning": "Could not complete prediction pipeline",
1077
+ "probabilities": {"home": 40, "draw": 30, "away": 30},
1078
+ "full_reasoning": full_reasoning or "",
1079
+ }
1080
+
1081
+ pick = parsed["pick"]
1082
+ confidence = parsed["confidence"]
1083
+ confidence_reason = parsed["confidence_reason"]
1084
+ reasoning = parsed["reasoning"]
1085
+ probabilities = parsed["probabilities"]
1086
+
1087
+ log(
1088
+ "Prediction: PICK=%s CONFIDENCE=%d probs=%s",
1089
+ pick, confidence, probabilities,
1090
+ )
1091
  log("Reasoning: %s", reasoning)
1092
 
1093
  # ── Step 6: Save state and push to GitHub ─────────────────────────────────
 
1108
  "prediction": {
1109
  "pick": pick,
1110
  "confidence": confidence,
1111
+ "confidence_reason": confidence_reason,
1112
  "reasoning": reasoning,
1113
+ "probabilities": probabilities,
1114
  },
1115
+ "evidence_synthesis": synthesis,
1116
+ "stress_test": stress_test,
1117
  "full_reasoning": full_reasoning,
1118
  "retroactive": RETROACTIVE,
1119
  "result": None,
prediction_intel.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Structured prediction pipeline — evidence synthesis, stress-test, calibrated pick."""
2
+
3
+ import json
4
+ import re
5
+ from datetime import datetime, timedelta, timezone
6
+
7
+ import gemini
8
+ import requests
9
+
10
+
11
+ def dedupe_results(results: list) -> list:
12
+ latest: dict[tuple, dict] = {}
13
+ for r in results:
14
+ key = (r.get("home"), r.get("away"))
15
+ prev = latest.get(key)
16
+ if prev is None:
17
+ latest[key] = r
18
+ elif r.get("reflected") and not prev.get("reflected"):
19
+ latest[key] = r
20
+ elif prev.get("reflected") and not r.get("reflected"):
21
+ continue
22
+ else:
23
+ latest[key] = r
24
+ return list(latest.values())
25
+
26
+
27
+ def build_learning_context(results: list, limit: int = 8) -> str:
28
+ """Summarize reflected matches — outcomes, mistakes, data lessons."""
29
+ reflected = sorted(
30
+ [r for r in dedupe_results(results) if r.get("reflected")],
31
+ key=lambda r: r.get("reflected_at") or "",
32
+ reverse=True,
33
+ )[:limit]
34
+ if not reflected:
35
+ return "(no reflected matches yet)"
36
+
37
+ lines = []
38
+ for r in reflected:
39
+ pred = r.get("prediction", {})
40
+ res = r.get("result") or {}
41
+ pick = pred.get("pick", "?")
42
+ correct = r.get("correct")
43
+ tag = "CORRECT" if correct else "WRONG"
44
+ score = f"{res.get('home_score', '?')}-{res.get('away_score', '?')}"
45
+ eval_snip = (r.get("evaluation") or "").replace("\n", " ")[:200]
46
+ lines.append(
47
+ f"- {r['home']} vs {r['away']}: picked {pick} ({pred.get('confidence', '?')}/10) "
48
+ f"→ {score} [{tag}]. Learning: {eval_snip}"
49
+ )
50
+ return "\n".join(lines)
51
+
52
+
53
+ def build_fixture_context(
54
+ home: str,
55
+ away: str,
56
+ home_name: str,
57
+ away_name: str,
58
+ schedule: list,
59
+ results: list,
60
+ kickoff: str,
61
+ ) -> str:
62
+ """Group-stage neighbors and results already played in this tournament."""
63
+ try:
64
+ kickoff_dt = datetime.fromisoformat(kickoff.replace("Z", "+00:00"))
65
+ except ValueError:
66
+ kickoff_dt = None
67
+
68
+ group_teams = {home, away}
69
+ for f in schedule:
70
+ if f.get("stage") != "Group Stage":
71
+ continue
72
+ h, a = f.get("home"), f.get("away")
73
+ if h in (home, away) or a in (home, away):
74
+ group_teams.add(h)
75
+ group_teams.add(a)
76
+
77
+ played = []
78
+ for r in dedupe_results(results):
79
+ if not r.get("result"):
80
+ continue
81
+ h, a = r.get("home"), r.get("away")
82
+ if h not in group_teams and a not in group_teams:
83
+ continue
84
+ res = r["result"]
85
+ played.append(
86
+ f"{h} {res['home_score']}-{res['away_score']} {a} (winner: {res['winner']})"
87
+ )
88
+
89
+ upcoming = []
90
+ for f in schedule:
91
+ if f.get("stage") != "Group Stage":
92
+ continue
93
+ h, a = f.get("home"), f.get("away")
94
+ if h not in group_teams and a not in group_teams:
95
+ continue
96
+ k = f.get("kickoff_utc", "")
97
+ if kickoff_dt and k:
98
+ try:
99
+ fdt = datetime.fromisoformat(k.replace("Z", "+00:00"))
100
+ if fdt <= kickoff_dt and (h, a) != (home, away):
101
+ continue
102
+ except ValueError:
103
+ pass
104
+ if (h, a) == (home, away):
105
+ label = "THIS MATCH"
106
+ else:
107
+ label = k[:16].replace("T", " ")
108
+ upcoming.append(f"{h} vs {a} ({label})")
109
+
110
+ parts = [
111
+ f"Group-stage cluster around {home_name} / {away_name}: {', '.join(sorted(group_teams))}",
112
+ ]
113
+ if played:
114
+ parts.append("Tournament results so far:\n" + "\n".join(f" • {p}" for p in played))
115
+ if upcoming:
116
+ parts.append("Related fixtures:\n" + "\n".join(f" • {u}" for u in upcoming[:6]))
117
+ return "\n".join(parts)
118
+
119
+
120
+ def fetch_espn_tournament_form(home: str, away: str, kickoff: str) -> str:
121
+ """Free ESPN scoreboard — recent World Cup results for both teams."""
122
+ try:
123
+ kickoff_dt = datetime.fromisoformat(kickoff.replace("Z", "+00:00"))
124
+ except ValueError:
125
+ kickoff_dt = datetime.now(timezone.utc)
126
+
127
+ teams = {home, away}
128
+ lines = []
129
+ url = "https://site.api.espn.com/apis/site/v2/sports/soccer/fifa.world/scoreboard"
130
+
131
+ for delta in range(14):
132
+ day = (kickoff_dt - timedelta(days=delta)).strftime("%Y%m%d")
133
+ try:
134
+ resp = requests.get(url, params={"dates": day}, timeout=12)
135
+ resp.raise_for_status()
136
+ data = resp.json()
137
+ except Exception:
138
+ continue
139
+
140
+ for event in data.get("events", []):
141
+ comps = event.get("competitions", [{}])
142
+ if not comps:
143
+ continue
144
+ comp = comps[0]
145
+ competitors = comp.get("competitors", [])
146
+ if len(competitors) != 2:
147
+ continue
148
+ abbrevs = {
149
+ c["homeAway"]: c["team"].get("abbreviation", "").upper() for c in competitors
150
+ }
151
+ if abbrevs.get("home") not in teams and abbrevs.get("away") not in teams:
152
+ continue
153
+ status = comp.get("status", {}).get("type", {})
154
+ if not status.get("completed", False):
155
+ continue
156
+ scores = {c["homeAway"]: c.get("score", "?") for c in competitors}
157
+ date = event.get("date", day)[:10]
158
+ lines.append(
159
+ f"{date}: {abbrevs.get('home')} {scores.get('home')}-{scores.get('away')} "
160
+ f"{abbrevs.get('away')}"
161
+ )
162
+
163
+ if not lines:
164
+ return "(no completed ESPN World Cup results found for these teams yet)"
165
+ return "ESPN tournament results:\n" + "\n".join(f" • {ln}" for ln in lines[:12])
166
+
167
+
168
+ def _parse_json_response(text: str) -> dict:
169
+ raw = text.strip()
170
+ raw = re.sub(r"^```[a-z]*\n?", "", raw)
171
+ raw = re.sub(r"\n?```$", "", raw)
172
+ return json.loads(raw)
173
+
174
+
175
+ def synthesize_evidence(
176
+ match: str,
177
+ home_name: str,
178
+ away_name: str,
179
+ kickoff: str,
180
+ strategy: str,
181
+ context_text: str,
182
+ learning_context: str,
183
+ fixture_context: str,
184
+ espn_form: str,
185
+ useful_count: int,
186
+ total_sources: int,
187
+ retroactive: bool,
188
+ ) -> dict:
189
+ retro = (
190
+ "RETROACTIVE: simulate pre-match analysis only — ignore any post-match scores in sources."
191
+ if retroactive
192
+ else ""
193
+ )
194
+ prompt = f"""You are a football data analyst. Extract structured evidence from research for {match}.
195
+ Kickoff: {kickoff}
196
+ {retro}
197
+
198
+ Strategy rules to apply:
199
+ {strategy or "(none yet)"}
200
+
201
+ Agent track record (learn from past mistakes):
202
+ {learning_context}
203
+
204
+ Fixture / group context:
205
+ {fixture_context}
206
+
207
+ ESPN results:
208
+ {espn_form}
209
+
210
+ Purchased research ({useful_count}/{total_sources} useful sources):
211
+ {context_text}
212
+
213
+ Return ONLY valid JSON:
214
+ {{
215
+ "data_quality": "high|medium|low",
216
+ "home_form": "one sentence",
217
+ "away_form": "one sentence",
218
+ "key_injuries": ["bullet"],
219
+ "tactical_matchup": "one sentence — who has structural edge",
220
+ "group_stakes": "one sentence — what each team needs",
221
+ "home_win_signals": ["specific evidence bullets"],
222
+ "away_win_signals": ["specific evidence bullets"],
223
+ "draw_signals": ["specific evidence bullets"],
224
+ "contradictions": ["conflicting signals if any"],
225
+ "strategy_applied": ["which strategy rules matter here"]
226
+ }}"""
227
+
228
+ text = gemini.generate(prompt, temperature=0.3, json_mode=True)
229
+ return _parse_json_response(text)
230
+
231
+
232
+ def stress_test_evidence(
233
+ match: str,
234
+ home_name: str,
235
+ away_name: str,
236
+ synthesis: dict,
237
+ strategy: str,
238
+ ) -> dict:
239
+ prompt = f"""You are a skeptical betting analyst reviewing a colleague's match brief for {match}.
240
+
241
+ Strategy:
242
+ {strategy or "(none)"}
243
+
244
+ Colleague's synthesis:
245
+ {json.dumps(synthesis, indent=2)}
246
+
247
+ Challenge weak reasoning. Find overlooked risks. Do NOT invent facts not implied by the synthesis.
248
+
249
+ Return ONLY valid JSON:
250
+ {{
251
+ "blind_spots": ["what the synthesis may be overweighting"],
252
+ "underweighted_factors": ["factors that could flip the result"],
253
+ "draw_risk": "low|medium|high — with one sentence why",
254
+ "favorite": "home|away|none",
255
+ "confidence_cap": 1-10 integer — max justified confidence given gaps,
256
+ "verdict": "one sentence overall assessment"
257
+ }}"""
258
+
259
+ text = gemini.generate(prompt, temperature=0.4, json_mode=True)
260
+ return _parse_json_response(text)
261
+
262
+
263
+ def make_final_prediction(
264
+ match: str,
265
+ home: str,
266
+ away: str,
267
+ home_name: str,
268
+ away_name: str,
269
+ kickoff: str,
270
+ strategy: str,
271
+ synthesis: dict,
272
+ stress_test: dict,
273
+ useful_count: int,
274
+ total_sources: int,
275
+ ) -> str:
276
+ prompt = f"""You are a World Cup match predictor. Make a calibrated prediction for {match}.
277
+ Home: {home_name} ({home})
278
+ Away: {away_name} ({away})
279
+ Kickoff: {kickoff}
280
+
281
+ Strategy:
282
+ {strategy or "(none)"}
283
+
284
+ Evidence synthesis:
285
+ {json.dumps(synthesis, indent=2)}
286
+
287
+ Stress-test review:
288
+ {json.dumps(stress_test, indent=2)}
289
+
290
+ Research quality: {useful_count}/{total_sources} useful sources.
291
+
292
+ PROCESS (think through this, then output the format lines):
293
+ 1. Estimate win probabilities (integers 0-100, must sum to 100).
294
+ 2. PICK = outcome with highest probability (if within 5% of second-best, prefer draw only when draw_signals dominate).
295
+ 3. CONFIDENCE must respect stress_test.confidence_cap and data_quality:
296
+ - high quality + cap 8+ → use 7-10 when probability spread ≥ 15%
297
+ - medium → 5-7
298
+ - low → 3-5
299
+ - Never use 5 as a default — justify the number.
300
+ 4. Do NOT pick draw at 5/10 unless draw probability is clearly highest OR home/away within 5% and draw_signals are strongest.
301
+
302
+ End with EXACTLY these lines:
303
+ HOME_PCT: [0-100]
304
+ DRAW_PCT: [0-100]
305
+ AWAY_PCT: [0-100]
306
+ PICK: [home|away|draw]
307
+ CONFIDENCE: [1-10]
308
+ CONFIDENCE_REASON: [one sentence]
309
+ REASONING: [one sentence on key factor]"""
310
+
311
+ return gemini.generate(prompt, temperature=0.35)
312
+
313
+
314
+ def confidence_from_probs(probs: dict[str, int], pick: str, cap: int | None = None) -> int:
315
+ """Map probability distribution to 1-10 confidence."""
316
+ p = probs.get(pick, 0)
317
+ ordered = sorted(probs.values(), reverse=True)
318
+ spread = ordered[0] - ordered[1] if len(ordered) > 1 else ordered[0]
319
+
320
+ if p >= 62:
321
+ base = 8
322
+ elif p >= 52:
323
+ base = 7
324
+ elif p >= 42:
325
+ base = 6
326
+ elif p >= 36:
327
+ base = 5
328
+ else:
329
+ base = 4
330
+
331
+ if spread >= 28:
332
+ base += 2
333
+ elif spread >= 18:
334
+ base += 1
335
+ elif spread < 8:
336
+ base -= 1
337
+
338
+ conf = max(1, min(10, base))
339
+ if cap is not None:
340
+ conf = min(conf, max(1, min(10, int(cap))))
341
+ return conf
342
+
343
+
344
+ def parse_prediction_response(text: str, stress_cap: int | None = None) -> dict:
345
+ def _parse(pattern: str, default: str = "") -> str:
346
+ m = re.search(pattern, text, re.IGNORECASE)
347
+ return m.group(1).strip() if m else default
348
+
349
+ home_pct = int(_parse(r"HOME_PCT:\s*(\d+)", "34") or 34)
350
+ draw_pct = int(_parse(r"DRAW_PCT:\s*(\d+)", "33") or 33)
351
+ away_pct = int(_parse(r"AWAY_PCT:\s*(\d+)", "33") or 33)
352
+ total = home_pct + draw_pct + away_pct
353
+ if total != 100 and total > 0:
354
+ home_pct = round(100 * home_pct / total)
355
+ draw_pct = round(100 * draw_pct / total)
356
+ away_pct = 100 - home_pct - draw_pct
357
+
358
+ probs = {"home": home_pct, "draw": draw_pct, "away": away_pct}
359
+ pick_raw = _parse(r"PICK:\s*(\w+)", "home").lower()
360
+ pick = pick_raw if pick_raw in ("home", "away", "draw") else max(probs, key=probs.get)
361
+
362
+ model_conf = _parse(r"CONFIDENCE:\s*(\d+)", "")
363
+ if model_conf.isdigit():
364
+ confidence = max(1, min(10, int(model_conf)))
365
+ if stress_cap is not None:
366
+ confidence = min(confidence, stress_cap)
367
+ else:
368
+ confidence = confidence_from_probs(probs, pick, stress_cap)
369
+
370
+ return {
371
+ "pick": pick,
372
+ "confidence": confidence,
373
+ "confidence_reason": _parse(r"CONFIDENCE_REASON:\s*(.+)", ""),
374
+ "reasoning": _parse(r"REASONING:\s*(.+)", "Insufficient data for strong prediction"),
375
+ "probabilities": probs,
376
+ "full_reasoning": text,
377
+ }
templates/index.html CHANGED
@@ -4,6 +4,7 @@
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <title>⚽ World Cup Prediction Agent</title>
 
7
  <style>
8
  * { box-sizing: border-box; margin: 0; padding: 0; }
9
  body { background: #0d0d0d; color: #e0e0e0; font-family: 'JetBrains Mono', 'Fira Code', monospace; font-size: 14px; line-height: 1.6; }
@@ -72,6 +73,7 @@
72
  .strategy-box { background: #111; border: 1px solid #2a2a2a; border-radius: 6px; padding: 16px; }
73
  pre { white-space: pre-wrap; word-wrap: break-word; color: #bbb; font-size: 13px; }
74
  .strategy-empty { color: #444; font-style: italic; }
 
75
 
76
  .history-item { border-bottom: 1px solid #1a1a1a; padding: 10px 0; }
77
  .history-match { font-size: 12px; color: #888; margin-bottom: 6px; }
@@ -81,6 +83,13 @@
81
  .detail-section { margin-bottom: 24px; }
82
  .detail-section h3 { font-size: 12px; color: #555; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; }
83
  .full-text { font-size: 12px; color: #aaa; white-space: pre-wrap; background: #0a0a0a; border: 1px solid #1e1e1e; border-radius: 4px; padding: 12px; max-height: 400px; overflow-y: auto; }
 
 
 
 
 
 
 
84
  </style>
85
  </head>
86
  <body>
@@ -89,10 +98,6 @@
89
  <header>
90
  <h1>⚽ World Cup Prediction Agent</h1>
91
  <div class="meta">
92
- {% if stats %}
93
- <div>Record: <span>{{ stats.wins }}W–{{ stats.losses }}L ({{ stats.pct }})</span></div>
94
- <div>Matches predicted: <span>{{ stats.total }}</span></div>
95
- {% endif %}
96
  <div><a href="/">Dashboard</a> · <a href="/strategy">Strategy</a></div>
97
  </div>
98
  </header>
@@ -132,7 +137,7 @@
132
  <div class="pred-item"><div class="pred-label">Bet Size</div><div class="pred-value">${{ pred.bet }}</div></div>
133
  <div class="pred-item"><div class="pred-label">Kickoff</div><div class="pred-value" style="font-size:12px;">{{ r.kickoff }}</div></div>
134
  </div>
135
- <div class="reasoning">{{ pred.reasoning }}</div>
136
  </div>
137
 
138
  <div class="detail-section">
@@ -164,20 +169,20 @@
164
 
165
  <div class="detail-section">
166
  <h3>Full Gemini Reasoning</h3>
167
- <div class="full-text">{{ r.full_reasoning }}</div>
168
  </div>
169
 
170
  {% if r.evaluation %}
171
  <div class="detail-section">
172
  <h3>Post-Match Evaluation</h3>
173
- <div class="full-text">{{ r.evaluation }}</div>
174
  </div>
175
  {% endif %}
176
 
177
  {% if r.strategy_snapshot %}
178
  <div class="detail-section">
179
  <h3>Strategy at Time of Prediction</h3>
180
- <div class="full-text">{{ r.strategy_snapshot if r.strategy_snapshot else "(no strategy yet at time of prediction)" }}</div>
181
  </div>
182
  {% endif %}
183
 
@@ -187,7 +192,7 @@
187
  <h2>Current Strategy</h2>
188
  <div class="strategy-box">
189
  {% if strategy %}
190
- <pre>{{ strategy }}</pre>
191
  {% else %}
192
  <div class="strategy-empty">No strategy yet — will be written after the first match reflection.</div>
193
  {% endif %}
@@ -200,7 +205,7 @@
200
  {% for item in strategy_history | reverse %}
201
  <div class="history-item">
202
  <div class="history-match">After {{ item.match }} ({{ item.kickoff[:10] if item.kickoff else '?' }})</div>
203
- <div class="history-snapshot">{{ item.snapshot[:300] if item.snapshot else "(empty at this point)" }}{% if item.snapshot and item.snapshot | length > 300 %}…{% endif %}</div>
204
  </div>
205
  {% endfor %}
206
  {% endif %}
@@ -208,23 +213,6 @@
208
  {% else %}
209
  <!-- ─── Dashboard ─── -->
210
 
211
- {% if upcoming %}
212
- <div class="section">
213
- <h2>Upcoming Matches</h2>
214
- <div class="upcoming-grid">
215
- {% for f in upcoming %}
216
- <div class="upcoming-item">
217
- <div>
218
- <span class="teams">{{ f.home }} vs {{ f.away }}</span>
219
- <span class="stage" style="margin-left:8px;">{{ f.stage }}</span>
220
- </div>
221
- <div class="kick">{{ f.kickoff_utc[:16].replace("T", " ") }} UTC</div>
222
- </div>
223
- {% endfor %}
224
- </div>
225
- </div>
226
- {% endif %}
227
-
228
  {% if results %}
229
  <div class="section">
230
  <h2>Predictions</h2>
@@ -256,7 +244,7 @@
256
  <div class="pred-item"><div class="pred-label">Bet</div><div class="pred-value">${{ pred.bet }}</div></div>
257
  <div class="pred-item"><div class="pred-label">Research cost</div><div class="pred-value" style="color:#f9a825;">${{ "%.4f" | format(r.research_cost) }}</div></div>
258
  </div>
259
- <div class="reasoning">"{{ pred.reasoning }}"</div>
260
 
261
  <!-- x402 purchase log -->
262
  {% if r.services_used %}
@@ -268,7 +256,7 @@
268
  <tr>
269
  <td>{{ svc.source }}</td>
270
  <td class="cost">${{ "%.4f" | format(svc.cost) }}</td>
271
- <td>{{ svc.get('reason', '') }}</td>
272
  </tr>
273
  {% endfor %}
274
  </table>
@@ -283,7 +271,7 @@
283
  <div class="result-bar {{ 'correct' if r.correct else 'incorrect' }}" style="margin-top:10px;">
284
  Result: <span class="result-score">{{ r.home }} {{ res.home_score }}–{{ res.away_score }} {{ r.away }}</span>
285
  {% if r.evaluation %}
286
- <div class="evaluation">{{ r.evaluation[:200] }}{% if r.evaluation | length > 200 %}…{% endif %}</div>
287
  {% endif %}
288
  </div>
289
  {% endif %}
@@ -300,13 +288,30 @@
300
  </div>
301
  {% endif %}
302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  {% if strategy %}
304
  <div class="section">
305
  <h2>Current Strategy <a href="/strategy" style="font-size:11px;color:#555;font-weight:normal;margin-left:8px;">full history →</a></h2>
306
  <div class="strategy-box">
307
- <pre>{{ strategy[:600] }}{% if strategy | length > 600 %}
308
 
309
- <a href="/strategy">… read more</a>{% endif %}</pre>
310
  </div>
311
  </div>
312
  {% endif %}
@@ -314,5 +319,10 @@
314
  {% endif %}
315
 
316
  </div>
 
 
 
 
 
317
  </body>
318
  </html>
 
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <title>⚽ World Cup Prediction Agent</title>
7
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
8
  <style>
9
  * { box-sizing: border-box; margin: 0; padding: 0; }
10
  body { background: #0d0d0d; color: #e0e0e0; font-family: 'JetBrains Mono', 'Fira Code', monospace; font-size: 14px; line-height: 1.6; }
 
73
  .strategy-box { background: #111; border: 1px solid #2a2a2a; border-radius: 6px; padding: 16px; }
74
  pre { white-space: pre-wrap; word-wrap: break-word; color: #bbb; font-size: 13px; }
75
  .strategy-empty { color: #444; font-style: italic; }
76
+ .strategy-md { color: #bbb; font-size: 13px; line-height: 1.7; }
77
 
78
  .history-item { border-bottom: 1px solid #1a1a1a; padding: 10px 0; }
79
  .history-match { font-size: 12px; color: #888; margin-bottom: 6px; }
 
83
  .detail-section { margin-bottom: 24px; }
84
  .detail-section h3 { font-size: 12px; color: #555; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; }
85
  .full-text { font-size: 12px; color: #aaa; white-space: pre-wrap; background: #0a0a0a; border: 1px solid #1e1e1e; border-radius: 4px; padding: 12px; max-height: 400px; overflow-y: auto; }
86
+ .render-md { white-space: normal; }
87
+ .render-md p { margin: 6px 0; }
88
+ .render-md h1, .render-md h2, .render-md h3 { color: #e0e0e0; margin: 12px 0 6px; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 1px solid #2a2a2a; padding-bottom: 4px; }
89
+ .render-md strong { color: #fff; }
90
+ .render-md ul, .render-md ol { padding-left: 20px; margin: 4px 0; }
91
+ .render-md li { margin: 2px 0; }
92
+ .render-md a { color: #4dabf7; }
93
  </style>
94
  </head>
95
  <body>
 
98
  <header>
99
  <h1>⚽ World Cup Prediction Agent</h1>
100
  <div class="meta">
 
 
 
 
101
  <div><a href="/">Dashboard</a> · <a href="/strategy">Strategy</a></div>
102
  </div>
103
  </header>
 
137
  <div class="pred-item"><div class="pred-label">Bet Size</div><div class="pred-value">${{ pred.bet }}</div></div>
138
  <div class="pred-item"><div class="pred-label">Kickoff</div><div class="pred-value" style="font-size:12px;">{{ r.kickoff }}</div></div>
139
  </div>
140
+ <div class="reasoning render-md">{{ pred.reasoning }}</div>
141
  </div>
142
 
143
  <div class="detail-section">
 
169
 
170
  <div class="detail-section">
171
  <h3>Full Gemini Reasoning</h3>
172
+ <div class="full-text render-md">{{ r.full_reasoning }}</div>
173
  </div>
174
 
175
  {% if r.evaluation %}
176
  <div class="detail-section">
177
  <h3>Post-Match Evaluation</h3>
178
+ <div class="full-text render-md">{{ r.evaluation }}</div>
179
  </div>
180
  {% endif %}
181
 
182
  {% if r.strategy_snapshot %}
183
  <div class="detail-section">
184
  <h3>Strategy at Time of Prediction</h3>
185
+ <div class="full-text render-md">{{ r.strategy_snapshot if r.strategy_snapshot else "(no strategy yet at time of prediction)" }}</div>
186
  </div>
187
  {% endif %}
188
 
 
192
  <h2>Current Strategy</h2>
193
  <div class="strategy-box">
194
  {% if strategy %}
195
+ <div class="render-md strategy-md">{{ strategy }}</div>
196
  {% else %}
197
  <div class="strategy-empty">No strategy yet — will be written after the first match reflection.</div>
198
  {% endif %}
 
205
  {% for item in strategy_history | reverse %}
206
  <div class="history-item">
207
  <div class="history-match">After {{ item.match }} ({{ item.kickoff[:10] if item.kickoff else '?' }})</div>
208
+ <div class="history-snapshot render-md">{{ item.snapshot[:300] if item.snapshot else "(empty at this point)" }}{% if item.snapshot and item.snapshot | length > 300 %}…{% endif %}</div>
209
  </div>
210
  {% endfor %}
211
  {% endif %}
 
213
  {% else %}
214
  <!-- ─── Dashboard ─── -->
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  {% if results %}
217
  <div class="section">
218
  <h2>Predictions</h2>
 
244
  <div class="pred-item"><div class="pred-label">Bet</div><div class="pred-value">${{ pred.bet }}</div></div>
245
  <div class="pred-item"><div class="pred-label">Research cost</div><div class="pred-value" style="color:#f9a825;">${{ "%.4f" | format(r.research_cost) }}</div></div>
246
  </div>
247
+ <div class="reasoning render-md">{{ pred.reasoning }}</div>
248
 
249
  <!-- x402 purchase log -->
250
  {% if r.services_used %}
 
256
  <tr>
257
  <td>{{ svc.source }}</td>
258
  <td class="cost">${{ "%.4f" | format(svc.cost) }}</td>
259
+ <td>{{ svc.reason if svc.reason is defined else '' }}</td>
260
  </tr>
261
  {% endfor %}
262
  </table>
 
271
  <div class="result-bar {{ 'correct' if r.correct else 'incorrect' }}" style="margin-top:10px;">
272
  Result: <span class="result-score">{{ r.home }} {{ res.home_score }}–{{ res.away_score }} {{ r.away }}</span>
273
  {% if r.evaluation %}
274
+ <div class="evaluation render-md">{{ r.evaluation[:200] }}{% if r.evaluation | length > 200 %}…{% endif %}</div>
275
  {% endif %}
276
  </div>
277
  {% endif %}
 
288
  </div>
289
  {% endif %}
290
 
291
+ {% if upcoming %}
292
+ <div class="section">
293
+ <h2>Upcoming Matches</h2>
294
+ <div class="upcoming-grid">
295
+ {% for f in upcoming %}
296
+ <div class="upcoming-item">
297
+ <div>
298
+ <span class="teams">{{ f.home }} vs {{ f.away }}</span>
299
+ <span class="stage" style="margin-left:8px;">{{ f.stage }}</span>
300
+ </div>
301
+ <div class="kick">{{ f.kickoff_utc[:16].replace("T", " ") }} UTC</div>
302
+ </div>
303
+ {% endfor %}
304
+ </div>
305
+ </div>
306
+ {% endif %}
307
+
308
  {% if strategy %}
309
  <div class="section">
310
  <h2>Current Strategy <a href="/strategy" style="font-size:11px;color:#555;font-weight:normal;margin-left:8px;">full history →</a></h2>
311
  <div class="strategy-box">
312
+ <div class="render-md strategy-md">{{ strategy[:600] }}{% if strategy | length > 600 %}
313
 
314
+ [… read more](/strategy){% endif %}</div>
315
  </div>
316
  </div>
317
  {% endif %}
 
319
  {% endif %}
320
 
321
  </div>
322
+ <script>
323
+ document.querySelectorAll('.render-md').forEach(function(el) {
324
+ el.innerHTML = marked.parse(el.textContent);
325
+ });
326
+ </script>
327
  </body>
328
  </html>
thumbnail.png ADDED